Skip to content

Beginner · Node.js and Express · topic 14 of 54 · 25 min

Middleware: checks before your handler

Explanation

Middleware is a function that runs between the request arriving and your route handler. Each one can look at the request, change it, stop it with a response, or pass it on by calling next(). Loggers, JSON reading, login checks and error handlers are all middleware.

What is middleware?

In Express, middleware is a function with three inputs: req, res and next. It runs before your route handler. It can read or change req, send a response itself, or call next() to hand the request to the next function in line.

Think of it like this: Think of the entrance of a mall. First a guard checks your bag, then another scans your ticket for the movie, and only then you reach the shop. Each check is a middleware. If the bag check fails, you never reach the shop. If it passes, the guard waves you on to the next check: that wave is next().

next() passes the request on

javascript
function logger(req, res, next) {
  console.log(req.method, req.url);
  next(); // go on to the next middleware or route
}

app.use(logger);

app.get('/api/orders', (req, res) => {
  res.json([]);
});
Runs on a server with Node.js: a logger prints every request, then calls next().

Order matters

Express runs middleware in the order you add it with app.use, from top to bottom. A middleware only affects routes that come after it. So express.json() must come before routes that read req.body, and an auth check must come before the routes it protects.

javascript
app.use(logger);              // 1. every request is logged
app.use(express.json());      // 2. JSON body is read into req.body

app.get('/api/health', (req, res) => res.json({ ok: true })); // public

app.use('/api/admin', requireApiKey); // 3. only for /api/admin paths
app.get('/api/admin/orders', (req, res) => res.json(orders));

app.use(errorHandler);        // 4. last: catches errors
Runs on a server with Node.js: the chain from top to bottom.

Common middleware

MiddlewareWhat it does
LoggerPrints the method, URL and time of each request
express.json()Reads a JSON body into req.body
Auth checkStops the request with 401 if the user or key is not valid
CORSSays which websites may call this API from the browser
Error handlerTurns any thrown error into a clean JSON response

An auth check and an error handler

javascript
function requireApiKey(req, res, next) {
  if (req.headers['x-api-key'] !== process.env.API_KEY) {
    return res.status(401).json({ error: 'Missing or wrong API key' });
  }
  next();
}

// Error middleware has FOUR inputs: err comes first.
function errorHandler(err, req, res, next) {
  console.error(err);
  res.status(500).json({ error: 'Something went wrong' });
}
Runs on a server with Node.js: Express knows a function is an error handler because it has 4 parameters.
Tip: Put the error handler last, after all routes. When any route throws or calls next(err), Express skips the normal middleware and jumps to it.
Careful: A middleware must either send a response or call next(). If it does neither, the request hangs: the browser keeps loading until it times out. Also never do both, or you get the error "Cannot set headers after they are sent".

Watch the lesson

Middleware: checks before your handler · 1/7

Middleware: checks before your handler

Middleware are the checks a request passes before it reaches your route handler.

Prefer a video by a teacher? Find free videos on “express middleware explained next function tutorial” on YouTube ↗

In real life: A UPI merchant API

A payments company gives shops an API to check payments. Every request first passes a logger (for audits), then express.json(), then a rate limiter that stops a shop sending more than 100 requests a minute, then an API key check. Only then does the route handler read the payment from the database. If the database fails, the error handler at the end answers 500 with a neat JSON message instead of crashing the server.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a middleware requireApiKey(req, res, next). If req.headers["x-api-key"] is exactly "tdt-123", call next(). Otherwise do NOT call next; instead send res.status(401).json({ error: "Missing or wrong API key" }). The test gives you a fake res that works like Express: res.status(code) returns res, and res.json(body) saves the body.

Task 2 · Code · Javascript

Build a tiny version of what Express does inside. Write runMiddleware(middlewares, req). Each middleware is a function (req, next). Call them in order, passing the same req. Go on to the next one only if the current one called next(). Return true if every middleware called next() (the request reached the end), or false if one stopped it. An empty list returns true.

Task 3 · Practice

Plan the middleware chain for a food delivery API with these routes: GET /api/menu (public), POST /api/orders (logged-in users), GET /api/admin/reports (admins only). Write the app.use lines in the right order.

Quick quiz

Question 1

1.What does calling next() in a middleware do?

Question 2

2.A POST route always sees req.body as undefined. The likely cause?

Question 3

3.How does Express know a function is an error handler?

Question 4

4.A middleware neither sends a response nor calls next(). What happens?

Question 5

5.Where should the error-handling middleware be added?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: Express: your first web server