Capítulo 372 de 456

Proxy

Core Idea

proxy.js|ts (the renamed middleware.js) runs code on the server before a request completes, letting you rewrite, redirect, or modify requests/responses ahead of routing, e.g. for auth or logging.

Key Concepts

  • proxy function: default or named export proxy(request, event); only one per file, runs on every route unless scoped by matcher.
  • matcher: exported config.matcher (string, array, or array of objects with source/locale/has/missing) restricting which paths trigger the proxy; must be statically analyzable (no dynamic variables).
  • request (NextRequest): first param, the incoming HTTP request.
  • event (NextFetchEvent): second param, exposes waitUntil(promise) to extend proxy lifetime for background work.
  • NextProxy type: shorthand type inferring both request and event param types.
  • Execution order: next.config.js headers → next.config.js redirects → Proxy → beforeFiles rewrites → filesystem routes → afterFiles rewrites → dynamic routes → fallback rewrites.
  • Runtime: defaults to Node.js; the runtime file-convention config option cannot be used in Proxy files (throws an error).
  • skipTrailingSlashRedirect / skipProxyUrlNormalize: next.config.js flags for advanced trailing-slash and URL-normalization control inside proxy logic.
  • unstable_doesProxyMatch: from next/experimental/testing/server (Next.js 15.1+), unit-tests whether proxy matches a given URL/headers/cookies without running it.

Code Examples

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function proxy(request: NextRequest) {
  return NextResponse.redirect(new URL('/home', request.url))
}

export const config = {
  matcher: '/about/:path*',
}
  • O que demonstra: minimal redirect proxy scoped by matcher.
export const config = {
  matcher: [
    '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
  ],
}
  • O que demonstra: negative-lookahead matcher excluding static/API/metadata paths.
export function proxy(req: NextRequest, event: NextFetchEvent) {
  event.waitUntil(
    fetch('https://my-analytics-platform.com', {
      method: 'POST',
      body: JSON.stringify({ pathname: req.nextUrl.pathname }),
    })
  )
  return NextResponse.next()
}
  • O que demonstra: waitUntil keeping proxy alive for background logging after the response is sent.

Reference Tables

Matcher object keyPurpose
sourcepath/pattern to match (must start with /)
localefalse ignores locale-based routing
hasrun only if header/query/cookie is present
missingrun only if header/query/cookie is absent
DeploymentSupported
Node.js serverYes
Docker containerYes
Static exportNo
AdaptersPlatform-specific

Anti-patterns

  • No matcher: proxy runs on every request including static files and images, potentially blocking CSS/JS/image loads with auth logic.
  • Forwarding all incoming headers via NextResponse.next({ headers }): exposes them to the client and can override framework-critical headers like Content-Type; forward request headers only via NextResponse.next({ request: { headers } }).
  • Relying solely on Proxy for auth on Server Functions: a matcher change can silently exclude a route; always re-check auth inside Server Actions too.
  • Excluding _next/data in matcher expecting it to skip proxy: Next.js still invokes proxy for _next/data routes intentionally, to avoid protecting a page but forgetting its data route.

Key Takeaways

  1. Proxy replaces the deprecated middleware convention (renamed in v16.0.0); a codemod (npx @next/codemod@canary middleware-to-proxy .) automates migration.
  2. Use precise matcher patterns, not a global catch-all, to avoid unintended blocking or overhead.
  3. NextResponse.rewrite() auto-propagates RSC headers; custom fetch()-based rewrites need skipProxyUrlNormalize and manual header forwarding.
  4. Proxy defaults to Node.js runtime and cannot override runtime config.
  5. Test proxy logic with unstable_doesProxyMatch, isRewrite, and getRewrittenUrl from next/experimental/testing/server.

Connects To

  • NextRequest: the request param's full API (cookies, nextUrl).
  • NextResponse: redirect, rewrite, next, json, cookie methods used to produce proxy responses.
  • Link: prefetching through proxy rewrites requires coordinating as/href.