
Proxy an external API through your domain using vercel.ts. Requests to /api/external/:path* are rewritten to your backend, cached at the CDN, and tagged for targeted purging.
Proxying puts the Vercel CDN in front of your backend, improving performance through Vercel's global edge network and reducing cost with built-in caching. It also adds a layer of security with the Vercel Firewall.
https://proxy-requests-to-external-origins.vercel.app/
Visit /blog to see blog posts fetched from an external API through the CDN proxy.
Deploy the template on Vercel using this link.
To proxy your own API instead of the demo, set the EXTERNAL_API_URL environment variable in your project settings or update the default value in vercel.ts, then redeploy. By default, the template uses jsonplaceholder.typicode.com as the external API.
pnpm create next-app --example https://github.com/vercel/examples/tree/main/cdn/api-proxy-rewritecd api-proxy-rewritepnpm installpnpm devThe rewrite and caching configuration lives in vercel.ts:
import { routes, type VercelConfig } from '@vercel/config/v1'
const EXTERNAL_API_URL = process.env.EXTERNAL_API_URL || 'https://jsonplaceholder.typicode.com'
export const config: VercelConfig = { framework: 'nextjs', outputDirectory: '.next', rewrites: [ routes.rewrite('/api/external/:path*', `${EXTERNAL_API_URL}/:path*`), ], headers: [ routes.header('/api/external/:path*', [ { key: 'CDN-Cache-Control', value: 'public, max-age=60, stale-while-revalidate=3600' }, { key: 'Vercel-Cache-Tag', value: 'api' }, ]), ],}/api/external/postsvercel.ts matches /api/external/:path* and proxies the request to your configured backendCDN-Cache-Control header caches responses at the edge for 1 minute, with a 1-hour stale-while-revalidate windowVercel-Cache-Tag header tags responses with api for targeted cache purgingCDN-Cache-Control controls caching at the Vercel CDN only. Unlike Cache-Control, which affects both the browser and CDN, CDN-Cache-Control is stripped before reaching the browser.
max-age=60: The CDN serves cached responses for 1 minute without hitting the external API.stale-while-revalidate=3600: After the 1-minute window, the CDN serves stale content immediately while fetching a fresh copy in the background.Vercel-Cache-Tag: api labels cached responses with a tag. You can purge all responses tagged api without flushing the entire project cache:
api, and click Purgevercel cache invalidate --tag apiIf you prefer to configure routing without code or redeployment, you can use project level routing rules through the Vercel Dashboard, CLI, API, or SDK. See the Add API External Rewrite Routing Rule template for a no-code approach.