proxy.ts in Next.js — The Silent Guardian at the Edge

The proxy.ts file in Next.js replaces middleware.ts and acts as an edge-level gatekeeper before your app renders. It can rewrite or redirect routes, set headers and cookies, block access, and run background tasks. This article explains how to use proxy.ts, define precise matchers, and implement real-world scenarios like authentication, A/B testing, CORS, and geo-based redirects.

matcherNextResponseEdge Middleware

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۲۱ آذر ۱۴۰۴

1. Why proxy.ts?


Next.js renamed middleware.ts to proxy.ts to avoid confusion with Express and clarify its role as a network-level proxy that runs at the edge before your app loads.


2. What Can proxy.ts Do?


ActionCode
RedirectNextResponse.redirect()
RewriteNextResponse.rewrite()
Set Headersresponse.headers.set()
Set Cookiesresponse.cookies.set()
Block Accessreturn new Response('401')
Log Analyticsevent.waitUntil(fetch(...))

3. Basic Setup


// proxy.ts
import { NextResponse, NextRequest } from 'next/server'

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

export const config = {
  matcher: '/about/:path*',
}

4. matcher — Be Precise


  • Single path: '/about'
  • Multiple: ['/dashboard', '/profile']
  • Wildcard: '/blog/:path*'
  • Regex: '/(?!api|_next/static).*'

5. Real-World Examples


5.1 Auth Guard

if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
  return NextResponse.redirect(new URL('/login', request.url))
}

5.2 A/B Testing

url.pathname = random < 0.5 ? '/experiments/a' : '/experiments/b'

5.3 Geo Redirect

if (country === 'IR') {
  return NextResponse.rewrite(new URL('/fa', request.url))
}

5.4 CORS for APIs

response.headers.set('Access-Control-Allow-Origin', origin)

5.5 Security Headers

response.headers.set('X-Frame-Options', 'DENY')

6. Background Tasks with waitUntil


event.waitUntil(fetch('https://analytics.com/log', { method: 'POST', body: ... }))

7. Testing proxy.ts


unstable_doesProxyMatch({ config, url: '/dashboard' })

8. Best Practices


DoDon’t
Use precise matchersRun on every route
Return earlyRun heavy logic
Use waitUntil for logsBlock response
Set cookies/headersDepend on global state
Keep it statelessShare app modules

9. Migration from middleware.ts


npx @next/codemod@canary middleware-to-proxy .

10. When to Use proxy.ts?


Use CaseUse proxy?
Auth redirect
A/B testing
Feature flags
Logging✅ (with waitUntil)
Rate limiting✅ (at edge)
SEO redirects
Page rendering❌ use Server Components

نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

ادامه

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

ادامه

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

ادامه

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

ادامه

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

ادامه

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

ادامه