Chapter 4. Middleware
This chapter covers
- Writing middleware functions: a function with three arguments
- Writing and using error-handling middleware: a function with four arguments
- Using open source middleware functions, like Morgan for logging and express.static for serving static files
Without any framework like Express, Node gives you a pretty simple API. Create a function that handles requests, pass it to http.createServer, and call it a day. Although this API is simple, your request handler function can get unwieldy as your app grows.
Express helps to mitigate some of these issues. One of the ways it does this is through the use of something called middleware. Framework-free Node has you writing a single large request handler function for your entire app. Middleware allows you to break these request handler functions into smaller bits. These smaller functions tend to handle one thing at a time. One might log all of the requests that come into your server; another might parse special values of incoming requests; another might authenticate users.
Conceptually, middleware is the biggest part of Express. Most of the Express code you write is middleware in one way or another. Hopefully, after this chapter, you’ll see why!