What is Middleware? | Lecture 11
1. What is Middleware?
Middleware
is a function that runs between the client request and the server response.
Flow:
Client Request → Middleware → Route → Response
Middleware
can:
- Execute code
- Modify request or response
objects
- End the request–response cycle
- Call the next middleware or
route
2. Why Do We Need Middleware?
Without
middleware:
- Code becomes repetitive
- Logic is mixed inside routes
- Difficult to manage security
and validation
With
middleware:
- Clean and reusable code
- Better security
- Easier debugging and
maintenance
3. Middleware Syntax
function middlewareName(req, res, next) {
// logic
here
next();
}
Key Points:
- req → request object
- res → response object
- next() → moves control to the next
middleware or route
If next() is not called, the request will stop.
4. Simple Middleware Example
Step 1: Create Server
const express = require('express');
const app = express();
Step 2: Create Middleware
function myMiddleware(req, res, next) {
console.log("Middleware executed");
next();
}
Step 3: Use Middleware
app.use(myMiddleware);
Step 4: Create Route
app.get('/', (req, res) => {
res.send("Home Page");
});
app.listen(3000);
5. Types of Middleware in Express.js
1. Application-Level Middleware
Used for
all routes.
app.use((req, res, next) => {
console.log("Application level middleware");
next();
});
Runs on
every request.
2. Route-Level Middleware
Used for
specific routes only.
function checkLogin(req, res, next) {
console.log("User authenticated");
next();
}
app.get('/dashboard', checkLogin, (req, res) =>
{
res.send("Dashboard Page");
});
Runs only
for the /dashboard route.
3. Built-in Middleware
Provided
by Express.
Example:
Parsing JSON data
app.use(express.json());
Used to
read JSON data from the request body.
4. Third-Party Middleware
Installed
using npm.
Example:
Morgan (logger)
npm install morgan
const morgan = require('morgan');
app.use(morgan('dev'));
Logs HTTP
requests automatically.
5. Error-Handling Middleware
Used to
handle application errors.
Must
contain four parameters.
app.use((err, req, res, next) => {
console.log(err.message);
res.status(500).send("Something went wrong");
});
6. Middleware Execution Order
Middleware
executes in the order it is defined.
app.use((req, res, next) => {
console.log("First middleware");
next();
});
app.use((req, res, next) => {
console.log("Second middleware");
next();
});
Output:
First middleware
Second middleware
7. Authentication Middleware Example
function auth(req, res, next) {
const
isLoggedIn = true;
if
(isLoggedIn) {
next();
} else {
res.send("Access Denied");
}
}
app.get('/profile', auth, (req, res) => {
res.send("Welcome to Profile");
});
Only
authorized users can access the profile route.
8. Middleware Without next()
app.use((req, res) => {
res.send("Request stopped here");
});
Routes
defined after this middleware will never execute.
9. Real-Life Example
Airport
security process:
Passenger → Security Check → Boarding → Flight
If
security stops the passenger, they cannot board the flight.
Middleware works in the same way in Express.js.
10. Summary Table
|
Feature |
Description |
|
Middleware |
Function
between request and response |
|
next() |
Passes
control to next middleware |
|
app.use() |
Applies
middleware |
|
Route
middleware |
Runs on
specific routes |
|
Built-in
middleware |
express.json(),
express.static() |
|
Third-party
middleware |
morgan,
cors |
|
Error
middleware |
Handles
errors |
Comments
Post a Comment