Skip to content
Edge Functions

支持从浏览器调用的跨域资源共享(CORS)

要从浏览器调用边缘函数,你需要处理 CORS 预检 请求。

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

自动处理 CORS #

🌐 Automatic CORS handling

withSupabase 封装器会帮你处理 CORS 和预检 (OPTIONS) 请求,所以你不用手动添加头信息:

🌐 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
}

手动处理 CORS #

🌐 Manual CORS handling

如果你的函数没有使用 withSupabase,就自己添加头文件。看看 GitHub 上的例子

🌐 If your function doesn't use withSupabase, add the headers yourself. See the example on GitHub.

npm:@supabase/supabase-js@^2/cors 导入 corsHeaders,就能自动获取所有需要的头文件:

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

1
import { corsHeaders } from 'npm:@supabase/supabase-js@^2/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 Response.json({ ok: true }, { 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
}

这种方法可以确保当向 Supabase SDK 添加新头时,你的 Edge 函数会自动包含它们,从而防止 CORS 错误。

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

在 2.95.0 之前的版本 #

🌐 For versions before 2.95.0

如果你在 v2.95.0 之前使用 @supabase/supabase-js,你需要硬编码 CORS 头。在 _shared 文件夹 内添加一个 cors.ts 文件:

🌐 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