Check out a free preview of the full API Design in Node.js, v3 course:
The "Route Order" Lesson is part of the full, API Design in Node.js, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Scott demonstrates how Express will respond with multiple route definitions that match the route of the request.

Get Unlimited Access Now

Transcript from the "Route Order" Lesson

[00:00:00]
>> Scott Moss: So we talked about how middleware order matters, right, and you saw my example where I had these up here first, so they ran in front of our routes down here. And that's because, yes, they were on top. So not only do middleware order matter, but route definition order matters, too.

[00:00:17] So if I had two that matched the exact same thing, for instance, app.get, and I do another one down here, in this case, let's say I send back 1, in this case I send back 2. If we were to run this, let me get rid of this right quick.

[00:00:38]
>> Scott Moss: Cool, so if we run this and we hit that,
>> Scott Moss: I got rid of the data. There we go.
>> Scott Moss: We get back to data 1, right? Because that was the first one that matched. Even though they're both the same, this one matched first, so it was executed.

[00:00:57] Now if you were to get crazy, [LAUGH] this will show you how the line between controllers and middleware are basically nothing. If I were to do a next in here, for some reason, instead of responding, I did a next, I'm just gonna get rid of that,
>> Scott Moss: What do you think would happen?

[00:01:20]
>> Scott Moss: [LAUGH]
>> Speaker 2: [INAUDIBLE] my guess it will go to two, but.
>> Scott Moss: Let's see. I like the way you think. Yeah, it goes to the next one. It goes to 2. It goes to the next one that matches, right? So that's why I was like middleware and controls are basically the same thing, it's just the intent are different.

[00:01:37] But as far as Express is concerned, it's the same thing. They take a request, a response and the next object. And you either respond, throw an error or you call it next. Those are basically your three options there. It's just that middleware, its intent is not to respond, it's to go next.

[00:01:53] So if I just put next here, it's gonna go here. You should never do this. I don't know, [LAUGH] if you saw this in your code, you should just find the person that did it and have a sit down with them. Tell them not to do this, because [LAUGH] this is very confusing.

[00:02:07] This should be middleware, instead. You wouldn't make this a route. If this thing was literally doing nothing but calling next first, get rid of it. But if it was doing something and not responding, it shouldn't be a route. It should be a middleware that you register on a route somewhere so it's easier to read.

[00:02:27]
>> Scott Moss: Any questions on that? So, yeah, order does matter, top to bottom.