There's more...

It is possible to pass control back to the next middleware function or route method outside of a router by calling next('router').

router.use((request, response, next) => { 
  next('route') 
}) 

For example, by creating a router that expects to receive a user ID as a query parameter. The next('router') function can be used to get out of the router or pass control to the next middleware function outside of the router when a user ID is not provided. The next middleware function out of the router can be used to display other information when the router passes control to it. For example:

  1. Create a new file named router-level-control.js
  2. Initialize a new ExpressJS application:
      const express = require('express') 
      const app = express() 
  1. Define a new router:
      const router = express.Router() 
  1. Define our logger middleware function inside the router:
      router.use((request, response, next) => { 
         if (!request.query.id) { 
             next('router') // Next, out of Router 
          } else { 
            next() // Next, in Router 
          } 
      }) 
  1. Add a route method to handle GET requests for path "/" which will be executed only if the middleware function passes control to it:
       router.get('/', (request, response, next) => { 
         const id = request.query.id 
         response.send(`You specified a user ID => ${id}`) 
      }) 
  1. Add a route method to handle GET requests for path "/" outside of the router. However, include the router as a route handler as the second argument, and another route handler to handle the same request only if the router passes control to it:
      app.get('/', router, (request, response, next) => { 
          response 
            .status(400) 
            .send('A user ID needs to be specified') 
    }) 
  1. Listen on port 1337 for new connections:
      app.listen( 
          1337, 
          () => console.log('Web Server running on port 1337'), 
      ) 
  1. Save the file
  2. Open a terminal and run:
      node router-level-control.js
  1. To see the result, in your browser, navigate to:
  http://localhost:1337/
      http://localhost:1337/?id=7331