Set CORS Headers in Next 13 Response

Here's how to set CORS headers in a Next.js 13 Response

Native Response

Next 13 changes a lot of things. One thing is that it now uses the native Response object for return values.

Because it's native, you don't need to import it in Node.js.

Liberal Headers for JSON

The example below is shows very liberal CORS headers, ensures that the response is json (instead of plain text by default), and disables cache:

return new Response(JSON.stringify({ take: 'this' }), {
  status: 200,
  headers: { 
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET,PUT,POST,PATCH,DELETE,OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type",
    "Content-Type": "application/json",
    "Cache-Control": "no-cache",
  }
});