Skip to content

How to resolve parameterized route conficts in express.js?

In this quick post, we will learn how to resolve route conflicts that arises when we are using parameterized routes in express.js routes.

Let’s take two routes as an example. In your route.js you would define your routes like this.

routes.get('/:dashboardId', dashboardService.getDashboard);

routes.get('/report', dashboardService.getReport);

When you define your routes like this and when you try to access /report, the first route with the param /:dashboardId would be called. The first route has parameters in the route and the second one doesn’t. But when you call the second route, the first one gets invoked! This is because of the ordering.

You need to move the non-parameterized routes to the top and then define the parameterized routes.

routes.get('/report', dashboardService.getReport);

routes.get('/:dashboardId', dashboardService.getDashboard);

Now your /report route should work!

See also  How to get query strings and path parameters in Express.js?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.