margot_eddie
margot_eddie

Reputation: 207

Routes priority in Express: am I doing it wrong?

I'm a bit confused about the Express priority order for all the routes. This is what I've done following some stackoverflow answers and other guides on internet.

I have some http requests and this is the order: is it right in your opinion? If not, why? Thanks!

app.get('/', (req, res) => {
   ...
});

app.get('/:car', (req, res) => {
   ...
});

app.get('/:car/:eng', (req, res) => {
   ...
});

app.put('/:car/:feature_id', (req, res) => {
   ...
});

app.get('/import/colors', (req, res) => {
   ...
});

app.post('/import/brands', (req, res) => {
   ...
});

app.post('/import/colors/:car_id', (req, res) => {
   ...
});

Upvotes: 1

Views: 1408

Answers (1)

jfriend00
jfriend00

Reputation: 707926

Express just attempts to match your routes in the order they are defined in your code for the type of request it is (.e.g GET, POST, PUT). So, if it's a GET request, Express matches only against the route definitions that include GET. Here's a few examples from the routes you show.

If there's an incoming route of /hello/there, then that will first match app.get('/:car/:eng', ...) because that matches ANY two segment path and it's the first route in order that matches.

If there's an incoming route of /import/colors, then that will also match app.get('/:car/:eng', ...) because that matches ANY two segment path.

If, on the other hand, you change the order of the code to this:

app.get('/import/colors', (req, res) => {
   ...
});

app.get('/:car/:eng', (req, res) => {
   ...
});

Then, /import/colors will match the first of these two routes because matching is tried in the order the routes are declared.

FYI, in general, I don't like using routes that have a top level wildcard because you get yourself all sorts of possible conflicts and you may find yourself boxed into a bit of a corner for future URL expansion when you want to add other routes.

Recommendation

So, if you have overlapping route definitions, then define the most specific routes first so they get a chance to match before the more general routes. Most of the time, I prefer a URL design that doesn't have overlapping routes and then you won't have this issue at all.

Upvotes: 1

Related Questions