typescriptintermediate

URL Rewrite Proxy Pattern

Use next.config.js rewrites to proxy API calls and avoid CORS issues in development and production.

typescript
// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  async rewrites() {
    return [
      {
        source: '/api/external/:path*',
        destination: 'https://api.external-service.com/:path*',
      },
      {
        source: '/blog/:slug',
        destination: '/posts/:slug',
      },
    ];
  },
  async redirects() {
    return [
      {
        source: '/old-page',
        destination: '/new-page',
        permanent: true,
      },
    ];
  },
  async headers() {
    return [
      {
        source: '/api/:path*',
        headers: [
          { key: 'Access-Control-Allow-Origin', value: '*' },
          { key: 'Cache-Control', value: 's-maxage=60, stale-while-revalidate' },
        ],
      },
    ];
  },
};

export default nextConfig;

Use Cases

  • API proxying
  • CORS avoidance
  • URL migration

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.