Almost every Express app I see has an app.use statement for middleware but I haven’t found a clear, concise explanation of what middleware actually is and what the app.use statement is doing. Even the express docs themselves are a bit vague on this. Can you explain these concepts for me please?
Almost every Express app I see has an app.use statement for middleware but I
Share
middleware
I’m halfway through separating the concept of middleware in a new project.
Middleware allows you to define a stack of actions that you should flow through. Express servers themselves are a stack of middlewares.
Then you can add layers to the middleware stack by calling
.useA layer in the middleware stack is a function, which takes n parameters (2 for express,
req&res) and anextfunction.Middleware expects the layer to do some computation, augment the parameters and then call
next.A stack doesn’t do anything unless you handle it. Express will handle the stack every time an incoming HTTP request is caught on the server. With middleware you handle the stack manually.
A more complete example :
In express terms you just define a stack of operations you want express to handle for every incoming HTTP request.
In terms of express (rather than connect) you have global middleware and route specific middleware. This means you can attach a middleware stack to every incoming HTTP requests or only attach it to HTTP requests that interact with a certain route.
Advanced examples of express & middleware :