Advance the middleware chain
Continue normal request processing after logging, validation, or another middleware task.
Express.js · Interface
NextFunction is the callback Express passes to middleware as its third argument. Invoke it to continue the middleware chain, or pass a routing or error signal to change how Express proceeds.
NextFunction is the callback Express supplies as the third argument to middleware and route handlers. Calling it without an argument continues processing with the next matching middleware; passing an error transfers control to error-handling middleware, while 'route' skips remaining callbacks for the current route.
(req, res, next) => { /* middleware */ }| Name | Type | Description |
|---|---|---|
req | Request | The request object for the current HTTP request. |
res | Response | The response object for the current HTTP response. |
next | NextFunction | A callback that continues middleware processing or signals routing behavior. |
The documentation does not specify a return value; next() transfers control within Express's middleware chain.
import express, { type Request, type Response, type NextFunction } from 'express';
const app = express();
app.use((req: Request, res: Response, next: NextFunction) => {
if (req.headers['x-skip']) return next('route');
next();
});
app.get('/', (_req, res) => res.send('handled'));
app.listen(3000);This middleware passes control onward with next(); a route-specific middleware can use next('route') to skip the remaining callbacks for the current route.
Continue normal request processing after logging, validation, or another middleware task.
Skip the remaining callbacks attached to the current route and let another route match.
Send an operational failure to Express error-handling middleware.
NextFunction is the third argument passed by Express to middleware and route callbacks. Calling next() tells Express to execute the next matching middleware in the request pipeline.
Follow-up: How do you report a failure? Pass the error to next(error); Express then bypasses ordinary middleware and searches for error-handling middleware.
Middleware must either finish the response or call next(). If it does neither, the request stays pending because Express has no signal to continue processing.
Follow-up: How can route middleware skip later callbacks on the same route? Call next('route'), which bypasses the remaining route callbacks and proceeds to the next matching route.
An error-handling middleware has four parameters: err, req, res, and next. Passing a value to next(), other than 'route', marks the request as an error and routes it toward error handlers.
Follow-up: What happens when an error is not handled by custom middleware? Express uses its built-in error handler to produce the response.
app.use()router.use()next('route')error-handling middlewareRequestResponse