List all routes used in Express[3,4,5]
const express = require('express');
const expressListRoutes = require('express-list-routes');
const app = express();
app.get('/health', fn)
app.use('/admin', router);
router.route('/user')
.post(fn)
.get(fn)
.put(fn);
expressListRoutes(app, { prefix: '/api/v1' });
// Logs out the following:
// GET /api/v1/health
// POST /api/v1/admin/user
// GET /api/v1/admin/user
// PUT /api/v1/admin/user
expressListRoutes(router);
// Logs out the following:
// POST /admin/user
// GET /admin/user
// PUT /admin/user
expressListRoutes
returns array of all routes found in express.
const paths = expressListRoutes(req.app, { logger: false });
paths.forEach((endpoint) => {
if (endpoint.path.endsWith('/')) {
...
}
});
npm install express-list-routes
You can pass a second argument to set some options
{
prefix: '', // A prefix for router Path
spacer: 7 // Spacer between router Method and Path
logger: console.info // A custom logger function or a boolean (true for default logger, false for no logging)
color: true // If the console log should color the method name
forceUnixPathStyle: false // Convert Windows backslashes to forward slashes for consistent path display across platforms
}
Errors with importing this library
You may need to enable esModuleInterop in your tsconfig.json to support default exports.Windows path display shows backslashes
On Windows systems, paths may display with backslashes (e.g., `\admin\user`) instead of forward slashes. This is due to Node.js path.normalize() behavior on Windows. To ensure consistent Unix-style paths across all platforms, set the `forceUnixPathStyle` option to `true`:expressListRoutes(app, { forceUnixPathStyle: true });
// This will display: /admin/user (even on Windows)
For Express5 currently nested routes will all be printted out as ~
as theres no way to get parent router path from app object that I'm aware of.