When working with the next()
function, you have three options:
1. Continue routing. To simply move on to the next route handler in the chain that matches this route, call next()
without any parameters:
next();
This is commonly used in middleware functions:
app.use((req, res, next) => {
// set a session item and continue routing
req.session.xxx = "foo";
next();
});
2. Stop routing and handle errors centrally. If you need to interrupt routing due to an error and direct it to your centralized error handler, pass an error to next()
:
next(new Error("timeout contacting database"));
This approach sends the specific error to your general error handling route where you can determine how to respond. Centralizing error-handling logic helps maintain consistency. Refer to this link for examples using next(err)
.
For more information on generalized error handling in Express, check out the documentation.
3. Skip route handlers in current router, proceed with other routers' routes. To bypass all route handlers in the current router but continue with routes from other registered routers, use:
next('route');
As explained in the documentation:
You can supply multiple callback functions similar to middleware. These callbacks can invoke next('route')
to skip remaining route callback(s). This feature allows setting pre-conditions for a route and then proceeding to subsequent routes if necessary.
If you search for "next(" in this part of the documentation, you'll find numerous examples. Additionally, there's a demonstration of this usage here.
Note that Express 5 might introduce new functionalities for next()
, potentially returning a promise to signal completion of routing procedures.