Search code examples
node.jstypescriptexpressnestjs

How can I get all the routes (from all the modules and controllers available on each module) in Nestjs?


Using Nestjs I'd like to get a list of all the available routes (controller methods) with http verbs, like this:

API:
      POST   /api/v1/user
      GET    /api/v1/user
      PUT    /api/v1/user

It seems that access to express router is required, but I haven found a way to do this in Nestjs. For express there are some libraries like "express-list-routes" or "express-list-endpoints".

Thanks in advance!


Solution

  • main.ts

    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      await app.listen(3000);
      const server = app.getHttpAdapter().getInstance();
      const router = server.router;
    
      const availableRoutes: [] = router.stack
        .map(layer => {
          if (layer.route) {
            return {
              route: {
                path: layer.route?.path,
                method: layer.route?.stack[0].method,
              },
            };
          }
        })
        .filter(item => item !== undefined);
      console.log(availableRoutes);
    }
    bootstrap();