Beginner LevelExpress JS
How do you inspect registered routes and middleware stacks programmatically using app._router.stack?
❓ Interview Prompt: Explain inspecting internal Express router stack (app._router.stack), extracting route paths, and dynamic API documentation.
Express maintains an internal array of all registered middleware layers and route regex objects under 'app._router.stack'.
Introspection Use Cases:
Traversing 'app._router.stack' allows programmatically listing all active endpoint URLs, HTTP methods, and mounted sub-routers for automated API documentation generators or diagnostics.
Code Implementation Example
javascript
import express from 'express';
const app = express();
app.get('/api/users', (req, res) => res.json([]));
app.post('/api/users', (req, res) => res.json({}));
// Diagnostic endpoint listing all registered route paths!
app.get('/api/routes', (req, res) => {
const routes = app._router.stack
.filter(layer => layer.route) // Filter for route layers
.map(layer => ({
path: layer.route.path,
methods: Object.keys(layer.route.methods)
}));
res.json({ routes });
});💡Programmatically inspecting registered application routes via app._router.stack.
🎯 Interview Key Takeaway
Traverse app._router.stack to inspect registered middleware layers and routes programmatically.
#app._router.stack#Introspection#Routing#Beginner
Back to all Express JS Questions→