I recently had a conversation in the WatchMeCode slack where someone was asking about the order in which various parts of Express middleware would fire.
After some initial thoughts on the question, I found myself not 100% certain of the order between calls to “.use”, vs get/post/etc. So I whipped up a quick demo app to see what would happen when I put things in different places.
The Sample Code
The code I came up with is fairly straightforward, with a call to “.get” and “.param”, and 2 calls to “.use” at various times:
This provides a good cross-section of the major parts of an express route handler setup.
On running this code, however, I found it didn’t quite work as I expected.
When making a request to “/foo” on my localhost, I knew “.param” call would fire before the route handler. I use param all the time, so this was expected.
My initial expectation of the “.use” calls, however, was not quite right.
I expected them both to fire before the “.get” call. What I got for the output, instead, was this:
Note that the “second use” console log message never shows up!
It turns out the order in which you add the middleware is important. And since the 2nd “use” method is added after the “get” handler, it is never called.
The “get” handler short-circuits the middleware when it renders the page, preventing any further middleware from being processed.
What I learned from this quick experiment, is that almost all Express middleware is treated equally when it comes to the order in which it executes.
With the exception of “.param” always happening just before any route handler that matches the parameter, the order in which your route handlers and other middleware functions are declared is the order which they will be executed.
This is true for all levels of your routing and middleware configuration. Whether you are dealing with a router instances, adding sub-routers or working with the top level Express application instance, calling .use, .get/post/etc, or any other middleware method will result in the code executing in that order.
The next time you’re wondering when your middleware will execute, then, just look at the order in which it was declared. You’ll know, with certainty, when the code will be called.