Introduction
Middleware in Express helps handle requests step-by-step. It lets you add features like logging, security, or data parsing easily.
Middleware in Express helps handle requests step-by-step. It lets you add features like logging, security, or data parsing easily.
app.use(function (req, res, next) {
// your code here
next();
});app.use((req, res, next) => {
console.log('Request URL:', req.url);
next();
});app.use(express.json());
app.use((req, res, next) => {
if (!req.user) {
res.status(401).send('Not logged in');
} else {
next();
}
});This example shows two middleware functions: one logs every request, the other parses JSON data. Then a route handles POST requests to '/data' and sends back the received data.
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 parse JSON body app.use(express.json()); // Route handler app.post('/data', (req, res) => { res.send(`Received data: ${JSON.stringify(req.body)}`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Middleware runs in the order you add it with app.use().
Always call next() unless you send a response to avoid hanging requests.
Middleware lets you add reusable steps to handle requests.
It is the core way Express processes requests and responses.
Using middleware keeps your code organized and flexible.
app.use() with a function that takes req, res, next.app.use and the correct function signature.app.use((req, res, next) => {
console.log('Middleware 1');
next();
});
app.use((req, res) => {
res.send('Hello from Express');
});app.use((req, res, next) => {
res.send('Hello');
next();
});Pass the test and this pattern moves unknown