How to set default path (route prefix) in Express?

Sometimes, we want to set default path (route prefix) in Express.

In this article, we’ll look at how to set default path (route prefix) in Express.

How to set default path (route prefix) in Express?

To set default path (route prefix) in Express, we can create a Router instance.

For instance, we write

const router = express.Router();
router.use("/user", user);

app.use("/api/v1", router);

to call express.Router to create a router.

Then we call router.use with a user route object.

Next, we call app.use with router to use the router in the app.

Therefore, we access the routes in the user router by prepending /api/v1/user to the URL.

Conclusion

To set default path (route prefix) in Express, we can create a Router instance.