next() passes control to the next middleware or route handler in the chain. A middleware that does not send a response must call it, or the request is left hanging.
app.use((req, res, next) => {
if (req.headers.authorization) {
next(); // Continue to next middleware
} else {
next(new Error('Unauthorized')); // Trigger error handling
}
});
next has three common forms:
next() moves on to the next matching function.
next(err) skips the normal functions and jumps to the error-handling middleware.
next('route') skips the remaining callbacks of the current route and moves to the next matching route.
Use return next() when more code follows, so the function stops there.
Rewriting in plainer words…
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Route 1 is app.get with a check, then a handler. Route 2 handles the same path. A 404 middleware and an error handler come last.
1 / 5← → keys
next() goes to the next function, next('route') to the next matching route, and next(err) to the error handler. If a function neither calls next nor sends a response, the request hangs.