Q47: How do you configure Cross-Origin Resource Sharing (CORS) in Route Handlers?

To allow external domains to make API requests to your Route Handlers (route.js), set standard CORS headers (Access-Control-Allow-Origin, Access-Control-Allow-Methods) on returned NextResponse objects and export an OPTIONS method handler.

CORS Route Handler Implementation
// app/api/external/route.js
import { NextResponse } from 'next/server';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
};

export async function OPTIONS() {
  return NextResponse.json({}, { headers: corsHeaders });
}

export async function GET() {
  return NextResponse.json({ data: 'Public API' }, { headers: corsHeaders });
}
💡 OPTIONS handles browser preflight checks; GET returns data along with explicit CORS origin headers.
Key Takeaways
  • Requires exporting an OPTIONS preflight handler function.
  • Sets Access-Control-Allow-* headers on returned responses.
Knowledge Check

Which HTTP method function must be exported from route.js to handle browser preflight CORS checks?