0

I have seen the following example: https://stackoverflow.com/questions/13133071/express-next-function-what-is-it-really-for which has three get methods with the same signature: app.get('/user/:id', function (req, res, next). I want to follow up on the answer but unfortunately, I do not have enough 'reputation' to add a comment.

My question is how does ExpressJS knows which method/middleware to execute next when the next() function is called? Is it the order of appearance of the get methods in the source code?

1 Answers1

0

My question is how does ExpressJS knows which method/middleware to execute next when the next() function is called? Is it the order of appearance of the get methods in the source code?

Yes, it is the order the app.get() calls are executed in the source code.

app.get() registers route handlers onto a router object. Internally, those are stored in an ordered array where the order is determined by the sequence of app.get() calls in the original execution of the code.

When Express attempts to find a route that matches an incoming request, it searches that array in order from start to end. When it finds a matching route, it creates a custom next() function that, when called will continue further matching at the point where it last left off when it matched this handler, thus continuing to iterate the ordered array looking for further matches.

jfriend00
  • 683,504
  • 96
  • 985
  • 979