Node.js Express Middleware
Express middleware are functions that run during the request-response cycle, before your final route handler. Each middleware receives req, res and next. It can read or change the request, send a response, or call next() to pass control to the next function in line.
Middleware is how Express handles logging, parsing, authentication, CORS, compression and errors.
Writing a Logger Middleware
app.use runs the middleware for every request. If you forget to call next() (or send a response), the request hangs forever.
function logger(req, res, next) {
const start = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - start}ms`);
});
next();
}
app.use(logger);GET /api/products 200 4ms POST /contact 400 2ms
Middleware Order Matters
Express runs middleware in the order you register it. Parsers and loggers go first, routes in the middle, and 404 and error handlers last.
app.use(express.json()); // 1. parse bodies
app.use(logger); // 2. log
app.use('/api', apiRouter); // 3. routes
app.use((req, res) => { // 4. nothing matched
res.status(404).json({ error: 'Not found' });
});GET /missing
{"error":"Not found"}Authentication Middleware
Middleware can protect routes. Apply it to a single route by listing it before the handler.
function requireApiKey(req, res, next) {
if (req.get('x-api-key') !== process.env.API_KEY) {
return res.status(401).json({ error: 'Invalid API key' });
}
req.user = { role: 'admin' };
next();
}
app.delete('/api/posts/:id', requireApiKey, (req, res) => {
res.json({ deleted: req.params.id, by: req.user.role });
});(without key) 401 {"error":"Invalid API key"}
(with key) 200 {"deleted":"5","by":"admin"}Built-in and Popular Middleware
- express.json() — parse JSON request bodies
- express.urlencoded() — parse HTML form submissions
- express.static() — serve files from a folder
- cors — allow requests from other origins, such as your React app
- helmet — set secure HTTP headers
- morgan — ready-made request logging
- express-rate-limit — limit repeated requests
Using Third-Party Middleware
npm install cors helmet
import cors from 'cors';
import helmet from 'helmet';
app.use(helmet());
app.use(cors({ origin: 'http://localhost:5173' }));(responses now include security headers and Access-Control-Allow-Origin: http://localhost:5173)
Frequently asked questions
What is middleware in Express?
A function with the signature (req, res, next) that runs before route handlers. It can modify the request or response, end the request, or call next() to continue.
What happens if I do not call next() in middleware?
Unless the middleware sends a response, the request is left hanging and the client eventually times out.
How do I fix CORS errors in Express?
Install the cors package and add app.use(cors({ origin: "https://your-frontend.com" })) before your routes so the browser is allowed to call your API.