Next.js › Route Handlers (API Route.js)

How do you set custom response headers, such as CORS headers, in a route handler to allow requests from a different domain?

Advanced

Answer

You construct your response using the Response constructor, passing a headers object that includes the necessary CORS headers like Access-Control-Allow-Origin, allowing browsers on other domains to successfully make requests to your API endpoint instead of being blocked by the browser's security policies.
export async function GET() {
  return new Response(JSON.stringify({ data: 'hello' }), {
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': 'https://partner-site.com'
    }
  });
}
Real-world example A company exposes a public API that a trusted partner website needs to call directly from the browser, configuring the correct CORS headers so the partner's requests are not blocked.

Common follow-ups: What is the difference between allowing all origins and allowing a specific origin?;How do you handle preflight OPTIONS requests for CORS?