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, auth, parsing, and any cross-cutting logic that applies across many routes.

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
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
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
Quick check
A middleware runs console.log("hi") but never calls next() or sends a response. What does the client see?
Go deeper
- 1Write a custom logging middleware that prints method, path and response time.
- 2Learn the middleware execution order and the role of calling `next()`.
- 3Apply middleware globally, per-router, and per-route, and notice the difference.
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.