Stop 05 · Backend with Node.js & ExpressTopics · 4/8

Middleware

Part of the Full Stack Developer Roadmap

In short

Logging, auth, body parsing, CORS: most of what an Express app does happens in middleware. Understand next() and the whole framework makes sense.

Functions that run between receiving a request and sending a response — used for logging, parsing, authentication, and any logic that should apply across many routes.

The mascot walks from a bag scanner through a ticket turnstile towards a metro platform.

Think of it like this

Metro station checkpoints

To reach the platform, you pass the bag scanner, then the ticket gate. Each checkpoint can wave you on or stop you. Middleware is a line of checkpoints every request walks through before it reaches your route.

Watch it happen

A request walking the middleware chain

Logger
JSON parser
Auth
Route
Response

1/5POST /orders arrives. The logger notes the method, path and start time, then calls next().

The big ideas

What you need to know

(req, res, next)

Middleware gets the request, the response, and next. Call next() to pass the request along.

Or end it right there

Middleware can send a response, like 401, and not call next. The route never runs.

Order is everything

Middleware runs in the order of app.use calls. Put the body parser before routes that read req.body.

Global or per route

app.use(logger) runs for all. app.get("/admin", requireAdmin, handler) runs only on that route.

See it in code

Walk through the code

js
1function logger(req, res, next) {2  const start = Date.now();3  res.on("finish", () => {4    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - start}ms`);5  });6  next();7}8 9function requireAuth(req, res, next) {10  const token = req.get("Authorization")?.replace("Bearer ", "");11  if (token !== process.env.API_TOKEN) return res.status(401).json({ error: "Unauthorised" });12  next();13}14 15app.use(logger, express.json());16app.post("/orders", requireAuth, (req, res) => res.status(201).json(req.body));

1/4Logger records the start time, logs when the response finishes, and passes control on.

The return before res.status(401) matters. Without it, the code would also call next() and try to respond twice.

Save yourself the pain

Common mistakes

Oops

Forgetting to call next(), so every request hangs forever.

Do this instead

Every middleware must either send a response or call next(). Check every branch.

Oops

Adding the auth middleware after the routes it should protect.

Do this instead

Middleware only affects routes added after it. Register it first, or pass it into the route directly.

Your mission

Write three middlewares

~25 min

Quick check

A middleware runs console.log("hi") but never calls next() or sends a response. What does the client see?

Go deeper

  1. 1Write a custom logging middleware that prints method, path and response time.
  2. 2Learn the middleware execution order and the role of calling `next()`.
  3. 3Apply an auth-checking middleware to a group of protected routes.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge