Server-side scripting, sessions and REST APIs notes — Unit 4
Free unit-wise study notes on server-side scripting, sessions and rest apis for Web Technology, Semester 5 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.
Server-side scripting, sessions and REST APIs
Notebook — 20 pages
Page 1
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
1. Server-Side Scripting Introduction
Unlike client-side scripts (JavaScript) which execute in the user's browser, server-side scripts execute on the web server before the response is sent back to the client.
⇒1.1 Why Server-Side?
Access to Databases: Client-side code cannot securely connect to a SQL database. Server-side code does.
Security: The source code of a server-side script is never seen by the user. Only the resulting HTML/JSON is sent.
File System Access: Reading/writing files on the server.
⇒1.2 Common Technologies
Historically: PHP, Java (Servlets/JSP), Python (Django), Ruby on Rails. Modern era: Node.js (JavaScript on the server), Go, Python (FastAPI).
Page 2
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
2. Node.js and Express.js
Node.js is a runtime environment that allows you to run JavaScript on the server. Express.js is a minimalist web framework built on top of Node.js.
⇒2.1 Basic Express Server
const express = require('express');
const app = express();
// Define a route
app.get('/', (req, res) => {
res.send('Hello from the Server!');
});
// Start listening
app.listen(3000, () => console.log('Running on port 3000'));
⇒2.2 The Request & Response Objects
`req` (Request): Contains data sent by the client (URL parameters, POST body data, HTTP headers, cookies).
`res` (Response): Contains methods to send data back (`res.send()`, `res.json()`, `res.redirect()`).
Page 3
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
3. HTTP Protocol Refresher
Server-side web development requires a deep understanding of HTTP (Hypertext Transfer Protocol). HTTP is stateless; the server forgets the client the moment the request ends.
⇒3.1 HTTP Methods (Verbs)
Method
Purpose
GET
Retrieve data from the server. (Should NEVER modify data).
POST
Submit new data to the server (e.g., form submission).
PUT
Update/Replace an entire existing resource.
PATCH
Partially update an existing resource.
DELETE
Remove a resource from the server.
⇒3.2 HTTP Status Codes
The server must reply with a status code indicating the result: 200 (OK), 201 (Created), 400 (Bad Request - client error), 401 (Unauthorized), 404 (Not Found), 500 (Internal Server Error).
Page 4
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
4. REST API Principles
REST (Representational State Transfer) is an architectural style for designing networked applications. APIs that follow these rules are called RESTful.
⇒4.1 Resource-Based Routing
In REST, URLs represent resources (nouns), not actions (verbs). The HTTP method defines the action.
BAD (RPC Style): `POST /deleteUser?id=123`
GOOD (RESTful): `DELETE /users/123`
⇒4.2 Standard RESTful Endpoints
`GET /articles` (Get all articles)
`POST /articles` (Create a new article)
`GET /articles/45` (Get article ID 45)
`PUT /articles/45` (Update article ID 45)
`DELETE /articles/45` (Delete article ID 45)
REST APIs communicate almost exclusively using JSON.
Page 5
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
5. Middleware
In Express and most modern web frameworks, Middleware is the backbone of request processing. A middleware is simply a function that has access to the request (`req`) and response (`res`) objects.
⇒5.1 The Middleware Pipeline
When a request arrives, it passes through a series of middleware functions in a pipeline. Each function can modify the request, send a response early, or pass control to the `next()` middleware.
// Custom Middleware
const logger = (req, res, next) => {
console.log(`Request made to: ${req.url}`);
next(); // Passes control to the next function
};
app.use(logger); // Apply globally
⇒5.2 Built-in and 3rd Party Middleware
`app.use(express.json())`: Automatically parses incoming JSON strings into JS objects.
`app.use(cors())`: Handles CORS headers automatically.
Page 6
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
6. State Management: Cookies
Because HTTP is stateless, the server does not remember if you logged in 5 minutes ago. Cookies were invented to solve this.
⇒6.1 How Cookies Work
1. The client makes a request.
2. The server responds and includes a `Set-Cookie` header (e.g., `Set-Cookie: userID=123`).
3. The browser saves this cookie to the user's hard drive.
4. For every subsequent request to that domain, the browser automatically attaches the `Cookie: userID=123` header.
5. The server reads the header and 'remembers' the user.
⇒6.2 Cookie Limitations and Security
Cookies are limited to 4KB. More importantly, users can easily modify them. If you store `isAdmin=false` in a cookie, a malicious user can edit it to `true` and hack your site. Therefore, never store sensitive logic in cookies.
Page 7
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
7. Server-Side Sessions
To safely manage state without trusting the client, we use Sessions.
⇒7.1 The Session Flow
1. User logs in with username/password.
2. Server verifies credentials.
3. Server creates a space in its RAM (or a database like Redis) to store data for this user (e.g., `isAdmin=true`).
4. Server generates a massive, random, unguessable string (the Session ID, e.g., `xyz987`).
5. Server sends a cookie to the client containing ONLY the Session ID (`Set-Cookie: session_id=xyz987`).
On the next request, the browser sends the Session ID back. The server looks up `xyz987` in its database, finds the associated data, and knows exactly who the user is. The user cannot tamper with the data because it is securely held on the server.
Page 8
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
8. Stateless Auth: JWT (JSON Web Tokens)
Sessions are stateful: the server must store the session data in memory. This becomes a nightmare to scale when you have millions of users and dozens of servers (Load Balancing). JWT is a stateless alternative.
⇒8.1 How JWT Works
Instead of storing data on the server, the server cryptographically signs a JSON payload and sends it to the client.
User logs in.
Server creates a JSON object: `{"userId": 123, "isAdmin": true}`.
Server signs this object using a secret key only the server knows, creating a JWT string.
Client stores the JWT (in localStorage or a cookie) and sends it in an `Authorization` header on future requests.
Server verifies the cryptographic signature. If it matches, the server knows the data wasn't tampered with, and logs the user in.
Because the data is embedded in the token itself, the server doesn't need to look up a database on every request. It just verifies the math.
Page 9
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
9. Database Integration
Server-side applications require databases to persist data permanently.
⇒9.1 Relational Databases (SQL)
MySQL, PostgreSQL. Data is stored in rigid tables with strict schemas and relationships (Foreign Keys). Used when data integrity and complex querying are paramount.
⇒9.2 NoSQL Databases
MongoDB. Data is stored as flexible, schema-less JSON-like documents. Highly scalable and fast, but lacks strict referential integrity. Very popular with Node.js stacks (the 'M' in MERN).
⇒9.3 ORMs and ODMs
Writing raw SQL strings inside JavaScript is error-prone. Object-Relational Mappers (ORM, like Prisma or Sequelize) or Object-Document Mappers (ODM, like Mongoose) allow developers to interact with the database using standard JavaScript methods.
Page 10
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
10. MVC Architecture in Web Apps
Model-View-Controller (MVC) is a software design pattern commonly used for developing web applications (e.g., Ruby on Rails, Django, Laravel).
⇒10.1 The Components
Model: Handles data logic. Interacts directly with the database. Defines the structure of the data (e.g., a `User` class).
View: The UI layer. Defines how the data is presented to the user (HTML templates).
Controller: The brain. Receives the HTTP request, asks the Model for data, processes it, and passes it to the View to be rendered.
In modern API-driven development (like a React app consuming a Node REST API), the backend only handles the Model and Controller, returning JSON instead of HTML. The View is handled entirely by the frontend framework.
Page 11
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
11. Template Engines (Server-Side Rendering)
Before React and SPAs, all HTML was generated dynamically on the server using Template Engines (like EJS, Pug, or Handlebars in Node).
⇒11.1 How they work
A template engine allows you to embed variables and logic (loops, if-statements) directly inside HTML-like files.
<!-- EJS Example -->
<ul>
<% for(let user of users) { %>
<li><%= user.name %> - <%= user.email %></li>
<% } %>
</ul>
The server queries the database, injects the resulting array into the template, compiles it into standard HTML, and sends the finished HTML string to the browser.
This is known as Server-Side Rendering (SSR). It is excellent for SEO because crawlers see fully formed HTML instantly.
Page 12
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
12. Input Validation (Server-Side)
As stated previously, client-side validation is for UX. Server-side validation is for security. You must assume all incoming data is malicious.
⇒12.1 Validation Checks
Before touching the database, the server must verify:
Required fields are present.
Data types are correct (e.g., age is actually a number, not a string).
Lengths are within limits (preventing buffer overflows or database crashes).
Formats are valid (e.g., valid email regex).
⇒12.2 Sanitization
Validation checks if data is valid. Sanitization actively modifies bad data into safe data (e.g., stripping `<script>` tags from a user's comment to prevent XSS). Libraries like `Joi` or `express-validator` are standard.
Page 13
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
13. Password Hashing
It is a cardinal sin of web development to store passwords in plain text in a database. If the database is breached, all user accounts are instantly compromised.
⇒13.1 Hashing vs Encryption
Encryption is two-way (data can be decrypted back to plain text). Hashing is one-way. A mathematical algorithm scrambles the password into a fixed-length string, and it is impossible to reverse the process.
⇒13.2 Salts and bcrypt
If two users have the password 'password123', they would have the same hash. Hackers use 'Rainbow Tables' (pre-computed lists of hashes) to crack them. To prevent this, a random string called a Salt is appended to the password before hashing.
Modern systems use libraries like `bcrypt` or `Argon2`. These algorithms are intentionally slow and computationally expensive, making brute-force cracking mathematically unfeasible.
Page 14
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
14. Handling File Uploads
Sending JSON is easy, but uploading a profile picture requires a different approach.
⇒14.1 Multipart/Form-Data
To upload files, the HTML form must use `enctype="multipart/form-data"`. This splits the HTTP request body into multiple parts, separating text fields from binary file data.
⇒14.2 Server-Side Processing (Multer)
Node.js cannot parse multipart data natively. Middleware like `multer` is used to intercept the incoming binary stream, save the file to the server's hard drive (or a cloud bucket like AWS S3), and then attach the file metadata (path, size, name) to the `req.file` object for the controller to save to the database.
Page 15
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
15. Pagination and Rate Limiting
⇒15.1 Pagination
If an API endpoint `GET /users` returns 1,000,000 records, the server will crash and the client will freeze. APIs must implement pagination.
Offset/Limit: Client requests `?limit=50&offset=100` (Give me 50 items, skipping the first 100).
Cursor-Based: Client passes an ID, server returns the next 50 items after that ID. (Much faster for massive datasets).
⇒15.2 Rate Limiting
To prevent Denial of Service (DoS) attacks or brute-forcing passwords, APIs must rate limit clients. Middleware tracks the IP address and blocks requests if they exceed a threshold (e.g., maximum 100 requests per minute).
Page 16
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
16. Webhooks
APIs allow you to pull data. Webhooks allow data to be pushed to you.
⇒16.1 How Webhooks Work
A webhook is essentially a 'Reverse API'. You provide a third-party service (like Stripe or GitHub) with a URL on your server. When a specific event happens on their end (e.g., a customer payment succeeds), they send an HTTP POST request to your server's URL containing the JSON data about the event.
This prevents you from having to constantly poll their API asking 'Did the payment succeed yet?'.
⇒16.2 Security
Because webhook endpoints must be public, you must verify the cryptographic signature sent in the headers to ensure the request actually came from Stripe, and not a malicious hacker trying to fake a successful payment.
Page 17
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
17. Caching Strategies
Database queries are the slowest part of a web request. Caching stores the results of expensive queries in blazing-fast RAM so subsequent requests don't hit the database.
⇒17.1 Redis
Redis is the industry standard in-memory Key-Value store used for caching.
The Cache-Aside Pattern:
1. App needs User 123.
2. App checks Redis. If found (Cache Hit), return data instantly.
3. If not found (Cache Miss), query SQL database.
4. Save the result into Redis with a Time-To-Live (TTL) of 5 minutes.
5. Return data. For the next 5 minutes, the database is safe from this query.
Page 18
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
18. Microservices Architecture (Web Context)
In modern large-scale web development, the backend is rarely a single monolithic Express.js server.
⇒18.1 Service Decomposition
The application is split into independent services (e.g., an Authentication Service, an Order Service, an Email Service). Each runs on its own server and has its own database.
⇒18.2 API Gateways
The frontend client does not communicate directly with 20 different microservices. It talks to a single API Gateway. The Gateway acts as a reverse proxy, authenticating the user, and routing the request to the correct internal microservice. This simplifies the frontend code immensely.
Page 19
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
19. GraphQL vs REST (Server Context)
⇒19.1 REST Limitations on Server
In REST, every endpoint (`/users`, `/posts`, `/comments`) has a dedicated controller function. If a frontend needs all three, it makes three requests, taxing the server's network layer.
⇒19.2 The GraphQL Approach
A GraphQL server exposes exactly one endpoint (usually `POST /graphql`).
The server defines a strict schema of all possible data. Instead of controller routes, developers write 'Resolvers'—functions that fetch specific pieces of data. When the single query arrives, the GraphQL engine parses it, executes only the necessary resolvers in parallel, stitches the data together into a perfect JSON tree, and returns it.
Page 20
Wink Notes
B.Tech CSE — 5th Semester
Web Technology
— Unit - 4 —
20. Serverless Computing (FaaS)
The newest paradigm in server-side development is 'Serverless' (Functions as a Service, like AWS Lambda).
⇒20.1 How it works
You do not write a monolithic Express app that listens on a port 24/7. Instead, you write individual JavaScript functions.
When an HTTP request arrives, the cloud provider (AWS) instantly boots up a micro-container, runs your single function, returns the response, and kills the container. You only pay for the exact milliseconds your code was executing.
⇒20.2 Pros and Cons
Pros: Infinite, automatic scaling. Zero server maintenance. Extremely cheap for low-traffic sites.
Cons: 'Cold Starts' (a slight delay when a function boots up after being idle). Unpredictable costs under heavy DoS attacks.