Express.js Router

Express.js Router is kind of nesting a mini server inside a server.

Create an Express.js Router

In the following example, we will create an API using router. The API is created separately to demonstrate modularity.


We created a router using express.Router() and then created some routing paths


When we used app.use('/api/', router1) all the requests to the server with the URI path /api/ are now routed to router1. And when you hit the URI http://localhost:8000/api/, ‘/’ routing in the router 1 is executed. This is because, for router1, http://localhost:8000/api/ is considered as base path.

Express.js Router Example

When you hit the URI http://localhost:8000/api/about/, /about/ routing is selected.

Express.js Router Example

Terminal Log

Express.js Router Terminal Log


When you use it for the first time, it could confuse you a little bit with the execution flow. But with practice, it can become a powerful tool to create modular express applications.