Next

How can we set up Proxy middleware using proxy.ts in Next.js 16 for API routes?

November 28, 2025

download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

Next.js 16 introduces proxy.ts (replacing middleware) at project root to proxy API routes to external services, handling auth, CORS, and routing cleanly without third-party libs.

Create proxy.ts in your project root (or src/) and export a proxy function that intercepts API requests. Use NextResponse to rewrite/redirect to your backend, add auth headers, or proxy full paths. Add config.matcher: '/api/:path*' to target only API routes. This runs before API handlers, perfect for BFF patterns and hiding backend URLs.

Code

// proxy.ts (project root)
import { NextRequest, NextResponse } from 'next/server'

export function proxy(request: NextRequest) {
  const url = request.nextUrl.clone()
  
  if (url.pathname.startsWith('/api')) {
    // Proxy /api/* to backend
    url.pathname = url.pathname.replace('/api', '/v1')
    url.host = 'https://your-backend.com'
    
    return NextResponse.rewrite(url)
  }
  
  return NextResponse.next()
}

export const config = {
  matcher: '/api/:path*'
}
Hire Now!

Need Help with Next Development ?

Work with our skilled next developers to accelerate your project and boost its performance.
**Hire now**Hire Now**Hire Now**Hire now**Hire now