Request/Response Lifecycle
The full journey of a request, from arriving at your server to the response being sent back.
What is it?
Every backend interaction has the same shape: something asks (a request) and the server answers (a response). In between, several steps happen in a predictable order.
Knowing that sequence, the request/response lifecycle, helps you decide where logging and auth checks belong, and why a response sometimes never arrives.
Explain like I'm 10
A drive-through: your car pulls up (a request arrives), you pass the ordering speaker and payment window (middleware), your order reaches the kitchen (the route handler), the food is made (business logic runs), and it's handed to you at the pickup window (the response is sent). If any step fails, you never reach the end.
Examples
Tracing one request through the whole lifecycle
app.use(express.json()); // 1. parse the request body
app.use(logger); // 2. log the request
app.get("/products/:id", (req, res) => { // 3. matched route runs
const product = findProduct(req.params.id); // 4. business logic
if (!product) {
return res.status(404).json({ error: "Not found" }); // 5a. response
}
res.json(product); // 5b. response
});Every request to this server goes through the same numbered stages, even though the data differs each time.
A request that ends early
app.use((req, res, next) => {
if (isBlocked(req.ip)) {
return res.status(403).send("Forbidden"); // lifecycle ends here
}
next();
});
app.get("/data", (req, res) => {
res.json(getData()); // never reached for blocked IPs
});The lifecycle doesn't always reach the route handler. Any middleware can send a response and end it early.
How it works
A request usually goes through these steps:
- It arrives at the server.
- The framework parses headers and the body.
- Global middleware runs, in order.
- The framework matches a route by method and path.
- Route-specific middleware runs.
- The route handler runs the app logic, often with a database call.
- A response is built with a status code, headers and a body.
- The response is sent back over the network, closing the request.
Once a response is sent, nothing more can be sent for that request.
Client
│ request
▼
[Parsing] → [Global middleware] → [Route matching]
│
▼
[Route-specific middleware]
│
▼
[Route handler]
│
▼
[Build response]
│
▼
Client ◄──────────────── response ─────┘Why does it exist?
A fixed lifecycle gives every developer a shared picture of where each piece of code runs relative to the rest. That's essential for debugging (why did this request never get logged?) and for deciding where new logic belongs.
When to use it
Use it when deciding where new logic belongs (global middleware, one route, or inside the handler) or when debugging an unexpected request.
When not to use it
You don't "use" the lifecycle directly; every request already runs through it. It applies to any HTTP backend, though very different systems (like a raw TCP server with no framework) may be structured differently.
Common mistakes
Sending a second response after one was already sent, which causes a runtime error.
Not noticing that earlier middleware or a handler already ended the lifecycle, so later code never runs.
Putting expensive, request-specific work in global middleware, so it runs on every request, even ones that don't need it.
Practice exercises
- Easy:
List, in order, the stages a GET request goes through in an Express app with one logging middleware and one route.
- Medium:
Write a small Express app where middleware blocks requests without a specific header. Trace what happens to a blocked request and an allowed one.
- Hard:
Explain what error you'd expect if a route handler calls
res.json()twice for the same request, and why.
Interview questions
What is the request/response lifecycle?
The ordered steps a request goes through from arriving at a server to a response being sent: parsing, middleware, routing, the handler, and the final response.
Can the lifecycle end before reaching the route handler?
Yes. Any middleware can send a response itself and not call next(), ending the lifecycle early.
What happens if code tries to send a response after one has already been sent for the same request?
It typically causes a runtime error, since a single request can only be answered with one response.
List, in order, the main stages a request passes through in a typical Express app, from arrival to response.
Arrival, parsing (headers and body), global middleware, route matching, route-specific middleware, the route handler running the app logic, building the response (status, headers, body), and sending it back over the network.
Why does body-parsing like `express.json()` need to run before any middleware or handler that reads `req.body`?
req.body only exists after something reads and parses the raw bytes. Anything registered before the parser sees req.body as undefined.
A global middleware checks `isBlocked(req.ip)` and returns a 403 without calling `next()`. What happens to that request's route handler?
It never runs. next() was never called, so the lifecycle ends at that middleware and the route handler is skipped for blocked requests.
Why is understanding the lifecycle useful for debugging "why did this request never get logged"?
If logging middleware comes after something that can short-circuit the request (like an early auth check or blocklist), rejected requests never reach the logger. Knowing the fixed order tells you exactly which stages a request passed through.
Where should logic that applies to every request go versus logic for just one route — early in the chain, or inside a specific handler?
Logic for every (or nearly every) request goes in global middleware registered early, before routing picks a handler. Logic for one endpoint goes in that route's handler or route-specific middleware, so other requests don't pay for it.
Why can a single request only ever receive one response, and what would break if that weren't true?
HTTP expects one status line, one set of headers and one body per request. A second response would write conflicting data to a connection the client already treats as answered, so frameworks throw an error instead of allowing it.
In the drive-through analogy, what corresponds to "the food gets made," and what corresponds to "the pickup window"?
"The food gets made" is the route handler running its business logic. "The pickup window" is the final response being built and sent, ending the lifecycle.
A route handler calls `res.json(product)`, and later in the same function unconditionally also calls `res.status(404).json({...})`. What bug results?
The first call already sent a response, so the second throws a "headers already sent" error. Fix it by returning after the first response or making the second call conditional, so only one runs.
Why does putting expensive, request-specific work in global middleware hurt performance even for requests that don't need it?
Global middleware runs on every request that passes through it, whether or not the request needs the work. An expensive step there adds latency to requests that never needed it.
With `app.use(express.json())`, then `app.use(logger)`, then a route, where does malformed JSON in the request body most likely cause a failure?
At the express.json() stage, before logger or the handler run. The parser fails on the malformed JSON and usually triggers an error response, ending the lifecycle early.
Give an example where a request not reaching the route handler is the intended, correct behavior.
Middleware rejecting an unauthenticated request with a 401 before a protected route. Ending early is the desired outcome here, not a bug.
What determines whether route-specific middleware runs before or after global middleware for a given request?
Global middleware is registered at the app level and runs first, because routing hasn't happened yet. Route-specific middleware only runs once the framework has matched the request to that route.
Why does the lifecycle model apply to essentially every HTTP-based backend, regardless of framework or language?
HTTP is request in, response out. Any server built on it, in any language or framework, must receive a request, process it, and send exactly one response. Middleware and routing are details layered on that shape.
To add authentication to just one route without affecting others, at which stage would you add that logic?
As route-specific middleware attached only to that route (or a group of routes), not global middleware, so other routes aren't affected.
From the client's point of view, can it tell whether a response came from an early short-circuiting middleware or the full lifecycle completing normally?
Not from the response shape alone: either way it gets a status code, headers and a body. Only the response's content (and knowing the API) shows whether it's a rejection partway through or the handler's real result.
Why is "building the response" treated as a distinct stage from the route handler having already computed a result?
Computing a result (like fetching a product) and turning it into an HTTP response (status code, headers, serialized body) are different jobs. Having data doesn't finish the handler's work; it still has to decide how that data becomes a proper response.
Two middleware functions and the route handler all set the same header. Which value does the client actually receive, and why?
The last call wins, because setting a header overwrites the previous value. The route handler runs after the earlier middleware, so its value usually takes effect, unless middleware registered after the handler (unusual) overwrites it again.