Understanding Middleware in Express.js
⏱ Estimated reading time: 3 min
Middleware in Express.js is a function that executes during the request-response cycle. It can modify the request or response objects, end the request-response cycle, or call the next middleware in the stack.
Think of middleware as layers through which a request passes before reaching the final route handler.
1. Types of Middleware
-
Application-Level Middleware
-
Bound to an instance of
express()usingapp.use()orapp.METHOD(). -
Example: Logging, authentication, request parsing.
-
-
Router-Level Middleware
-
Bound to an instance of
express.Router(). -
Helps organize routes and middleware for specific route groups.
-
-
Built-in Middleware
-
Express provides some built-in middleware, e.g.:
-
express.json()– Parses JSON request bodies. -
express.urlencoded()– Parses URL-encoded request bodies.
-
-
-
Third-Party Middleware
-
Middleware provided by npm packages, e.g.:
-
cors– Enable Cross-Origin Resource Sharing. -
morgan– HTTP request logging. -
body-parser– Parsing request bodies (now mostly replaced byexpress.json()).
-
-
-
Error-Handling Middleware
-
Middleware that catches errors and sends responses.
-
Signature:
(err, req, res, next).
-
2. Middleware Function Signature
-
req– Request object -
res– Response object -
next– Function to pass control to the next middleware
3. Using Middleware
Example 1: Application-Level Middleware
Example 2: Using Built-in Middleware
Example 3: Error-Handling Middleware
4. Middleware Execution Flow
-
Incoming request hits first middleware in the stack.
-
Middleware modifies
req/resor performs actions. -
Calls
next()→ passes control to next middleware or route handler. -
If
next()is not called → request stops here. -
Errors can be passed using
next(err)→ goes to error-handling middleware.
5. Key Points
-
Middleware can be global (
app.use) or route-specific. -
Order of middleware matters.
-
Middleware is essential for tasks like:
-
Logging requests
-
Parsing request bodies
-
Authentication & authorization
-
Error handling
-
Middleware is one of the core concepts in Express.js, making it flexible and modular.
Register Now
Share this Post
← Back to Tutorials