To validate a Cloudflare Turnstile token within a Worker, you must extract the cf-turnstile-response token from the incoming POST request's formData. You then perform a POST request to the Cloudflare Turnstile verification endpoint (https://challenges.cloudflare.com/turnstile/v0/siteverify) using FormData.
Required fields for the verification request:
secret: Your Turnstile secret key.response: The token provided by the Turnstile widget (cf-turnstile-response).remoteip: The user's IP address (typically retrieved from the CF-Connecting-IP header).
If the response JSON contains success: false, the token is invalid.
async function handlePost(request) {
const body = await request.formData();
const token = body.get('cf-turnstile-response');
const ip = request.headers.get('CF-Connecting-IP');
let formData = new FormData();
formData.append('secret', 'YOUR_SECRET_KEY');
formData.append('response', token);
formData.append('remoteip', ip);
const result = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
body: formData,
method: 'POST',
});
const outcome = await result.json();
if (!outcome.success) {
return new Response('The provided Turnstile token was not valid! \n' + JSON.stringify(outcome));
}
return new Response('Turnstile token successfuly validated. \n' + JSON.stringify(outcome));
}