Validate CAPTCHA tokens on the server
mainTo prevent forgery, you must validate the Turnstile token on your server using Cloudflare's siteverify endpoint.
If using a standard HTML form, the token is available via the responseFieldName (default: cf-turnstile-response). If using client-side logic, capture the token via the on:callback event.
interface TokenValidateResponse {
'error-codes': string[];
success: boolean;
action: string;
cdata: string;
}
async function validateToken(token: string, secret: string) {
const response = await fetch(
'https://challenges.cloudflare.com/turnstile/v0/siteverify',
{
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({
response: token,
secret: secret,
}),
},
);
const data: TokenValidateResponse = await response.json();
return {
success: data.success,
error: data['error-codes']?.length ? data['error-codes'][0] : null,
};
}