Supabase Edge Function CORS Error: Fix the Preflight

Calling a Supabase Edge Function from the browser fails with a CORS preflight error? Handle OPTIONS first, add headers to every response, and find the real error hiding behind it.

A CORS error when you call a Supabase Edge Function from the browser almost always means the function did not answer the browser's OPTIONS preflight request with the right headers. Handle OPTIONS at the very top of the function, return the CORS headers on every response including errors, and allow the headers the Supabase client sends. If the function crashes, the browser still shows a CORS error that hides the real failure, so read the function logs too.

Edge Functions do not add CORS headers for you. Supabase's troubleshooting guide and its CORS page both say you must handle preflight requests when invoking from a browser. Here is the fix in order.

Step 1: Confirm It Is a Preflight Failure

Open dev tools, Network tab. Before your POST, the browser sends an OPTIONS request to the same URL. This is the preflight. Look at it:

  • Status 200 or 204 with an Access-Control-Allow-Origin header: preflight passed. The problem is the real request (Step 4).
  • Status 4xx or 5xx, or no Access-Control-Allow-* headers: preflight failed. Continue with Step 2.

The console message usually reads "Response to preflight request doesn't pass access control check". That text describes the browser's view. It does not tell you why the function failed.

Step 2: Answer OPTIONS Before Anything Else

Create a shared headers file and return early for OPTIONS:

// supabase/functions/_shared/cors.ts
export const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers":
    "authorization, x-client-info, apikey, content-type",
};
// supabase/functions/my-function/index.ts
import { corsHeaders } from "../_shared/cors.ts";

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders });
  }

  const { name } = await req.json();
  return new Response(JSON.stringify({ message: `Hello ${name}` }), {
    headers: { ...corsHeaders, "Content-Type": "application/json" },
  });
});

The order matters. A Japanese write-up found that the preflight has no body, so calling await req.json() before the OPTIONS check throws, and the preflight fails with a 500. Put the check first.

Step 3: Allow the Headers the Client Sends

supabase.functions.invoke() adds the apikey and authorization headers automatically, and the client library also sends x-client-info. The browser lists every non-simple header it plans to send in Access-Control-Request-Headers. If your Access-Control-Allow-Headers value is missing one, the preflight fails.

If you add your own header, for example x-request-id, add it to the list:

"Access-Control-Allow-Headers":
  "authorization, x-client-info, apikey, content-type, x-request-id",

Look at the failing preflight in the Network tab. Compare Access-Control-Request-Headers in the request with Access-Control-Allow-Headers in the response. They must line up.

Step 4: Add Headers to Every Response, Including Errors

The preflight can pass and the real call can still show a CORS error. This happens when your function returns an error response without the CORS headers. The browser then blocks the response and the console says CORS, not "500" or "401".

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders });
  }

  try {
    const body = await req.json();
    // ... your logic
    return Response.json({ ok: true }, { headers: corsHeaders });
  } catch (err) {
    console.error("my-function failed", err);
    return Response.json(
      { error: "Something went wrong" },
      { status: 500, headers: corsHeaders },
    );
  }
});

Now a failure shows as a readable 500 with a JSON body, not a vague CORS message. The same rule applies to 400 validation errors and 401 auth errors.

Step 5: Read the Function Logs for the Real Error

When a function throws before it returns, for example a missing secret, a bad import or a Deno permission error, the platform answers with its own error response that has no CORS headers. The browser reports CORS and hides the cause. In the Supabase dashboard, open Edge Functions, pick the function, and check Logs. Call the function with curl to see the real status and body without a browser in the way:

curl -i -X POST "https://<project-ref>.supabase.co/functions/v1/my-function" \
  -H "Authorization: Bearer <anon-key>" \
  -H "Content-Type: application/json" \
  -d '{"name":"test"}'

If curl returns 401, check JWT verification. If it returns 500, the bug is in your function. If it works, the issue is only in the CORS headers.

Step 6: Restrict the Origin for Production

"*" is fine for a public function. For one that uses cookies or sensitive data, return the origin only if it is on an allow list:

const allowed = ["https://app.example.com", "http://localhost:5173"];

function corsFor(req: Request) {
  const origin = req.headers.get("origin") ?? "";
  return {
    "Access-Control-Allow-Origin": allowed.includes(origin) ? origin : allowed[0],
    "Access-Control-Allow-Headers":
      "authorization, x-client-info, apikey, content-type",
    "Vary": "Origin",
  };
}

Do not combine Access-Control-Allow-Origin: * with credentials. Browsers reject it. The same wildcard-with-credentials trap exists in other stacks, as in CORS Errors in Production: Next.js Fix Guide.

Step 7: Watch the Function After You Ship

A CORS bug in an Edge Function breaks one feature for every user while your server logs look clean, because the failing request never reaches your code. If your app was built with a tool like Lovable and talks to Supabase, the same pattern applies, and a related login problem is covered in Lovable Supabase Login Fails After Publish. After each deploy, call the function from the real production domain and check the Network tab.

How Relia Helps

When a browser blocks a response, your function logs may show nothing, while users see a broken button. Relia watches the users, APIs and servers of a live product and joins related signals, such as a deploy and a spike in failing requests from the browser, into one incident explained in plain words. It shows who was affected and, after a fix, checks whether it worked. Supabase, Firebase and edge functions are supported, and npx relia-sdk@latest init sets up Node.js and browser apps. There is a Free plan, and a live demo at app.tryrelia.com/demo.

FAQ

Why does my Supabase Edge Function work in curl but fail in the browser?

Browsers send a preflight OPTIONS request and enforce CORS. curl does not. The function must answer OPTIONS with the right headers.

Do I need CORS headers on error responses?

Yes. Without them the browser hides the status and shows a CORS error instead of the real failure.

Can I use Access-Control-Allow-Origin: * in production? For a public function, yes. For anything that uses credentials, return a specific origin from an allow list.

Why is the preflight returning 500?

Usually your code runs before the OPTIONS check and throws, for example await req.json() on an empty body, or a missing secret.

Does supabase.functions.invoke handle CORS for me?

No. It sends the required headers, but the function must still allow them. See the Supabase CORS guide.

All guides