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.

router1.js

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

app.js

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

Summary

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.