Nestjs Get All Routes| List all controller methods and paths with code examples
Sometimes, the Nestjs application needs to get all routes from all modules in an application..
this tutorial shows you how to retrieve all routes from the NestjS app.
NestJS code example to get all routes
nestjs uses express routes, use the express classes to get route information.
- First, In
main.js
, get the server object using theapp.getHttpServer()
method - Get routes from the
server._events.request._router
property - Iterate routes stack using the map method
- check each route if it is a route, and print the request
path
(routeObj.route?.path) andmethod
(routeObj.route?.stack[0].method).
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
const server=app.getHttpServer()
const router = server.\_events.request.\_router;
const existingRoutes: [] = router.stack
.map(routeObj => {
if (routeObj.route) {
return {
route: {
path: routeObj.route?.path,
method: routeObj.route?.stack[0].method,
},
};
}
})
.filter(item => item !== undefined);
console.log(existingRoutes);
}
bootstrap();
The result is printed to the console as given below
[
{ route: { path: '/api/ip', method: 'get' } },
{ route: { path: '/api/ip1', method: 'get' } },
{ route: { path: '/api/ip2', method: 'get' } },
{ route: { path: '/api/url', method: 'get' } },
{ route: { path: '/api/employees', method: 'get' } },
{ route: { path: '/api/employee/:id', method: 'get' } },
{ route: { path: '/api/employees/:id', method: 'get' } }
]
express-list-routes example to get all controller, module routes example
- First, install the
express-list-routes
npm library
npm install express-list-routes
- Next, in
main.js
, get the server object using theapp.getHttpServer()
method - pass server._events.request._router property to expressListRoutes method, expressListRoutes is imported to code.
Here is an example
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import \* as expressListRoutes from 'express-list-routes';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
const server=app.getHttpServer()
const existingRoutes=server.\_events.request.\_router
expressListRoutes(existingRoutes);
}
bootstrap();
Output:
GET A:\api\ip
GET A:\api\ip1
GET A:\api\ip2
GET A:\api\url
GET A:\api\employees
GET A:\api\employee\:id
GET A:\api\employees\:id