Fix CORS errors when calling a Supabase Edge Function from the browser

Updated

Error messageAccess to fetch has been blocked by CORS policy: Response to preflight request doesn't pass access control check

Before the real request, the browser sends an OPTIONS preflight. The function must answer it with CORS headers and include the same headers on every response, errors included. If the function throws before returning, the browser also reports a CORS error, so check the function logs first.

First, rule out a crash

Open the function’s logs in the dashboard and trigger the request. An exception or a 401 there means the CORS message is a side effect: the error response went out without headers. Fix that first.

curl -i -X OPTIONS https://<project-ref>.supabase.co/functions/v1/my-function \
  -H "Origin: https://yoursite.com" \
  -H "Access-Control-Request-Method: POST"

A working function returns 200 with Access-Control-Allow-Origin in the headers.

Answer the preflight and add headers everywhere

With supabase-js 2.95 or newer, import the header list from the SDK so it stays in sync with what the client sends:

import { corsHeaders } from 'npm:@supabase/supabase-js@^2/cors'

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

  try {
    const { name } = await req.json()
    return Response.json({ message: `Hello ${name}` }, { headers: corsHeaders })
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error)
    return Response.json({ error: message }, { status: 400, headers: corsHeaders })
  }
})

On older versions, define the headers yourself, and include authorization, x-client-info, apikey, content-type in Access-Control-Allow-Headers.

Check that it worked

Call the function from the deployed site, not only from localhost. Then make it fail on purpose, for example with invalid input: the error must reach your code as a 400 with a message, not as a CORS error.

Sources