Middleware in Express.js - Enhancing Your Web Applications
By Łukasz Kallas
- Published on
Sharing
This post explores what middleware is, how to use it in Express.js, and includes a hands-on YouTube tutorial to help you get started.
What is Middleware?
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions can perform various tasks such as logging, authentication, data parsing, and error handling.
Types of Middleware
- Application-level Middleware: Bound to an instance of express using app.use() or app.METHOD().
- Router-level Middleware: Bound to an instance of express.Router().
- Error-handling Middleware: Defined with four arguments and used for error handling.
- Built-in Middleware: Provided by Express.js (e.g., express.json()).
- Third-party Middleware: Provided by the community (e.g., morgan, cors).