THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
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 uses express routes, use the express classes to get route information.
main.js
, get the server object using the app.getHttpServer()
methodserver._events.request._router
propertypath
(routeObj.route?.path) and method
(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
npm librarynpm install express-list-routes
main.js
, get the server object using the app.getHttpServer()
methodHere 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
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts