Edge Functions

CORS (Cross-Origin Resource Sharing) support for Invoking from the browser


To invoke edge functions from the browser, you need to handle CORS Preflight requests.

See the example on GitHub.

Import corsHeaders from @supabase/supabase-js/cors to automatically get all required headers:

1
import { corsHeaders } from '@supabase/supabase-js/cors'
2
3
console.log(`Function "browser-with-cors" up and running!`)
4
5
Deno.serve(async (req) => {
6
// This is needed if you're planning to invoke your function from a browser.
7
if (req.method === 'OPTIONS') {
8
return new Response('ok', { headers: corsHeaders })
9
}
10
11
try {
12
const { name } = await req.json()
13
const data = {
14
message: `Hello ${name}!`,
15
}
16
17
return new Response(JSON.stringify(data), {
18
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
19
status: 200,
20
})
21
} catch (error) {
22
return new Response(JSON.stringify({ error: error.message }), {
23
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
24
status: 400,
25
})
26
}
27
})

This approach ensures that when new headers are added to the Supabase SDK, your Edge Functions automatically include them, preventing CORS errors.

For versions before 2.95.0

If you're using @supabase/supabase-js before v2.95.0, you'll need to hardcode the CORS headers. Add a cors.ts file within a _shared folder:

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

Then import it in your function:

1
import { corsHeaders } from '../_shared/cors.ts'
2
3
// ... rest of your function code