Home

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.

We recommend adding a cors.ts file within a _shared folder which makes it easy to reuse the CORS headers across functions:

cors.ts

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

You can then import and use the CORS headers within your functions:

index.ts

_28
import { serve } from 'https://deno.land/std@0.177.0/http/server.ts'
_28
import { corsHeaders } from '../_shared/cors.ts'
_28
_28
console.log(`Function "browser-with-cors" up and running!`)
_28
_28
serve(async (req) => {
_28
// This is needed if you're planning to invoke your function from a browser.
_28
if (req.method === 'OPTIONS') {
_28
return new Response('ok', { headers: corsHeaders })
_28
}
_28
_28
try {
_28
const { name } = await req.json()
_28
const data = {
_28
message: `Hello ${name}!`,
_28
}
_28
_28
return new Response(JSON.stringify(data), {
_28
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
_28
status: 200,
_28
})
_28
} catch (error) {
_28
return new Response(JSON.stringify({ error: error.message }), {
_28
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
_28
status: 400,
_28
})
_28
}
_28
})