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.

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

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