Next.js 16 introduces a new file-convention: proxy.js / proxy.ts (often “Proxy”) which supersedes the older middleware.js. This feature allows you to intercept HTTP requests early (before routing/rendering) and run custom logic—redirects, rewrites, header manipulation, or forwarding (proxying) to another service.
In e-commerce (or any frontend/back-end scenario) this gives you a powerful tool: you can make your Next.js app act as a Backend-for-Frontend (BFF) layer, hiding upstream APIs, consolidating micro-services, enforcing auth, caching, rewriting URLs, etc. This aligns well with many of the architectures discussed in your referenced articles about Next.js for commerce (SSG/ISR/SSR strategies etc).
What is Proxy and when to use it
The Proxy file (proxy.js/.ts) in Next.js is a special server-side file (located in the project root or under src) that runs before any route handling or page rendering occurs. In fact, Proxy (and Middleware) executes before every incoming request — not just those for pages or APIs — including requests for assets like images, icons, or JavaScript files. Because of this, Next.js provides the matcher configuration, allowing you to specify which routes the Proxy should apply to and avoid intercepting unnecessary requests.
It allows you to inspect the incoming request, then respond, redirect, rewrite, or modify headers based on your application’s needs.
Relation to Middleware & Rewrites
- In previous versions,
middleware.js(App Router) was used for this pattern; Proxy replaces it. - While
rewrites()innext.config.jscan act like a proxy by mapping URL paths to different destinations, the Proxy feature goes further — it gives you direct access to the request object itself, including headers, cookies, and other request data.
When to use Proxy
Proxy works best in scenarios that require lightweight, real-time adjustments to incoming requests — such as performing quick redirects based on request details, dynamically rewriting routes for A/B testing or experimental features, or modifying request and response headers across specific routes or the entire application.
However, it’s not well-suited for tasks involving heavy data fetching or complex session management, as those are better handled by dedicated API routes or backend services.
Relation to Backend-for-Frontend (BFF) pattern
In the BFF pattern, the frontend has a dedicated backend layer (the “for the frontend”) that aggregates, transforms, or proxies requests to multiple microservices. Next.js supports this pattern via Route Handlers, Proxy and server actions.
Setting up Proxy: conventions & example
File convention
- Create a
proxy.ts(orproxy.js) file in the project root or insidesrc/alongside your top‐levelapp/orpages/folder. - Only one proxy file per project is supported—though you can modularize logic within it by importing helpers.
- Export a function named
proxy(or default) that receives aNextRequestand returns aNextResponse. - Optionally export a
configobject with amatcherproperty to specify which routes this proxy applies to.
Basic example
// proxy.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function proxy(request: NextRequest) {
// simple redirect
return NextResponse.redirect(new URL('/home', request.url));
}
export const config = {
matcher: '/about/:path*',
}
This intercepts /about/* and sends users to /home.
Proxying to different pathname
// proxy.ts
import { NextResponse } from 'next/server';
export function proxy(request: Request) {
if (request.nextUrl.pathname === '/v1/docs') {
request.nextUrl.pathname = '/v2/docs'
return NextResponse.redirect(request.nextUrl);
}
}
This way /v1/docs in your Next.js app becomes a proxy to your v2 version.
Important flags & matching
-
matchercan be a string, array of strings, or objects withsource,has,missing,regexpfor fine control. - You should exclude internal Next.js paths such as
/_next/, static assets etc, to avoid intercepting everything accidentally. - Be aware of runtime: The Proxy is executed by default in the Edge Runtime environment; performance matters.
Use cases & how it fits e-commerce / frontend/back-end scenarios
Use case 1: Authentication / session gating before forwarding
Before forwarding to upstream API, you can inspect cookies/headers in Proxy, validate session, add or strip auth headers, or reject unauthorized requests early. This centralises “frontend backend” logic.
For example:
if (!request.cookies.get('sessionToken')) {
return NextResponse.redirect('/login')
}
Use case 2: A/B testing, feature flags, routing to different backends
E-commerce often runs experiments: you might want to route certain requests to a “new checkout backend” or “legacy order API” based on a feature flag. Proxy allows dynamic routing:
if (featureFlag.isEnabled('newCheckout') && pathname.startsWith('/checkout')) {
return NextResponse.rewrite(new URL('/new-checkout' + rest, request.url))
}
This is exactly where Proxy shines, beyond simple rewrites. The docs mention this scenario.
Use case 3: Multi-zone / micro-frontend routing
If you break your site into zones (e.g., /shop, /blog, /dashboard) and each is a separate Next.js app or separate backend service, you can use Proxy to route to the correct service based on path or condition. The docs mention this under Multi-Zones: “Proxy can also be used when there is a need for a dynamic decision when routing.”
How this complements SSG/ISR/SSR strategies
In your e-commerce context (as your referenced articles explore SSG/ISR/SSR), Proxy supports architecture by giving you control over how client-requests hit your backend:
- If you statically generate product pages (SSG/ISR) but still need dynamic APIs behind the scenes (inventory, pricing), Proxy sits in front of those APIs.
- If you use SSR for checkout or account pages, you might fetch via your BFF rather than directly from client; Proxy gives you that layer.
- This allows you to decouple the frontend build (Next.js) from the backend services, while still providing unified domain, consistent cookies/sessions, and reduction of client-side complexity.
Summary
The Proxy file convention in Next.js is a modern, flexible tool for intercepting HTTP requests early in your application lifecycle. It’s especially valuable in setups where your frontend is part of a larger ecosystem (microservices, e-commerce, feature-flagged experiments) and you need a lightweight backend-for-frontend layer without building a full custom server.
For e-commerce platforms built with Next.js—where you may have static product pages, dynamic inventory/pricing APIs, customer sessions, checkout flows—the Proxy gives you an elegant place to manage domain-consolidation, routing, auth, A/B experimentation and API facade logic.
However, you should use it wisely: keep logic lean, use it for the right cases (redirects, rewrites, header manipulation, request forwarding) rather than heavy data aggregation. Combined with Next.js’s rendering strategies (SSG, ISR, SSR) and BFF pattern, Proxy becomes an important architectural building block.
Top comments (0)