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:
1import { withSupabase } from 'npm:@supabase/server@^1'23export 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.
For @supabase/supabase-js v2.95.0 and later: Import CORS headers directly from the SDK to ensure they stay synchronized with any new headers added to the client libraries.
Import corsHeaders from @supabase/supabase-js/cors to automatically get all required headers:
1import { corsHeaders } from '@supabase/supabase-js/cors'23console.log(`Function "browser-with-cors" up and running!`)45export default {6 fetch: async (req) => {7 // Handle the CORS preflight request.8 if (req.method === 'OPTIONS') {9 return new Response('ok', { headers: corsHeaders })10 }1112 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:
1export 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:
1import { corsHeaders } from '../_shared/cors.ts'23// ... rest of your function code