How to Retrieve All Registered Routes in Express JS

Updated: December 28, 2023 By: Guest Contributor Post a comment

Understanding and inspecting the routes in an Express application can be crucial for debugging, documentation, or perhaps for the creation of certain features like automatic API documentation, route health checks, or generating route-based metrics. Express, a minimal and flexible Node.js web application framework, does not provide a built-in feature to list all registered routes, but it allows for introspection which we can leverage to retrieve this information.

Getting Started

Before delving into code examples, let’s get a clear picture of what routes are in the context of Express JS. Routes are essentially the heart of your web application, defining endpoints and their corresponding handlers that react to various HTTP requests. Retrieving a list of all registered routes can give developers a bird’s eye view of the application structure, aiding in maintenance and further development.

Starting with a Basic Express App

First, install Express using npm if you have not done so:

npm install express

Next, set up a simple Express application:

const express = require('express');
const app = express();

app.get(‘/’, (req, res) => { res.send(‘Home Page’); }); app.get(‘/about’, (req, res) => { res.send(‘About Page’); }); app.listen(3000, () => { console.log(‘Server is running on port 3000’); });

Now, let’s explore how we can list all the routes registered on this app.

Retrieving Routes Using Express’s Own Mechanisms

You can get a list of all routes by inspecting the app’s ‘_router’ property and applying a filter:

console.log(app._router.stack.filter(r => r.route).map(r => ({
  path: r.route.path,
  methods: r.route.methods
})));

This will output a list of route paths and the HTTP methods associated with each.

Advanced Route Retrieval

If you want to write a more reusable function for listing the routes or even develop a middleware for this purpose, you can expand on the previous example:

function listRoutes(app) {
  const routes = [];
  app._router.stack.forEach(middleware => {
    if (middleware.route) { // routes registered directly on the app
      routes.push(extractRoute(middleware));
    } else if (middleware.name === 'router') { // router middleware
      middleware.handle.stack.forEach(handler => {
        if(handler.route) {
          routes.push(extractRoute(handler));
        }
      });
    }
  });
  return routes;
}

function extractRoute(middleware) {
  return {
    path: middleware.route.path,
    methods: Object.keys(middleware.route.methods).map(method => method.toUpperCase())
  };
}

To use this function, simply call it with your Express app instance:

const routes = listRoutes(app);
console.log(routes);

Conclusion

In this article, we’ve looked at how you can retrieve all registered routes in an Express.js application. We started with basic introspection and proceeded to building a reusable function. While Express doesn’t offer a standardized method to list routes, the flexibility of JavaScript and the introspective capabilities of the framework allow developers to devise their own solutions. With the techniques outlined in this guide, developers can now programmatically access their route definitions, aiding in debugging and providing a platform for further automation and tooling within their Express applications.