In Express 5, what must every (req, res, next) middleware do, and why does a request hang when one neither responds nor calls next()?
answer
- three arguments, one obligation
- end the cycle or pass it on
- no default reply, no timeout
- a resolved promise is not next()
basics
~20 sExpress middleware must either end the request-response cycle with a response or call next() to pass control on. Doing neither leaves the request hanging: Express has no fallback reply and no response timeout, so the client waits until something else gives up.
solid answer
~50 sExpress calls each matching middleware with the request, the response and `next`, a function its router supplies. The middleware may run any code and change `req` or `res`, but then it must do one of two things: finish the response (`res.send`, `res.json`, `res.end` and friends) or call `next()` so the next matching layer runs; `next(err)` instead skips ahead to the error-handling middleware. If it does neither, nothing downstream runs and Express sends nothing. It has no fallback reply and no response timeout of its own, so the socket stays open until the client or a proxy gives up, or a server-level timeout closes it. In Express 5 a middleware that returns a promise has a rejection forwarded as `next(err)`, but a promise that *resolves* does not call `next()` for you, so an `async` middleware that forgets `next()` hangs the same way.
code
javascript · 22 linesconst express = require('express');
const app = express();
const tenants = new Map([['acme', { id: 'acme', plan: 'pro' }]]);
const lookupTenant = async (id) => tenants.get(id);
// Hangs: the promise resolves, but nothing responds or calls next().
app.use('/broken', async (req, res, next) => {
req.tenant = await lookupTenant(req.get('x-tenant'));
});
// Every branch either responds or calls next().
app.use(async (req, res, next) => {
const tenant = await lookupTenant(req.get('x-tenant'));
if (!tenant) return res.status(404).json({ error: 'unknown tenant' });
req.tenant = tenant;
next();
});
app.get('/plan', (req, res) => res.json({ plan: req.tenant.plan }));
app.listen(3000);go deeper
Recall the two exits, respond or call next(), and that doing neither hangs the request with no error and no automatic 404.
Explain next(err) versus next(), why a four-parameter function is skipped on healthy requests, and that Express 5 forwards rejections but not resolutions of an async middleware.
Show how you would find a hung route in production: log lines with no status, guards missing a return, and ERR_HTTP_HEADERS_SENT from a branch that both responds and calls next().
Weigh how a team prevents this class of bug: a return-on-every-branch convention enforced in review or lint, versus a service-wide response timeout as a backstop that hides the bug while bounding its cost.
## The contract Express hands every middleware In Express, a **middleware** is a function the router calls with three arguments: `req` (the request object), `res` (the response object) and `next`. The `next` argument is not part of Node's HTTP API; it is a callback the router creates for this request, and calling it tells the router to look for the next layer in its stack that matches the request. The Express guide is explicit that the name is a convention: the function could be called anything, but it is always the third argument. The guide lists four things a middleware may do: - execute any code; - make changes to the request and response objects; - end the request-response cycle; - call the next middleware in the stack. The first two are optional. One of the last two is not: **if a middleware does not end the cycle, it must call `next()`, otherwise the request is left hanging.** That sentence is the whole contract. ## The legal ways out of a middleware | What the middleware does | What Express does next | |---|---| | Sends a response (`res.send`, `res.json`, `res.end`, `res.sendStatus`) | Nothing further runs unless the code also calls `next` | | Calls `next()` | Runs the next layer whose path (and, for routes, method) matches | | Calls `next(err)` with an error | Skips the remaining ordinary middleware and runs the four-argument error handlers | | Calls `next('route')` or `next('router')` | Skips the rest of the current route's or router's stack (covered with routing and mounting) | Arity matters too. The router treats a function declared with four parameters, `(err, req, res, next)`, as an **error handler** and skips it for ordinary requests; it only runs once an error has been passed. That is why a three-argument function cannot catch errors and a four-argument one never runs on a healthy request. ## Why doing neither hangs Express is a stack walker. When a middleware returns without responding or calling `next`, the walk simply stops: 1. The router is waiting for `next` to be called before it touches the next layer, so no later middleware, route or 404 handler runs. 2. Express's final handler, which answers `404 Cannot GET /path` when the stack is exhausted, is never reached, because the stack was never exhausted. 3. Express has no response timeout of its own, so the open socket stays open until the client gives up, a proxy in front times out, or a Node server-level timeout closes it. 4. An access logger mounted first sees the request start but has nothing to write until the connection closes; morgan, for example, then prints a line with `-` where the status and response time would be. The symptom in production is a request that "takes forever" with no error anywhere, which is far harder to diagnose than a crash. ## Express 5 and async middleware Express 5's router inspects what a middleware returns. If it returns a promise, the router attaches a rejection handler only: - a **rejected** promise or a `throw` inside an `async` function is forwarded as `next(err)` (with `new Error('Rejected promise')` substituted when the rejection value is falsy), so it reaches the error handlers; - a **resolved** promise is ignored: the router does not call `next()` when it settles. So `async (req, res, next) => { req.user = await load(); }` hangs every request it sees. The `await` succeeds, the function returns, the promise resolves, and nobody responds or calls `next`. The Express 5 migration guide records the forwarding of rejections as new in 5, which removed the need for a wrapper around every `async` handler; it did not make resolution advance the chain. A synchronous `throw` inside a middleware is caught by the router and forwarded as `next(err)` as well. ## The opposite mistake: responding and calling next() Calling `next()` after sending a response is not harmless. The next layer runs, and if it writes headers or a body, Node throws `ERR_HTTP_HEADERS_SENT` ("Cannot set headers after they are sent to the client"). The router's own README says you should not call `next` once you have begun writing to the response. The idiom that avoids both mistakes is to **return on every branch**: ```js function requireTenant(req, res, next) { if (!req.get('x-tenant')) return res.status(400).json({ error: 'missing tenant' }); next(); } ``` ## What to check in review - Every branch of a guard either returns a response or calls `next` exactly once. - `async` middleware calls `next()` at the end of its success path; awaiting is not enough. - Callback-style APIs pass their errors to `next(err)`, because only returned promises are forwarded automatically. - Error handlers keep the four-parameter signature even when `next` is unused. - A request logger mounted at the top makes hung requests visible as lines with no status.
- What does Express 5 do when an async middleware throws or its returned promise rejects?The router calls `next(err)` with the thrown or rejected value, substituting `new Error('Rejected promise')` when that value is falsy. The request then skips the remaining ordinary middleware and reaches the four-argument error handlers. The migration guide lists this forwarding as an Express 5 change; a callback-style error still has to be passed to `next(err)` by hand.
- Why is `return next()` a common idiom in Express middleware?`next()` does not stop the current function: code after it still runs once `next()` returns. Writing `return next()` and `return res.status(401).end()` makes each branch end where it decides, so a guard cannot reject a request and then fall through to code that calls `next()` or writes a second response, which would throw `ERR_HTTP_HEADERS_SENT`.
- How does a hung route show up in an Express service's access log?With morgan mounted first, the request's line is written only when the response finishes or the connection closes. A request nobody answered is logged when the client or proxy disconnects, with `-` in place of the status and response time, which points at a middleware that neither responded nor called `next()`.
- Express sends a 404 automatically when a middleware forgets to call next().
- Express times out a request that no middleware answers.
- In Express 5 an async middleware that resolves continues the chain automatically.
- Calling next() after res.send() is harmless because Express ignores it.
- Express only recognises the third parameter if it is literally named next.
Assumes Express 5, whose router forwards a returned promise rejection as next(err); the migration guide shows Express 4 code passing such rejections to next by hand.