Controlling Requests with Next.js Proxy
Explore how to control incoming requests in Next.js using the proxy feature. Understand how to rewrite paths, redirect unauthenticated users, and modify headers to enhance routing, authentication, and performance with low-latency edge runtime.
In the previous lesson, we built API endpoints using route handlers. Now we’ll look at the Next.js Proxy, a feature that runs in front of all routes and lets us intercept requests before they complete. This is especially useful for cross-cutting concerns like authentication, A/B testing, and internationalization. These operations run on the edge runtime, allowing them to execute with low latency.
What is a Proxy?
In Next.js, a Proxy is a function that executes before a request is processed by a page or route handler. By creating a single proxy.js (or .ts) file in the root of our project, we can intercept every request that comes into our application.
The file must export a default function that programmatically alters the outcome of a request. This function can be used to let the request pass through unmodified, rewrite the destination path, redirect to a different URL, or even modify request and response headers.
export default function HomePage() {
return (
<div>
<h1>Home Page</h1>
<p>
Check the server console to see the interception message.
</p>
</div>
);
}Explanation:
Line 3: We define and export a function named
proxy. Next.js automatically detects and uses this function. It receives the incomingrequestobject as an argument, which gives us access to cookies, headers, and the URL.Line 4: We log the path of the incoming request. This is useful for debugging to see which routes are being processed.
Line 5: The
NextResponse.next()function is called to signal that the Proxy has completed its work and the request should continue to the next step in the processing chain, which is typically rendering a page or executing a route handler. Without this, the request would stall.
You'll see many messages on the console logged by the Proxy. That's because the Proxy runs for every single network call the browser makes, not just the initial page request. A single page load requires dozens of separate requests to fetch the HTML, all necessary JavaScript bundles, CSS files, and, in development mode, numerous background requests related to Hot Module Replacement (HMR). The Proxy is intercepting all of these network activities. ...