typescriptintermediate

Route Handler with CORS Support

Add CORS headers to Next.js route handlers for cross-origin API access.

typescript
// 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.