Introduction to Middleware
Understand and harness the power of middleware in Express.js to create flexible and modular applications.
Middleware functions execute at different stages of the request-response cycle, allowing us to intercept requests, modify data, enforce rules, and pass execution along a defined sequence. They are fundamental to Express applications, acting as the glue that connects different parts of our app.
In this lesson, we will focus on understanding what middleware is, how it executes, and how it fits into Express’s architecture.
What is middleware?
Middleware is a function that typically runs before the final request handler, but it can also execute after one—for example, during error handling or response modification. It allows us to process incoming requests, modify responses, and control execution flow.
Every middleware function receives three parameters:
req
: This is the request object.res
: This is the response object.next
: This function passes control to the next middleware or route handler.
How middleware executes in Express.js
Middleware functions execute in the order they are registered using app.use()
. When a request is made, Express processes middleware from top to bottom, invoking each middleware function sequentially.
Get hands-on with 1400+ tech skills courses.