Middleware helps you add extra steps when your server handles requests. It lets you run code before sending a response.
Building custom middleware in Node.js
function middlewareName(req, res, next) {
// Your code here
next();
}The req is the request object with info about the client request.
The res is the response object used to send data back.
The next is a function you call to move to the next middleware or route.
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}function addPoweredBy(req, res, next) {
res.setHeader('X-Powered-By', 'Node.js');
next();
}function checkAuth(req, res, next) {
if (!req.headers.authorization) {
res.status(401).send('Unauthorized');
} else {
next();
}
}This example creates a simple Express server. It uses a custom middleware called logger that prints the HTTP method and URL for every request. Then it responds with 'Hello, world!' on the home page.
import express from 'express'; const app = express(); // Custom middleware to log requests function logger(req, res, next) { console.log(`${req.method} ${req.url}`); next(); } // Use the middleware for all routes app.use(logger); app.get('/', (req, res) => { res.send('Hello, world!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always call next() in your middleware unless you send a response directly.
Middleware runs in the order you add it with app.use() or on routes.
You can create middleware to handle errors by defining a function with four arguments: (err, req, res, next).
Middleware lets you add extra steps when handling requests.
It uses three arguments: req, res, and next.
Call next() to continue to the next step or send a response to end.