Full answer
The Express request lifecycle:
- The server gets the request and Express creates req and res (extended Node objects).
- app.use middleware runs in registration order: logging, security headers, body parsing (express.json()), authentication.
- Routing: app.get('/path', ...handlers) matches method and path. A route can have several handlers and calls next() to move to the next one. next('route') skips the rest of this route.
- A handler sends a response (res.json, res.send, res.status(...).end). After the response is sent, the rest of the chain should not write again.
- If nothing responded, the request reaches the final "not found" middleware you add after all routes.
- If any step throws or calls next(err), Express skips normal middleware and runs error handlers: functions with four parameters (err, req, res, next), registered after the routes.
Express 5 change: handlers that return a rejected promise (or async functions that throw) pass the error to next(err) on their own. In Express 4 you needed try/catch plus next(err), or a wrapper library. Synchronous throws were caught in both versions.
Good practice for errors:
- Create one error handler that maps known errors to status codes and a safe message, and logs the rest.
- Never send err.stack to clients in production.
- If headers are already sent, call next(err) and let Express close the connection.
- Place the 404 handler before the error handler, and both after all routes.
Useful extras: res.on('finish') to run code after the response is flushed, app.set('trust proxy') behind a proxy, and router objects (express.Router) to group routes.
const express = require('express');
const app = express();
let trace = [];
app.use((req, res, next) => {
trace.push('logger in');
res.on('finish', () => trace.push('finished ' + res.statusCode));
next();
trace.push('logger out');
});
app.get('/students',
(req, res, next) => { trace.push('route step 1'); next(); },
(req, res) => { trace.push('route step 2'); res.json([{ id: 1 }]); });
app.get('/async-fail', async () => { // no try/catch, no next(err)
await Promise.resolve();
throw new Error('database unavailable');
});
app.use((req, res) => res.status(404).json({ error: 'not found' })); // after all routes
app.use((err, req, res, next) => { // four parameters: error handler
trace.push('error handler');
res.status(500).json({ error: 'internal error' }); // no stack trace for the client
});
const server = app.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
for (const path of ['/students', '/async-fail', '/missing']) {
trace = [];
const res = await fetch(base + path);
await res.text();
await new Promise((r) => setImmediate(r));
console.log(path.padEnd(12), res.status, '|', trace.join(' > '));
}
server.close();
});The async handler throws without any try/catch, and Express 5 still sends the error to the error middleware. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): /students 200 | logger in > route step 1 > route step 2 > logger out > finished 200 /async-fail 500 | logger in > logger out > error handler > finished 500 /missing 404 | logger in > logger out > finished 404
Key points
- Order of registration decides order of execution.
- Error middleware has four parameters and comes last.
- Express 5 forwards async errors automatically.
- 404 handler goes after routes, before the error handler.
Common mistakes
- Writing the error handler before the routes.
- Giving the error handler three parameters, so Express treats it as normal middleware.
- Sending a response and then calling next().
- Sending err.message or err.stack of unknown errors to clients.
Follow-ups
- How did you handle async errors in Express 4?
- What does next('route') do?
- How do you add a request timeout in Express?
Tips
- Narrate the lifecycle in six steps.
- Know the Express 5 async change by name.
- Say the error handler is the last middleware.