typescriptintermediate
Route Handler with CORS Support
Add CORS headers to Next.js route handlers for cross-origin API access.
typescriptPress ⌘/Ctrl + Shift + C to copy
// app/api/data/route.ts
import { NextRequest, NextResponse } from 'next/server';
const ALLOWED_ORIGINS = [
'https://app.example.com',
'https://staging.example.com',
];
function getCorsHeaders(origin: string | null) {
const headers: Record<string, string> = {
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400',
};
if (origin && ALLOWED_ORIGINS.includes(origin)) {
headers['Access-Control-Allow-Origin'] = origin;
headers['Access-Control-Allow-Credentials'] = 'true';
}
return headers;
}
// Handle preflight requests
export async function OPTIONS(request: NextRequest) {
const origin = request.headers.get('origin');
return new NextResponse(null, {
status: 204,
headers: getCorsHeaders(origin),
});
}
export async function GET(request: NextRequest) {
const origin = request.headers.get('origin');
const data = { items: [{ id: 1, name: 'Item 1' }] };
return NextResponse.json(data, {
headers: getCorsHeaders(origin),
});
}
export async function POST(request: NextRequest) {
const origin = request.headers.get('origin');
const body = await request.json();
// Process the request...
const result = { id: '123', ...body };
return NextResponse.json(result, {
status: 201,
headers: getCorsHeaders(origin),
});
}Use Cases
- external API consumers
- mobile app backends
- cross-origin access
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
Next.js Route Handlers (API Routes)
Build RESTful API endpoints using Next.js App Router route handlers with typed responses.
Best for: Building REST APIs within a Next.js application
#nextjs#api
typescriptintermediate
API Route Rate Limiting
Add rate limiting to Next.js API routes with sliding window, IP-based limits, and custom responses.
Best for: API abuse prevention
#nextjs#api
typescriptbeginner
Route Handler Response Helpers
Common response patterns for Next.js route handlers with proper status codes and headers.
Best for: API route handlers
#nextjs#api