Express Middleware
Middleware is a function that runs between a request arriving and a response being sent. It has access to the request object (req), the response object (res), and a next function that passes control to the next middleware or route handler.
Middleware can: log requests, authenticate users, parse request bodies, set headers, or end the request/response cycle early.
Custom middleware
const express = require('express');
const app = express();
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url} - ${Date.now()}`);
next(); // pass control to the next middleware or route
};
app.use(logger); // apply to all routes
Calling next() is required unless the middleware ends the response. If you forget next(), the request will hang.
Middleware order matters
Express runs middleware in the order you declare it with app.use(). Middleware declared before your routes runs first. Middleware declared after a route only runs if that route calls next() instead of sending a response.
app.use(logger); // runs first on every request
app.use(express.json()); // runs second
app.get('/', handler); // routes run after middleware
Built-in middleware
Express ships with three built-in middleware functions.
express.json(): parses JSON request bodies. Required for POST and PUT routes that receive JSON. Add it before your routes:
app.use(express.json());
express.urlencoded({ extended: false }): parses HTML form data (URL-encoded bodies):
app.use(express.urlencoded({ extended: false }));
express.static('public'): serves static files (HTML, CSS, images) from a folder. See Serve Static Files
for details.
Applying middleware to specific routes
Pass the middleware as an argument before the route handler to apply it only to that route:
const requireAuth = (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorised' });
}
next();
};
app.get('/dashboard', requireAuth, (req, res) => {
res.send('Dashboard');
});
Third-party middleware
Install via npm, then apply with app.use(). Example: cors allows requests from other origins (required when a frontend on a different domain calls your API):
npm install cors
const cors = require('cors');
app.use(cors());
Check the Express middleware list for other commonly used packages.
What to read next
- Routing : define routes that middleware feeds into
- express.Router() : organise middleware and routes into separate files