Next
Next

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

November 28, 2025

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 ?

Ready to leverage the power of conversational AI? Start your project with Zignuts expert AI developers.
bg-image
download-image
Company Deck
PDF, 3MB
© 2026 Zignuts Technolab. All Rights Reserved.
branch imagesbranch imagesbranch imagesbranch imagesbranch imagesbranch images