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.

๐Ÿ›’
UrbanCart Example
What happens when POST /api/cart is called

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.

server.js Basic middleware anatomy
The golden rule: Every middleware must either call 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.

server.js Global vs path-scoped middleware
๐ŸŒ

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.

Order matters: Middleware is executed in the order it is registered. Always call 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
server.js UrbanCart โ€” built-in middleware setup
Server console
UrbanCart API running on port 3000 Adding product 42 x2 to cart

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.

middleware/logger.js Request logger middleware
Server console output
[2026-04-18 09:23:14] GET /api/products 200 12ms [2026-04-18 09:23:15] POST /api/cart 401 3ms โ€” Unauthorized [2026-04-18 09:23:22] GET /api/products/42 200 8ms [2026-04-18 09:23:31] DELETE /api/cart/7 200 5ms

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.

middleware/auth.js Authorization header check
Server console โ€” unauthorized request blocked
[2026-04-18 09:23:15] POST /api/cart 401 3ms โ€” Unauthorized โ†’ Missing Authorization header from 192.168.1.45
๐Ÿ”
UrbanCart Example
Protecting the cart and checkout routes

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.

terminal Install 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.

server.js CORS middleware โ€” allow React dev server

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.

server.js Morgan HTTP logger
Morgan 'dev' output in terminal
GET /api/products 200 12.345 ms - 24 POST /api/cart 401 2.891 ms - 56 GET /api/products/42 200 7.612 ms - 148 DELETE /api/cart/7 200 4.203 ms - 22

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.

Signature is critical: Express uses the number of arguments to determine if a function is an error handler. If you write (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.
middleware/errorHandler.js Centralized error handling middleware

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.

routes/products.js Triggering the error handler with next(err)
Server console โ€” error handler in action
[ERROR] Product 999 not found โ†’ Responded: 404 Not Found [ERROR] name and price are required โ†’ Responded: 400 Validation Failed [ERROR] Cannot read properties of undefined (reading 'id') โ†’ Responded: 500 Internal Server Error

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.

UrbanCart API โ€” Request Lifecycle
Incoming
Request
โ†’
morgan
Log request
โ†’
cors
CORS headers
โ†’
express.json()
Parse body
โ†’
authMiddleware
Check token
โ†’
Route Handler
Business logic
โ†’
errorHandler
Catch errors
โ†’
Response
JSON sent
server.js Complete UrbanCart API โ€” correct middleware order
Server startup and request log
UrbanCart API on http://localhost:3000 GET /api/products 200 11.2 ms - 142 POST /api/cart 401 2.9 ms - 56 GET /api/products/42 200 8.1 ms - 389 POST /api/cart 201 14.7 ms - 88 โ† authenticated request succeeds
Common ordering mistakes:
  • Putting express.json() after routes โ€” req.body is 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.

concept How next() chains middleware together

Quiz

Question 1 of 5
What does calling next() inside a middleware function do?
Question 2 of 5
What is the correct signature of an Express error-handling middleware?
Question 3 of 5
What does the express.json() middleware do?
Question 4 of 5
Where should the error-handling middleware be placed in your Express app?
Question 5 of 5
What does the cors middleware do in an Express API?
0
/ 5
Great job!

You completed the Middleware & Error Handling quiz.

Next Lesson

REST API Design โ†’
You've mastered middleware chains. Next: design clean, RESTful APIs for UrbanCart.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

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 โ†’