ExpressJS Middleware: A Beginner’s Guide
In the world of backend development, Express.js middleware is a core concept that every developer must understand. Middleware functions in Express.js are essential for handling requests, responses, and adding modular, reusable functionality to applications.
In this guide, we’ll explore what middleware is, how it works in Express.js, why it’s so powerful, and how to implement it effectively with 10 practical examples. Whether you’re a beginner or an intermediate developer, this article will give you a complete understanding of Express.js middleware.
ExpressJS Middleware: What It Is
Middleware in Express.js refers to functions that execute during the request-response cycle. These functions have access to the request object (req
), the response object (res
), and the next()
function that triggers the next middleware.
Middleware functions are the perfect place to modify the req
and res
objects with relevant information. For instance, after a user has logged in, you could fetch their user details from a database, and then store those details in res.user
.
Key Features:
Can execute any code.
Can modify the
req
andres
objects.Can end the request-response cycle.
Can call the next middleware in the stack.
How Middleware Works
When a request hits your Express app, it travels through a chain of middleware functions before reaching the final route handler. This flow gives you full control over the behavior of your application.
Types of Middleware in Express.js
Application-level middleware
Router-level middleware
Built-in middleware
Third-party middleware
Error-handling middleware
Let’s go through each type with real-world examples.
10 Practical Examples of Express.js Middleware
1. Logging Request Details
Intercepts every incoming request to your Express app.
Logs the HTTP method and URL of the request to the console.
Example: If someone accesses
GET /home
, it will log:GET /home
Calls
next()
to pass control to the next middleware or route handler.
2. Custom Authentication Middleware
What it does:
This is a custom authentication middleware in Express.js. It checks whether an incoming HTTP request has a specific token in its headers.
req.headers.token
:
This reads thetoken
value from the request headers (e.g.,Authorization: secret
in Postman or curl).if (req.headers.token === 'secret')
:
Checks if the token is exactly'secret'
. This is a simple security check.next()
:
If the token is valid,next()
is called to pass control to the next middleware or route handler.res.status(403).send('Forbidden')
:
If the token is missing or incorrect, it sends a 403 Forbidden response and stops the request from proceeding.app.use(authenticate)
:
Registers the middleware globally — so it runs on all routes.
3. Router-level Middleware
What’s Happening Here:
express.Router()
:
Creates a new instance of a router in Express.js. Routers help you organize routes into separate modules, like for user routes, product routes, etc.router.use(...)
:
This adds middleware to the router, not to the whole app. It will only run for requests that go through this specific router.Middleware function:
The function logs"Router-level middleware"
to the console every time a request hits any route under this router.next()
:
It tells Express to move on to the next middleware or route handler in the chain.
🔁 When does this run?
Whenever a request is made to any route defined under this router
, this middleware will run before the final route handler.
4. Built-in JSON Parsing Middleware
5. Third-party Middleware (e.g., morgan)
Morgan is a popular HTTP request logger middleware for Express.js.
It logs details about each incoming request to your app — super helpful for debugging and development!
6. Error-Handling Middleware
This is a custom error-handling middleware in Express.js. It catches errors that happen during the request-response cycle and handles them gracefully.
7. Middleware to Add Custom Headers
app.use(...)
:
Registers a middleware function that runs for every incoming request.res.setHeader('X-Powered-By', 'Capable Techies')
:
This sets a custom HTTP response header namedX-Powered-By
with the value'Capable Techies'
.next()
:
Passes control to the next middleware or route handler.
8. Session Management Middleware
This sets up session management in your Express app using the express-session
middleware. It allows you to store data for each user across multiple requests — like login status, cart items, or preferences.
9. Middleware to Handle CORS

CORS stands for Cross-Origin Resource Sharing. It’s a security feature implemented by web browsers that restricts web pages from making requests to a different domain than the one that served the web page.
By default, browsers block cross-origin requests for security reasons — unless the server explicitly allows them.
10. Request Time Logging
This middleware adds a new property called requestTime
to the req
(request) object, storing the timestamp of when the request was received.
req.requestTime = Date.now();
Saves the current time in milliseconds (since Jan 1, 1970) to the request object.next()
Passes control to the next middleware or route handler.
Best Practices for Using Middleware
Keep middleware functions small and focused.
Place global middleware at the top of the file.
Use separate files/modules for complex middleware.
Always call
next()
unless ending the response.Log and handle errors gracefully.
❓ FAQs About Express.js Middleware
Q1: What is the purpose of middleware in Express.js?
- A: Middleware allows developers to intercept and manipulate requests/responses during the lifecycle of a request.
Q2: Can middleware handle errors?
- Yes. Error-handling middleware is a special type with four parameters:
(err, req, res, next)
.
Q3: What’s the difference between app.use()
and app.get()
?
app.use()
applies middleware to all requests, whileapp.get()
targets GET requests for a specific route.
Q4: Can I use multiple middleware functions on a single route?
- Absolutely. You can pass multiple middleware functions to a route like this:
Q5: Is middleware synchronous or asynchronous?
- It can be either. You can use async functions and
await
inside middleware.
Conclusion
Understanding how middleware works in Express.js is fundamental to building powerful, scalable, and maintainable web applications. From handling requests to managing authentication and logging, middleware gives developers the tools to shape application behavior efficiently.
Keep experimenting, building, and exploring. If you’re ready to go deeper into backend magic, check out our other guides at Capable Techies.