typescriptintermediate
URL Rewrite Proxy Pattern
Use next.config.js rewrites to proxy API calls and avoid CORS issues in development and production.
typescriptPress ⌘/Ctrl + Shift + C to copy
// 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.
typescriptintermediate
Route Handler with CORS Support
Add CORS headers to Next.js route handlers for cross-origin API access.
Best for: external API consumers
#nextjs#cors
typescriptintermediate
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Best for: CRUD API endpoints
#api#route-handler
typescriptintermediate
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Best for: Dashboard access control
#middleware#authentication
typescriptintermediate
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Best for: Blog post creation
#server-actions#forms