7. Express Middleware
What is Middleware?
Middleware functions run in between the request and the response. They can modify the request, end the request, or pass control to the next middleware. This is how Express handles logging, authentication, validation, and error handling.
How Middleware Works
Every middleware function receives req, res, and next parameters. The next() function tells Express to move to the next middleware. If you forget to call next(), the request hangs forever. This is the most common mistake new Express developers make.
const logger = (req, res, next) => { console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`); next(); // CRITICAL: Without this, the request hangs! }; app.use(logger); app.get('/', (req, res) => { res.send('Home Page'); });
Try it: Remove the next() line and see what happens. The browser will load forever.
Middleware That Ends the Request
If a middleware sends a response, it should NOT call next(). Once you've sent a response, calling next() would try to send another response, which causes an error. This pattern is used for authentication: if the token is missing, respond immediately and stop the pipeline.
const requireAuth = (req, res, next) => { const token = req.headers.authorization; if (!token) { return res.status(401).json({ error: 'No token provided' }); // Notice: no next() here - we ended the request } next(); // Only proceed if authenticated }; app.get('/protected', requireAuth, (req, res) => { res.json({ message: 'Secret data' }); });
Error Handling Middleware
Error middleware has FOUR parameters: (err, req, res, next). Express identifies it by the number of parameters. This must be the LAST middleware you add to your app. Any error thrown in routes or called via next(err) will end up here.
app.get('/danger', (req, res) => { throw new Error('Something crashed!'); }); app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ error: 'Internal Server Error' }); });
Creating a Request Timer
Middleware can measure how long requests take. This is useful for performance monitoring. The finish event on the response fires after the response has been sent to the client.
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`${req.method} ${req.url} took ${duration}ms`);
});
next();
});
Rate Limiting
Rate limiting prevents a single IP from making too many requests. This protects your server from DDoS attacks and brute force login attempts. The example stores request counts in memory, but in production you would use Redis.
const rateLimit = new Map(); const limiter = (req, res, next) => { const ip = req.ip; const now = Date.now(); const windowMs = 60 * 1000; // 1 minute const maxRequests = 10; const requests = rateLimit.get(ip) || []; const recent = requests.filter(time => now - time < windowMs); if (recent.length >= maxRequests) { return res.status(429).json({ error: 'Too many requests' }); } recent.push(now); rateLimit.set(ip, recent); next(); }; app.use('/api/', limiter);
Knowledge Check
Ready to test your understanding of 7. Express Middleware?