~2 min read • Updated Dec 12, 2025
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?
| Action | Code |
|---|---|
| Redirect | NextResponse.redirect() |
| Rewrite | NextResponse.rewrite() |
| Set Headers | response.headers.set() |
| Set Cookies | response.cookies.set() |
| Block Access | return new Response('401') |
| Log Analytics | event.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
| Do | Don’t |
|---|---|
| Use precise matchers | Run on every route |
| Return early | Run heavy logic |
| Use waitUntil for logs | Block response |
| Set cookies/headers | Depend on global state |
| Keep it stateless | Share app modules |
9. Migration from middleware.ts
npx @next/codemod@canary middleware-to-proxy .10. When to Use proxy.ts?
| Use Case | Use proxy? |
|---|---|
| Auth redirect | ✅ |
| A/B testing | ✅ |
| Feature flags | ✅ |
| Logging | ✅ (with waitUntil) |
| Rate limiting | ✅ (at edge) |
| SEO redirects | ✅ |
| Page rendering | ❌ use Server Components |
Written & researched by Dr. Shahin Siami