Menu Close

How to Get All Registered Routes in Express and JavaScript?

Sometimes, we want to get all registered routes in Express and JavaScript.

In this article, we’ll look at how to get all registered routes in Express and JavaScript.

Get All Registered Routes in Express and JavaScript

To get all registered routes in Express and JavaScript, we can use the app._route.stack property.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get("/", (req, res) => {
  res.send('hello world')
});

app.get("foo", (req, res) => {
  res.send('foo')
});

app.get("bar", (req, res) => {
  res.send('bar')
});

app._router.stack.forEach((r) => {
  console.log(r.route && r.route.path)
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to log all the registered routes with:

app._router.stack.forEach((r) => {
  console.log(r.route && r.route.path)
})

We get the pathname string with r.route.path .

Conclusion

To get all registered routes in Express and JavaScript, we can use the app._route.stack property.

Posted in Express, expressjs