Middleware is the single most important idea in Express. Logging, reading JSON bodies, checking who's logged in, handling errors: all of it is middleware. This chapter explains how a request flows through middleware, how next() works, how to handle errors properly, and what every common HTTP status code means.
In this chapter you'll learn
- what middleware is, and how
next()passes a request along - application-level, router-level, built-in, third-party and error-handling middleware
- how to write an auth middleware that protects routes
app.use()vsapp.all()- how error-handling middleware works, and how async errors differ in Express 4 and 5
- the HTTP status codes you'll use every day
Before you start: read Chapter S2 04: Routing and Request handlers. Code: DevTinder backend repository.
What is middleware?
A middleware is a function that runs between the request arriving and the response being sent. It gets three arguments:
function myMiddleware(req, res, next) {
// 1. look at or change req / res
// 2. then EITHER send a response, OR call next() to continue
}function myMiddleware(req, res, next) {
// 1. look at or change req / res
// 2. then EITHER send a response, OR call next() to continue
}Think of airport security. Before you reach the gate (the route handler), you pass through several checkpoints in order: ticket check, ID check, baggage scan. Each checkpoint either lets you through (next()) or stops you (sends a response, like "401 Unauthorized"). The gate never sees passengers who were stopped.
A middleware can:
- run any code (log the request, measure time)
- change
reqorres(addreq.userafter checking a token) - end the request by sending a response
- call
next()to pass control to the next middleware or route handler
Route handlers are middleware too: they're simply the last function in the chain, the one that sends the response.
How next() works
app.get(
"/user",
(req, res, next) => {
console.log("Handler 1");
next(); // go to the next function
},
(req, res, next) => {
console.log("Handler 2");
res.send("Response from handler 2"); // send the response: the chain ends here
}
);app.get(
"/user",
(req, res, next) => {
console.log("Handler 1");
next(); // go to the next function
},
(req, res, next) => {
console.log("Handler 2");
res.send("Response from handler 2"); // send the response: the chain ends here
}
);Express keeps all the matching middleware and handlers in a stack, in the order you registered them. It runs the first one and moves to the next one only when next() is called. Nothing runs automatically.
Every middleware must do exactly one of two things:
| What it does | Result |
|---|---|
calls next() | the request continues down the chain |
sends a response (res.send, res.json, res.status(...).send) | the chain stops; the client gets the response |
| neither | ❌ the request hangs: the client waits until it times out |
| both | ❌ a later handler tries to respond again: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client |
// ❌ Responds AND calls next()
app.get("/user", (req, res, next) => {
res.send("Response 1");
next();
}, (req, res) => {
res.send("Response 2"); // ERR_HTTP_HEADERS_SENT
});// ❌ Responds AND calls next()
app.get("/user", (req, res, next) => {
res.send("Response 1");
next();
}, (req, res) => {
res.send("Response 2"); // ERR_HTTP_HEADERS_SENT
});Skipping the rest of a route: next("route")
Calling next("route") skips the remaining handlers of the current route and jumps to the next route that matches:
app.get("/skip", (req, res, next) => {
console.log("Handler A runs");
next("route"); // skip handler B
}, (req, res) => {
res.send("Handler B (skipped)");
});
app.get("/skip", (req, res) => {
res.send("Next matching route"); // this one answers
});app.get("/skip", (req, res, next) => {
console.log("Handler A runs");
next("route"); // skip handler B
}, (req, res) => {
res.send("Handler B (skipped)");
});
app.get("/skip", (req, res) => {
res.send("Next matching route"); // this one answers
});next("route") only works in app.get/post/... and router.get/post/..., not in app.use().
Types of middleware
| Type | How it's added | Example |
|---|---|---|
| Application-level | app.use(fn) or app.use("/path", fn) | a logger for every request |
| Route-level | as extra arguments to one route | app.get("/profile", userAuth, handler) |
| Router-level | router.use(fn) on an express.Router() | middleware for one group of routes (Chapter S2 11: Diving into the APIs and Express router) |
| Built-in | comes with Express | express.json(), express.static("public") |
| Third-party | installed from npm | cookie-parser (Chapter S2 10: Authentication, JWT & Cookies), cors (Chapter S2 16: DevTinder UI - Part 2) |
| Error-handling | four parameters (err, req, res, next) | the global error handler below |
A logger for every request
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
next();
});app.use((req, res, next) => {
console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
next();
});Because it's registered first with no path, it runs for every request.
Protecting routes: an auth middleware
The course's first real middleware checks whether the caller is an admin. Here's the idea with a hardcoded token (in Chapter S2 10: Authentication, JWT & Cookies you'll replace this with real JWT verification):
// middlewares/auth.js
const adminAuth = (req, res, next) => {
const token = "xyz"; // pretend we read this from the request
const isAdmin = token === "xyz";
if (!isAdmin) {
return res.status(401).send("Unauthorized"); // stop here
}
next(); // allowed: continue
};
module.exports = { adminAuth };// middlewares/auth.js
const adminAuth = (req, res, next) => {
const token = "xyz"; // pretend we read this from the request
const isAdmin = token === "xyz";
if (!isAdmin) {
return res.status(401).send("Unauthorized"); // stop here
}
next(); // allowed: continue
};
module.exports = { adminAuth };// app.js
const { adminAuth } = require("./middlewares/auth");
app.use("/admin", adminAuth); // runs for EVERY /admin/... route
app.get("/admin/getAllData", (req, res) => res.send("All data"));
app.delete("/admin/deleteUser", (req, res) => res.send("User deleted"));
app.get("/user/data", userAuth, (req, res) => { // route-level: just this one route
res.send("User data");
});// app.js
const { adminAuth } = require("./middlewares/auth");
app.use("/admin", adminAuth); // runs for EVERY /admin/... route
app.get("/admin/getAllData", (req, res) => res.send("All data"));
app.delete("/admin/deleteUser", (req, res) => res.send("User deleted"));
app.get("/user/data", userAuth, (req, res) => { // route-level: just this one route
res.send("User data");
});Writing the check once as middleware, instead of copying it into every route, is the whole point.
app.use() vs app.all()
Both run for every HTTP method. The difference is path matching:
| Request | app.use("/user", fn) | app.all("/user", fn) |
|---|---|---|
GET /user | runs | runs |
POST /user | runs | runs |
GET /user/42/photos | runs (starts with /user) | does not run (exact path only) |
GET /users | does not run (/users isn't the segment /user) | does not run |
Also, inside app.use("/user", fn), Express strips the mount path: req.url is /42/photos, while req.originalUrl keeps the full /user/42/photos.
Use app.use for middleware and for mounting routers; use app.all when one exact route should accept every method.
Error handling
Error-handling middleware
An error-handling middleware has four parameters:
app.use((err, req, res, next) => {
console.error(err); // log the details for yourself
res.status(500).send("Something went wrong"); // send a safe message to the client
});app.use((err, req, res, next) => {
console.error(err); // log the details for yourself
res.status(500).send("Something went wrong"); // send a safe message to the client
});- Express recognises it by the number of parameters (four). The name
errdoesn't matter, but the count does. If you write(err, req, res)with only three, Express treats it as a normal middleware and your error handler never runs (we tested this: Express skips it and uses the next four-parameter handler). - Register it after all routes, at the very bottom, so errors from everything above reach it.
- When an error happens, Express skips all normal middleware and jumps straight to the next error handler.
How errors reach the error handler
| How the error happens | Express 4 | Express 5 |
|---|---|---|
throw in a synchronous handler | caught ✅ | caught ✅ |
next(err) | caught ✅ | caught ✅ |
throw / rejected Promise in an async handler | ❌ not caught: the request hangs and Node logs an unhandledRejection | caught ✅ |
We tested this table on Express 4.22 and Express 5.3. On Express 4, wrap async code yourself:
app.get("/getUserData", async (req, res, next) => {
try {
const user = await User.findOne({ emailId: req.query.emailId });
res.send(user);
} catch (err) {
next(err); // hand the error to the error handler
}
});app.get("/getUserData", async (req, res, next) => {
try {
const user = await User.findOne({ emailId: req.query.emailId });
res.send(user);
} catch (err) {
next(err); // hand the error to the error handler
}
});In Season 2 you'll also see try/catch blocks that send the error response themselves (res.status(400).send("ERROR: " + err.message)). That works on both versions and keeps each route's error message specific.
A 404 handler for unknown routes
If no route matches, Express sends a basic Cannot GET /something page. To send your own, add a normal middleware after all routes (and before the error handler):
app.use((req, res) => {
res.status(404).json({ message: "Route not found" });
});app.use((req, res) => {
res.status(404).json({ message: "Route not found" });
});Never send err.stack or raw database errors to the client in production. They reveal file paths, library versions and query details that help attackers. Log them on the server; send the user a short, safe message.
HTTP status codes
A status code is a three-digit number in every response that tells the client what happened. The first digit gives the category:
| Range | Category | Meaning |
|---|---|---|
| 1xx | Informational | request received, continuing (rarely seen directly) |
| 2xx | Success | it worked |
| 3xx | Redirection | look somewhere else |
| 4xx | Client error | the request is wrong |
| 5xx | Server error | the server failed |
The ones you'll use most:
| Code | Name | When to use it |
|---|---|---|
| 200 | OK | general success (GET, PATCH, login) |
| 201 | Created | a new resource was created (signup, sending a request) |
| 204 | No Content | success with no body (some deletes) |
| 301 / 302 | Moved Permanently / Found | redirects: permanent vs temporary |
| 304 | Not Modified | the client's cached copy is still valid |
| 400 | Bad Request | invalid input: missing fields, wrong format, validation failed |
| 401 | Unauthorized | not logged in: missing, invalid or expired token |
| 403 | Forbidden | logged in, but not allowed to do this |
| 404 | Not Found | the resource or route doesn't exist |
| 409 | Conflict | the request conflicts with current data (duplicate email or connection request) |
| 429 | Too Many Requests | rate limit exceeded |
| 500 | Internal Server Error | an unexpected bug or crash on the server |
| 502 | Bad Gateway | a proxy (like Nginx) got a bad response from the app behind it (Chapter S3 02: Nginx and Backend Node App Development) |
| 503 | Service Unavailable | the server is overloaded or down for maintenance |
The 401 vs 403 difference is a favourite interview question: 401 = "who are you?", 403 = "I know who you are, and you can't do this."
Setting a status in Express:
res.status(201).json({ message: "User created" });
res.status(400).send("Invalid email");
res.sendStatus(204); // status with its default text, no bodyres.status(201).json({ message: "User created" });
res.status(400).send("Invalid email");
res.sendStatus(204); // status with its default text, no bodyCommon mistakes
- Forgetting
next()in a middleware that doesn't respond: the request hangs. - Responding and calling
next():ERR_HTTP_HEADERS_SENT. - Error handler with three parameters: it's never treated as an error handler.
- Error handler registered before the routes: errors from routes below it never reach it.
- Unhandled errors in
asynchandlers on Express 4: requests hang. - Always answering 200, even for errors: the frontend can't tell success from failure.
Key takeaways
- Middleware =
(req, res, next): it runs in order, and must either respond or callnext(), never both, never neither. - Middleware types: application, route, router, built-in (
express.json), third-party, and error-handling. - Put shared logic like auth checks in middleware instead of repeating it in every route.
app.use(path)matches all methods and sub-paths;app.all(path)matches all methods on the exact path.- Error handlers have four parameters and go last. Express 5 catches async errors; Express 4 needs
try/catch+next(err). - Use the right status codes: 400 bad input, 401 not logged in, 403 not allowed, 404 not found, 500 server bug.
Interview questions
Q1. What is middleware in Express?
Middleware is a function with the signature (req, res, next) that runs during the request–response cycle. It can execute code, modify req and res, end the cycle by sending a response, or pass control to the next middleware with next(). Express runs middleware in the order it's registered. Examples: express.json(), a logger, an authentication check.
Q2. What happens if a middleware neither calls next() nor sends a response?
The request hangs. Express waits for the middleware to finish the request or pass it on, so the client keeps waiting until it times out. No later middleware or route runs.
Q3. How does Express know a middleware is an error handler?
By its arity: it must declare exactly four parameters, (err, req, res, next). Express checks the function's length. A function with three parameters is treated as normal middleware, even if the first one is named err. Error handlers are registered after all routes.
Q4. How do you handle errors in async route handlers?
In Express 5, a rejected promise or throw inside an async handler is passed to the error handler automatically. In Express 4, it isn't: the request hangs. Wrap the code in try/catch and call next(err), or use a small wrapper like const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);.
Q5. What is the difference between app.use() and app.all()?
Both run for all HTTP methods. app.use(path) also matches every sub-path (/user matches /user/42) and strips the mount path from req.url, so it's used for middleware and routers. app.all(path) matches the exact path only, like a normal route.
Q6. What is the difference between status codes 401 and 403?
401 Unauthorized means the client is not authenticated: no credentials, or invalid or expired ones. Logging in may fix it. 403 Forbidden means the client is authenticated but lacks permission for this action; logging in again won't help.
Q7. What are the types of middleware in Express?
Application-level (app.use), router-level (router.use), route-level (passed to a single route), built-in (express.json, express.urlencoded, express.static), third-party (cors, cookie-parser, helmet, morgan) and error-handling middleware (four parameters).
Q8. What does "Cannot set headers after they are sent to the client" mean?
It's ERR_HTTP_HEADERS_SENT: the code tried to send a second response (or set a header) after the response was already sent. Common causes: calling res.send twice, responding and calling next(), or missing a return after an early res.status(400).send(...) inside an if.
What's next
Your routes don't store anything yet. In Chapter S2 06: Database, Schema, Models & Mongoose you'll connect the app to MongoDB with Mongoose, define a schema and model for users, and save your first document.