Difference between middleware, route handlers and regular function in express
Hello, can someone explain what is the difference between a middleware, a route handler and a regular function in Express please. I do have an answer (I think), for middleware, it's like a "middle-man" trying to modify whatever request or response.
When we say it modifies response object also, what does it mean, from where does the object response come from?
When we use functions like
app.use()
, this expect a middleware? Or even when we create a router, like express.route(), why we don't see the next
parameter?4 Replies
A route handler is a specific function that is called when an API route is hit. It literally handles the route.
A regular function is just that, it's a function.
Middleware is a function (or series of functions) that run on all route handlers. IIRC it runs through the middleware list in order immediately after the route handler starts, then runs backwards through the list right after the response is sent.
Middleware is for when you want something to happen on all route handlers. Like looking for an auth header and assigning it a user ID via a DB look up. Logging each request so you have statistics on the various API routes. Timing each route so you know which needs attention to be better, etc.
the
next
param is only for middleware as it's what's used to call the next function in the chain. I'm pretty sure they make use of generators and yield
the req/res to the next function, then when things run in reverse any logic after the initial next()
call is run. IIRC that's how Express handles the incoming/outgoing logic for middleware
When we say it modifies response object also, what does it mean, from where does the object response come from?The
response
obect is part of Nodejs: every HTTP request creates a request
and response
object that is passed through to any function that handles API calls.yep I see, hmm just for the "then runs backwards through the list right after the response is sent", I'm a bit confused about that, does a middleware do that?
It's been a while since I've used Express so I could be mis-remembering this, but…
From what I remember, you code middleware something like this:
So it'll log
runs first
then the next middleware in the chain runs, etc until it finally gets to the route handler. Then the middleware chain is run back until runs last
is logged. And at that point it's done.
So basically any middleware code before the next()
call is run first. Then the route handler. Than any code after the next()
call is run. I think.yep I see, thanks !