1. What is Middleware
When a browser sends a request to your UrbanCart API, it doesn't jump straight to your route handler. Before the route runs, Express passes the request through a series of middleware functions โ small, focused functions that each do one job.
A middleware function receives three arguments (or four for error middleware): req, res, and next. After doing its work, it must either call next() to hand off to the next middleware, or send a response itself. If it does neither, the request hangs forever.
A customer adds an item to their cart. The request hits the UrbanCart API and travels through: JSON parser (reads the request body) โ Logger (records the timestamp and method) โ Auth check (verifies the token) โ Route handler (updates the cart in the database) โ Response sent back to the browser. Each step is a middleware function.
next() to continue the chain, or call res.send() / res.json() to end it. Forgetting this is one of the most common Express bugs.
2. app.use()
app.use() is how you register middleware in Express. You can apply it globally (every request) or scope it to a specific path prefix.
app.use(fn)
No path prefix โ middleware runs on every incoming request regardless of the route or HTTP method.
app.use('/path', fn)
Scoped to a path prefix. Only requests starting with /path will trigger this middleware.
app.use(express.json()) before any route handler that reads req.body.
3. Built-in Middleware
Express ships with three commonly-used built-in middleware functions. You don't need to install anything extra โ they come with Express itself.
| Middleware | What it does | When to use |
|---|---|---|
express.json() |
Parses incoming JSON request bodies into req.body |
Any API that receives JSON (REST APIs) |
express.urlencoded() |
Parses URL-encoded form data into req.body |
Traditional HTML form submissions |
express.static() |
Serves static files (HTML, CSS, images) from a directory | Serving a built React app or public assets |
4. Custom Middleware
The real power of middleware is writing your own. Two patterns you'll use in almost every Express application are a request logger and an authentication check.
Custom Logger
A logger records every incoming request with the HTTP method, path, status code, and response time. This is invaluable for debugging in production.
Auth Middleware
An auth middleware checks whether the request carries a valid Authorization header before allowing access to protected routes. If the token is missing or wrong, it short-circuits the chain and returns a 401.
Browsing products on UrbanCart is public โ anyone can GET /api/products. But adding to cart and checking out require a logged-in user. By scoping authMiddleware to app.use('/api/cart', authMiddleware), all cart routes are protected without repeating the auth check in every handler.
5. Third-Party Middleware
The Express ecosystem has hundreds of middleware packages on npm. Two that nearly every production API uses are cors and morgan.
cors โ Cross-Origin Resource Sharing
Browsers block JavaScript from making requests to a different domain by default. When your React frontend at localhost:5173 calls your Express API at localhost:3000, the browser refuses it unless your API sends the right CORS headers. The cors package handles this automatically.
morgan โ HTTP Request Logger
Morgan is a polished, configurable request logger. It's more robust than a custom logger and supports several built-in formats. 'dev' is color-coded and great for development.
6. Error Handling Middleware
Regular middleware takes three arguments. Error-handling middleware takes four โ (err, req, res, next). Express identifies it by the four-argument signature and routes any errors passed via next(err) directly to it, skipping all regular middleware.
(err, req, res) with only 3 parameters, Express treats it as regular middleware, not an error handler. You must declare all four, even if you don't use next.
In your route handlers, pass errors to the error middleware by calling next(err) instead of next(). This immediately skips all remaining regular middleware and route handlers.
7. Middleware Execution Order
Middleware executes in the exact order you register it with app.use() or app.get(). Getting this order wrong causes subtle, hard-to-debug issues โ like auth checks that run before the JSON body is parsed, or error handlers that are never reached.
Request
Log request
CORS headers
Parse body
Check token
Business logic
Catch errors
JSON sent
- Putting
express.json()after routes โreq.bodyis undefined in those routes - Placing auth middleware before
express.json()โ you can't read the token from the body - Registering the error handler before routes โ errors from routes never reach it
- Forgetting
next(err)โ errors swallowed silently, request hangs
Visualizing the Chain
When a request comes in, Express walks down the middleware stack in order. Each layer either passes the baton with next(), sends a response (ending the chain), or calls next(err) to jump straight to the error handler.
Quiz
next() inside a middleware function do?express.json() middleware do?cors middleware do in an Express API?You completed the Middleware & Error Handling quiz.
You just built a production-grade middleware chain.
Now build a backend career that scales.
Join the Best AI Programs โ three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses โ