β What is Middleware in Node js?
Middleware in Node.js refers to functions that execute during the request-response cycle. Every HTTP request goes through a stack of middleware before reaching its final response.
You can think of middleware as interceptors that can:
-
Modify the request (
req) or response (res) objects -
End the request-response cycle
-
Call the next middleware in the stack using
next()
There are two types:
-
Pre Middleware: Runs before the request is handled
-
Post Middleware: Runs after some processing, or to handle things like errors
βοΈ How Middleware Works in Node.js (with Example)
Let’s create a simple Express server using TypeScript and see middleware in action.
π File:
index.ts
import * as express from ‘express’;
const app: express.Application = express();
// β
This is a middleware without a specific route
app.use((req, res, next) => {
console.log(‘π Global middleware called’);
next(); // Pass control to the next middleware or route
});
// β
Route-specific middleware example
app.get(‘/login’, (req: any, res, next) => {
const data = [{ name: ‘testUsername’ }];
req.user = data; // Attach data to the request
next(); // Move to the next middleware
}, (req: any, res, next) => {
console.log(‘β
Login middleware called’);
res.send(req.user); // Send response
});
// β
A simple route with no middleware chain
app.get(‘/test’, (req, res) => {
res.send(‘This is a test request’);
});
// β
This middleware will be called for unmatched routes
app.use((req, res, next) => {
console.log(‘β No route matched, fallback middleware called’);
res.status(404).send(‘Route not found’);
});
// Start the server
app.listen(5000, () => {
console.log(‘π Server running on http://localhost:5000’);
});
π Middleware Execution Flow
Letβs break down what happens when a request is made:
π When visiting /login:
-
The global middleware is called (
app.use(...)) -
The first
/loginmiddleware runs and attaches data toreq.user -
The next middleware sends the
req.userresponse
π When visiting /test:
-
The global middleware is called
-
The
/testroute directly sends the response
π When visiting any unknown route:
-
Global middleware runs
-
None of the route paths match
-
Fallback middleware sends a 404 response
π Important Notes on Middleware in Node.js
-
Always call
next()to pass control; otherwise, the request will hang -
Use
app.use()for global or fallback middleware -
Custom data should be added to
req, notres -
The order of middleware matters: middleware runs in the order it is defined
-
It’s a good practice to structure your API routes like
/api/user/loginrather than just/login
β Example with Clean Route Paths
sh
app.get(‘/api/user/login’, (req: any, res) => {
const data = [{ name: ‘testusername’ }];
res.status(200).send(data);
});
app.get(‘/api/user/signup’, (req, res) => {
res.send(‘Signup route’);
});
π§ Summary: What You Learned About Middleware in Node js
-
Middleware are functions that process incoming requests
-
You can write global, route-specific, or error-handling middleware
-
Middleware in Node js helps you keep logic clean and modular
-
Standard practice is to keep your API URLs structured and RESTful