Introduction
Middleware helps organize code that runs between receiving a request and sending a response. It makes your app easier to build and maintain.
Middleware helps organize code that runs between receiving a request and sending a response. It makes your app easier to build and maintain.
function middlewareFunction(req, res, next) {
// Do something with req or res
next(); // Pass control to the next middleware
}app.use(function(req, res, next) {
console.log('Request URL:', req.url);
next();
});app.use(function(req, res, next) {
if (!req.user) {
res.status(401).send('Not logged in');
} else {
next();
}
});This example shows two middleware functions: one logs requests, the other adds a header. Then a route sends a welcome message.
import express from 'express'; const app = express(); // Middleware to log request method and URL app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); // Middleware to add a custom header app.use((req, res, next) => { res.setHeader('X-Custom-Header', 'HelloMiddleware'); next(); }); // Route handler app.get('/', (req, res) => { res.send('Welcome to middleware demo!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always call next() unless you end the response to avoid hanging requests.
Middleware runs in the order you add it, so order matters.
Middleware runs code between request and response.
It helps keep your app organized and reusable.
Use middleware for logging, authentication, error handling, and more.
app.use((req, res, next) => { console.log('First'); next(); });
app.use((req, res, next) => { console.log('Second'); res.send('Done'); });
app.use((req, res, next) => { console.log('Third'); next(); });app.use((req, res) => { console.log('Logging request'); });Pass the test and this pattern moves unknown