Beginner · Node.js and Express · topic 14 of 54 · 25 min
Middleware: checks before your handler
Explanation
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.
next() passes the request on
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([]);
});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.
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 errorsCommon middleware
| Middleware | What it does |
|---|---|
| Logger | Prints the method, URL and time of each request |
| express.json() | Reads a JSON body into req.body |
| Auth check | Stops the request with 401 if the user or key is not valid |
| CORS | Says which websites may call this API from the browser |
| Error handler | Turns any thrown error into a clean JSON response |
An auth check and an error handler
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' });
}Watch the lesson
Middleware: checks before your handler · 1/7
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)
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.
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.
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
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.