Middleware, Headers, Cookies and the Request Lifecycle
Understand request interception, middleware use cases, cookies, headers, redirects, rewrites, and where security and routing logic belongs.
Understanding the Request Lifecycle
A request passes through several layers before the final UI or API response is returned. Depending on the application and deployment platform, this can involve edge infrastructure, middleware or proxy logic, routing, server rendering, data access, and caching.
Understanding this lifecycle helps explain why a redirect may happen before a page executes or why a response can be cached even though the page contains server code.
- A request can pass through multiple infrastructure layers.
- Caching and routing decisions can happen before rendering.
- Understanding the lifecycle makes debugging easier.
Middleware Use Cases
Middleware is useful for lightweight request-level logic such as redirects, rewrites, locale detection, and certain authentication-related routing decisions.
It should not become a general-purpose business-logic layer. Expensive database operations, complex business workflows, and large application services usually belong elsewhere.
Always consider the runtime and deployment constraints of middleware before importing libraries that depend on Node-specific APIs.
- Use middleware for lightweight request interception.
- Keep heavy business logic out of middleware.
- Understand the runtime supported by your deployment environment.
Redirects and Rewrites
A redirect tells the client or browser to use another URL. A rewrite maps one URL to another destination without necessarily changing the visible browser URL.
Redirects are useful when a resource has moved or authentication requires navigation to a login page. Rewrites can be useful for proxying or creating clean public URLs over internal paths.
Choose between them based on whether the browser should know that the URL changed.
- Redirects change navigation.
- Rewrites can preserve the visible URL while changing the destination.
- URL behavior should be predictable and documented.