When to return after sending an Express response
Sending a response finishes the HTTP exchange. Calling next() is a separate decision—and usually the wrong one afterward.
An Express middleware chain advances when a handler calls `next()`. Methods such as `res.send()`, `res.json()`, and `res.end()` finish the response, but they do not call `next()` or stop JavaScript execution automatically.
That distinction matters: later middleware normally stays idle because the handler never passes control onward. Use `return` when sending an early response so the current function also stops running.
In this example, earlier authentication middleware sets `req.user` for signed-in requests.
app.get('/account', (req, res, next) => {
if (!req.user) {
return res.status(401).json({ error: 'Sign in required' });
}
next();
}, (req, res) => {
res.json({ id: req.user.id });
});
Think of the first handler as a railway switch. An unauthenticated request takes the response route; an authenticated request continues to the next handler. Each branch has one place that finishes the response.
Avoid calling `next()` after sending a response. It can run more middleware, but another attempt to send a response can produce an “headers already sent” error. Choose a response path, finish it, and return.