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.

Automatic CORS handling#

The withSupabase wrapper handles CORS and preflight (OPTIONS) requests for you, so you don't add headers manually:

1
import { withSupabase } from 'npm:@supabase/server@^1'
2
3
export default {
4
fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {
5
const { name } = await req.json()
6
return Response.json({ message: `Hello ${name}!` })
7
}),
8
}

Manual CORS handling#

If your function doesn't use withSupabase, add the headers yourself. 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
export default {
6
fetch: async (req) => {
7
// Handle the CORS preflight request.
8
if (req.method === 'OPTIONS') {
9
return new Response('ok', { headers: corsHeaders })
10
}
11
12
try {
13
const { name } = await req.json()
14
return Response.json({ message: `Hello ${name}!` }, { headers: corsHeaders })
15
} catch (error) {
16
return Response.json({ error: error.message }, { status: 400, headers: corsHeaders })
17
}
18
},
19
}

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