Sling Academy
Home/Node.js/How to Retrieve All Registered Routes in Express JS

How to Retrieve All Registered Routes in Express JS

Last updated: December 28, 2023

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.

Next Article: How to Integrate H2 Database with Express and Node.js

Previous Article: How to Manage Cookies in Express JS

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates