Skip to content
Edge Functions

支持 Cloudflare Turnstile 的 CAPTCHA

Cloudflare Turnstile 是一个友好、免费的 CAPTCHA 替代品,它可以与 Supabase Edge Functions 无缝协作,保护你的表单。在 GitHub 上查看

设置 #

🌐 Setup

代码 #

🌐 Code

在你的项目中创建一个新函数:

🌐 Create a new function in your project:

1
supabase functions new cloudflare-turnstile

然后把代码加到 index.ts 文件里:

🌐 And add the code to the index.ts file:

1
import { withSupabase } from 'npm:@supabase/server@^1'
2
3
console.log('Hello from Cloudflare Trunstile!')
4
5
function ips(req: Request) {
6
return req.headers.get('x-forwarded-for')?.split(/\s*,\s*/)
7
}
8
9
// `withSupabase` handles CORS and preflight requests for you.
10
export default {
11
fetch: withSupabase({ auth: 'none' }, async (req) => {
12
const { token } = await req.json()
13
const clientIps = ips(req) || ['']
14
const ip = clientIps[0]
15
16
// Validate the token by calling the
17
// "/siteverify" API endpoint.
18
let formData = new FormData()
19
formData.append('secret', Deno.env.get('CLOUDFLARE_SECRET_KEY') ?? '')
20
formData.append('response', token)
21
formData.append('remoteip', ip)
22
23
const url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
24
const result = await fetch(url, {
25
body: formData,
26
method: 'POST',
27
})
28
29
const outcome = await result.json()
30
console.log(outcome)
31
if (outcome.success) {
32
return Response.json({ success: true })
33
}
34
return Response.json({ success: false })
35
}),
36
}

部署服务器端验证的 Edge Functions #

🌐 Deploy the server-side validation Edge Functions

1
supabase functions deploy cloudflare-turnstile --no-verify-jwt
2
supabase secrets set CLOUDFLARE_SECRET_KEY=your_secret_key

从你的网站调用这个函数 #

🌐 Invoke the function from your site

1
const { data, error } = await supabase.functions.invoke('cloudflare-turnstile', {
2
body: { token },
3
})