CodePark/ questions / HTTP servers & Express middleware
START PRACTICINGPRACTICE
Backend question · Node.js › HTTP servers & Express middleware

Explain the difference between next(), next(err), next('route') and next('router') in Express.

next() passes control to the next matching middleware or handler in the stack.

next(err) marks the request as failed. err can be any value except the special strings 'route' and 'router'. Express skips all remaining normal middleware and routes. It goes straight to the error-handling middleware, which has four parameters.

next('route') skips the remaining callbacks of the current route. Express moves to the next route that matches. It only works in middleware attached with app.METHOD() or router.METHOD(), such as app.get. It is useful for conditional handlers. Example: a permission check that falls through to a public version of the page.

next('router') leaves the current router completely. Express continues with whatever comes after the place where that router was mounted.

  • next() continues to the next match.
  • next(err) jumps to the error handlers.
  • next('route') skips the rest of the current route's callbacks.
  • 'route' only works in app.METHOD or router.METHOD middleware.
  • next('router') exits the current router.