Express Middleware - 401-advanced-javascript-davetrost/alchemy-fsjs-fall-2019 GitHub Wiki
Express Middleware
Reading Materials
JsWiz Video
Surprisingly, we've been using express middleware all along, with the app.uses() call, we just didn't know what it meant. Now, armed with a better understanding of chaining events, this makes total sense! The diagram shown in the video by JsWiz is a great visual about how and where middleware takes effect:

It's also nice to know there is an alternate way to instantiate middleware. The app.uses('middleware') call instantiates middleware for all routes defined after the line number of the app.uses() call. A different method instantiates the middleware only to selected routes. The way to do this is: app.METHOD('route-name', 'middleware', 'middleware', 'final handler')
Using Express Middleware
Middleware comes in 5 forms:
- Application-level: middleware that you define and apply with
app.use()so that it takes effect for all methods - Router-level: middleware that you define and apply with
route.use()so that it takes effect for one router - Error-handling: middleware that deals with error conditions
- Built-in: the following 3 functions are built-in: express.static, express.json, express.urlencoded
- Third-party: needs to be installed and required as a Node.js module. Then it can be loaded at the application or router level.
Middleware on TutorialPoint
A listing of commonly used third-party middleware:
- body-parser
- cookie-parser
- express-session