Demo, all content is generated
Question

Supabase edge function works in curl, browser says preflight doesn't have HTTP ok status

Solved · 413 views · asked by freya_c · edited

Lovable made me an edge function send-invite. Testing it with curl from the docs page works. From my app:

Access to fetch at 'https://xyz.supabase.co/functions/v1/send-invite' from origin 'https://myapp.lovable.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
What I’ve tried

Asked Lovable to fix CORS three times. It added corsHeaders to the response but the error is the same.

Comment
Every single Lovable edge function I've seen has this bug at least once. mo_saleh · edited

2 answers

Marked as helpful by the asker
jb_supa · edited

The browser first sends an OPTIONS request (the preflight) before the real POST. Your function probably tries to parse a JSON body or check auth on that OPTIONS request, crashes, returns 500 → 'not HTTP ok'.

Handle it at the very top of the function, before anything else:

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

Deno.serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }
  // ... your code, and add corsHeaders to every response, errors too
})

Curl doesn't do preflights, that's why it worked there.

Comment
The OPTIONS check was below the await req.json(). Moved it up, works. freya_c · edited
Also add corsHeaders on your error responses, otherwise real errors show up as CORS errors and confuse you later. jb_supa · edited
pixelpaulo · edited

Tip: open Edge Functions → your function → Logs in the Supabase dashboard. You'll see the OPTIONS request and the stack trace of the crash. Much faster than guessing from the browser error.

Comment