4. Express.
js
Most important for backend.
Let’s learn how to create a server in both:
1️⃣ [Link] (core module)
2️⃣ [Link] (most common and easy way)
I will explain both with simple examples 👇
⭐ 1️⃣ Creating a Server using [Link] (HTTP Module)
[Link] comes with a built-in module called http.
// [Link]
const http = require('http');
const server = [Link]((req, res) => {
[Link]("Hello from Node Server");
[Link]();
});
[Link](5000, () => {
[Link]("Server is running on port 5000");
});
Run the server:
node [Link]
Open in browser:
[Link]
✔ Server created without any external package
❌ But handling routes manually becomes hard
⭐ 2️⃣ Creating a Server using [Link] (Recommended)
Express makes creating API routes very easy.
Step 1: Install Express
npm install express
Step 2: Create server file
// [Link]
const express = require('express');
const app = express();
[Link]('/', (req, res) => {
[Link]("Hello from Express Server");
});
[Link](5000, () => {
[Link]("Server running on port 5000");
});
Run:
node [Link]
Open:
[Link]
✔ Very easy routing
✔ JSON support
✔ Middleware support
✔ Used in real projects (MERN stack)
⭐ Add JSON API Route Example
[Link]('/users', (req, res) => {
[Link]([
{ id: 1, name: "Siri" },
{ id: 2, name: "Akka" }
]);
});
Visit:
[Link]
You will see JSON 👌
📝 Summary
[Link] HTTP [Link]
Feature
Server Server
Difficulty Harder Easier
Routing Manual Simple
Middlewar
No Yes
e
Best Use Learning basics Real projects
Most developers use [Link] because it saves time and code.
[Link](5000, () => {...}) Explanation
This line starts the server and makes it listen for incoming
client requests.
5000 → Server runs on port 5000
() => { [Link](...) } → Callback function executed
when the server starts successfully
🔹 What is a Port?
A port is like a door number through which a server receives
requests.
Example:
[Link]
Here 5000 is the port.
Common ports:
Por
Usage
t
300 Most React apps during
0 development
500
Many Node/Express servers
0
80 HTTP default
443 HTTPS default
🔹 Full Line Meaning
[Link](5000, () => {
[Link]("Server running on port 5000");
});
✔ Start Express server
✔ Keep it running and listening on port 5000
✔ When server starts → print message in console
🔹 Without Callback
[Link](5000);
Server still runs ✔
But no message shown ❌
🔹 Why a callback function?
Because starting a server is asynchronous
→ Callback runs after the server starts
🎯 In Simple Words
Code Meaning
[Link]
Start the server
()
5000 Port number
Run after server
Callback
starts
🔥 Real example output
Server running on port 5000
Now you can open your server in the browser.
⭐ What are Routers in [Link]?
Routers are used to organize API routes in separate
files instead of keeping everything inside [Link].
✔ Makes code clean
✔ Easy to manage large projects
✔ Helps separate different features (users, products, orders
etc.)
🔥 Without Router (everything in one file ❌)
const express = require("express");
const app = express();
[Link]("/users", (req, res) => {
[Link]("All Users");
});
[Link]("/products", (req, res) => {
[Link]("All Products");
});
[Link](5000);
When APIs grow → the file becomes messy and hard to
read.
🟢 Using Router (Best Practice ✔)
We separate routes into different files.
📌 Step 1: Create a Router file
[Link]
const express = require("express");
const router = [Link]();
[Link]("/", (req, res) => {
[Link]("All Users");
});
[Link]("/:id", (req, res) => {
[Link](`User ID: ${[Link]}`);
});
[Link] = router;
📌 Step 2: Use this router in main file
[Link]
const express = require("express");
const app = express();
const userRoutes = require("./users");
// use() → mounts router
[Link]("/users", userRoutes);
[Link](5000, () => [Link]("Server running"));
🧠 What happens now?
Request → [Link]
Response → "All Users"
Request → [Link]
Response → "User ID: 10"
⭐ Why Routers are useful?
Without Router With Router
All API code in one Code split into multiple
Without Router With Router
file files
Hard to maintain Easy to scale
Messy project Clean folder structure
📂 Typical Folder Structure in Express App
project/
│
├─ [Link]
├─ routes/
│ ├─ [Link]
│ ├─ [Link]
└─ controllers/
├─ [Link]
This is what we use in real MERN projects.
🎯 Summary
Term Meaning
Helps create separate mini-apps with
Router
their own routes
[Link]
Creates a router object
r()
[Link]() Mount router on a path
⭐ What is Middleware in [Link]?
Middleware is a function that runs between the request and
the response.
📌 It gets access to:
req → Request object
res → Response object
next() → Pass control to next middleware or route
🔹 Simple Definition
Middleware is like a checkpoint between client request and
server response.
We use it to:
Check authentication (is user logged in?)
Log request details
Parse JSON body
Error handling
Validate input data
Handle CORS
Add headers
🔥 Basic Middleware Example
const express = require("express");
const app = express();
const myMiddleware = (req, res, next) => {
[Link]("Middleware executed");
next(); // continue to next step
};
[Link](myMiddleware);
[Link]("/", (req, res) => {
[Link]("Home Page");
});
[Link](5000);
📌 Output in terminal when opening /
Middleware executed
→ Then the response is sent
🔹 Why next() is important?
If we don’t call next():
Request will get stuck
Response will never be sent
So middleware must call next() (except in error or response
cases)
🔹 Built-in Middleware Example
To handle JSON request body:
[Link]([Link]());
Now Express can read:
[Link]
🔹 Route-Level Middleware
Middleware applied to specific routes:
const checkUser = (req, res, next) => {
[Link]("Checking User Authentication...");
next();
};
[Link]("/profile", checkUser, (req, res) => {
[Link]("Profile Page");
});
Only /profile uses this middleware ✔
🔹 Error-Handling Middleware
Special middleware with 4 parameters:
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).send("Something broke!");
});
Used when something goes wrong in the server.
⭐ Summary
Feature Meaning
Middlewar Function that runs before sending
e response
next() Move to next middleware or route
Feature Meaning
Can Auth, logging, validation, parsing,
handle errors
Used with [Link](), routes
Middleware = Powerful tool to control server behavior in real
apps
[Link]() — Simple Notes
⭐ What is it?
A built-in middleware in [Link] that parses JSON data
coming from the client.
⭐ Why use it?
To access the data sent in the request body using:
[Link]
⭐ Without [Link]()
[Link] // undefined ❌
⭐ With [Link]()
[Link]([Link]());
[Link] // { name: "Siri", age: 20 } ✔
⭐ Example
[Link]([Link]());
[Link]("/login", (req, res) => {
[Link]([Link]); // Works!
[Link]("Received!");
});
⭐ It does NOT:
🚫 Convert objects to JSON
🚫 Send data to client
✔ It only reads JSON from incoming requests
🎯 Final Line to Remember
[Link]() converts JSON request body → JavaScript
object in [Link]
⭐ Error-Handling Middleware — Simple Notes
Error-handling middleware is a special type of middleware
that catches and handles errors in Express.
📌 It has 4 parameters:
(err, req, res, next)
If your middleware has 4 arguments, Express knows:
➡️This middleware is for handling errors
🔹 Basic Example
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).send("Something went wrong!");
});
🔥 How does a normal error go to this middleware?
You must call:
next(err);
Example route:
[Link]("/", (req, res, next) => {
const error = new Error("Test Error");
next(error); // send error to error-handling middleware
});
Now the error middleware will catch it.
🔹 Why use error-handling middleware?
✔ To avoid server crash
✔ To send a proper error response
✔ To log errors in one place
✔ To improve debugging
✔ To secure server by not exposing code details
⭐ Example with Status Code and JSON Response
[Link]((err, req, res, next) => {
[Link]([Link] || 500).json({
success: false,
message: [Link] || "Server Error"
});
});
You can customize errors easily.
🔹 Order is important!
Error-handling middleware should be placed:
✔ After all routes
❌ Not before routes
// routes here...
// error handling middleware always at the end
[Link]((err, req, res, next) => {
[Link](500).send("Error occurred!");
});
🎯 Summary
Feature Meaning
4
(err, req, res, next)
parameters
Server errors in one
Handles
place
Must be
After routes
last
Triggered
next(err)
by
⭐ Final Line to Remember
Error-handling middleware catches all errors and
prevents server crash.
CORS in [Link] — Simple Notes
⭐ What is CORS?
CORS = Cross-Origin Resource Sharing
Used to allow a frontend (React, etc.) to access a backend
API running on a different origin (domain/port).
Example:
Frontend: [Link]
Backend: [Link]
Browser blocks by default ❌
CORS allows it ✔
🔥 How to enable CORS in Express
Step 1: Install
npm install cors
Step 2: Use middleware
const cors = require("cors");
[Link](cors());
✔ Allows all origins (good for development)
🔹 Allow only specific frontend origin
[Link](cors({
origin: "[Link]
}));
🔹 Allow specific methods/headers
[Link](cors({
origin: "[Link]
methods: ["GET", "POST", "PUT", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"]
}));
🎯 Summary
Concept Meaning
Allow/block frontend access to
CORS
backend
[Link](cors
Allow all origins
())
origin Only allow specific frontend
Why
Browser security rule
needed?
⭐ One Line Summary
CORS in Express enables secure communication
between different origins.
⭐ Body Parsers — Simple Notes
A Body Parser is a middleware that helps Express read the
data inside the request body.
When a frontend sends data (like JSON or form data),
the backend needs a way to convert that data into a usable
format in [Link].
📌 Without body parser:
[Link] // undefined ❌
📌 With body parser:
[Link] // shows the data ✔
🔹 Built-in Body Parsers in Express
Middleware Used For
[Link]() Parse JSON data
Middleware Used For
[Link] Parse form data (x-www-form-
d() urlencoded)
🔥 Example: Enable both
[Link]([Link]());
[Link]([Link]({ extended: true }));
🔹 JSON Body Example (Frontend → Backend)
Frontend (React)
fetch("/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: [Link]({ name: "Siri", age: 20 })
});
Backend (Express)
[Link]([Link]());
[Link]("/login", (req, res) => {
[Link]([Link]);
[Link]("Received");
});
Output in server:
{ name: "Siri", age: 20 }
🔹 Form Data Example
HTML form (default encoding)
<form action="/register" method="POST">
<input name="name" />
<button>Submit</button>
</form>
Then Express:
[Link]([Link]({ extended: true }));
⭐ Summary
Output
Body Parser Purpose
stored in
Reads JSON
[Link]() [Link]
data
[Link] Reads form
[Link]
d() data
Without them → Express cannot read body data.
🆚 Query Params vs Route Params
Both are used to send data to the backend, but they
are used in different situations.
🔹 1️⃣ Route Params (URL Parameters)
Used when the value is a part of the URL
Usually for identifying something specific (like a user or
product ID)
📌 Syntax: /:paramName
Example Route:
[Link]("/users/:id", (req, res) => {
[Link](`User ID is ${[Link]}`);
});
Request URL:
[Link]
✔ Output:
User ID is 10
📌 Used for:
Single user → /users/10
Product details → /product/121
🔹 2️⃣ Query Params
Used for filtering, searching, sorting
They appear after ? in the URL
📌 Syntax: ?key=value
Example Route:
[Link]("/search", (req, res) => {
[Link]([Link]);
});
Request URL:
[Link]
✔ Output:
{ "city": "Hyd", "age": "20" }
📌 Used for:
Search filters → ?city=Hyd
Pagination → ?page=2&limit=10
Sorting → ?sort=price
🔥 Quick Comparison Table
Query
Feature Route Params
Params
Location in
Inside path After ?
URL
/users?
Example /users/10
page=2
Identifying Filtering,
Used for
resource sorting
Access using [Link] [Link]
Required? Usually yes Optional
🎯 Simple Rule to Remember
Route Params → identify a specific thing
Example: which user → /users/10
Query Params → provide additional details
Example: how to filter/sort users → ?page=2&city=Hyd
🔐 Authentication Routes (Simple Notes)
Authentication routes are API endpoints used for user login,
register, and managing user sessions/tokens.
⭐ Basic Authentication Routes
Route Method Purpose
/ POST Create a new user account
Route Method Purpose
registe
r
/login POST Verify user & give token/cookie
POST/
/logout Remove token & logout user
GET
Get logged-in user details
/me GET
(protected)
🔹 /register → POST
User creates an account
Request body example:
{
"name": "Siri",
"email": "siri@[Link]",
"password": "123456"
}
Server response:
User registered successfully
🔹 /login → POST
User logs into website
Server checks:
✔ Email exists?
✔ Password correct?
If correct → server sends:
Session cookie
or
JWT token
🔹 /logout → POST
Server clears session/cookie and logs out user.
🔹 /me → GET (Protected Route)
Only logged-in users can access
Example response:
{
"name": "Siri",
"email": "siri@[Link]"
}
This uses auth middleware to verify token/session.
⭐ Example Express Router Structure
[Link]
const express = require("express");
const router = [Link]();
[Link]("/register", (req, res) => {
[Link]("User registered");
});
[Link]("/login", (req, res) => {
[Link]("User logged in");
});
[Link]("/me", (req, res) => {
[Link]("User details");
});
[Link]("/logout", (req, res) => {
[Link]("Logged out");
});
[Link] = router;
Then in main server:
const authRoutes = require("./authRoutes");
[Link]("/auth", authRoutes);
📌 Routes become:
/auth/register
/auth/login
/auth/me
/auth/logout
🎯 Why separate authentication routes?
✔ Clean code
✔ Reusable auth handler
✔ Easy to protect user-only routes
✔ Security and clarity
⭐ Summary
Route Function
Register Create account
Authenticate
Login
user
End session /
Logout
remove token
Me Return current
user details
Cookies — Simple Notes
⭐ What are Cookies?
Cookies are small pieces of data stored in
the browser by a website.
They are automatically sent back to the server
with every request.
🔹 Why do we need Cookies?
Because HTTP is stateless ❌
➡️Server does not remember who you are for
the next request
Cookies help the server remember the user
✔
🧠 What do cookies store?
Small info like:
Login session (user ID, auth token)
Preferences (theme, language)
Shopping cart data
Tracking info (analytics)
Route Function
📌 Sensitive info like passwords should NEVER
be stored in cookies
🔥 Common Usage Examples
Use Case Example
Keep user logged in even after
Login
closing browser
Ecommerce Save items in cart
Personalizati
Dark mode settings
on
Tracking Recently viewed items
🔹 How Cookies Work
1️⃣ User logs in
2️⃣ Server verifies user
3️⃣ Server sends a cookie with a unique
identifier
4️⃣ Browser stores the cookie
5️⃣ On next visit → Browser automatically
sends cookie back
6️⃣ Server checks cookie → User stays logged
in ✔
🔹 Example of a Cookie from Server
Set-Cookie: sessionId=123abc; HttpOnly; Max-
Age=604800
sessionId → a unique id for user
HttpOnly → JS cannot access (more
secure)
Route Function
Max-Age → Valid for 1 week
🔹 Simple Summary Table
Feature Description
Stored in Browser
Created by Server
Sent
With every request
automatically
Remember users & store
Purpose
small data
Best for Authentication & preferences
⭐ Final Line to Remember
Cookies allow websites to remember
users across multiple requests and visits.
That’s why when you open YouTube or
Instagram after a week — you are still logged
in 😊
Folder Structure for Express (Routes, Controllers,
Models)
This structure follows MVC pattern (Model–View–Controller)
⭐ Why use folder structure?
✔ Organizes code
✔ Easy to maintain
✔ Controller handles logic → Routes stay clean
✔ Models handle database communication
✔ Used in real production apps
📁 Recommended Folder Structure
project/
│
├─ [Link] --> Main entry file
│
├─ routes/
│ └─ [Link] --> All user-related endpoints
│
├─ controllers/
│ └─ [Link] --> Logic for each route
│
├─ models/
│ └─ [Link] --> Database schema (MongoDB example)
│
└─ middleware/
└─ [Link] --> Protect routes (optional)
🔹 Example Files
1️⃣ Route File → routes/[Link]
const express = require("express");
const { registerUser, loginUser } =
require("../controllers/userController");
const router = [Link]();
[Link]("/register", registerUser);
[Link]("/login", loginUser);
[Link] = router;
✔ Only defines endpoints
❌ No business logic here
2️⃣ Controller File → controllers/[Link]
[Link] = (req, res) => {
[Link]("User Registered");
};
[Link] = (req, res) => {
[Link]("User Logged In");
};
✔ Handles logic & calling models
✔ Cleaner separation
3️⃣ Model File → models/[Link]
const mongoose = require("mongoose");
const userSchema = [Link]({
name: String,
email: String,
password: String
});
[Link] = [Link]("User", userSchema);
✔ Database schema (MongoDB)
4️⃣ Main Server File → [Link]
const express = require("express");
const userRoutes = require("./routes/userRoutes");
const app = express();
[Link]([Link]());
[Link]("/api/users", userRoutes);
[Link](5000, () => [Link]("Server running"));
✔ Include routes
✔ Start server
✔ Middleware here
🎯 Summary Table
Part Contains Responsibility
Routes Endpoints Decide URL + method
Controller Actual logic (CRUD
Functions
s operations)
Database
Models Store data structure
schema
⭐ Final Line
A clean folder structure separates URL routing, business
logic, and database models → making code easy to scale and
maintain.