Cloudflare Turnstile is a privacy-friendly CAPTCHA replacement that verifies a visitor is human without forcing them to solve puzzles. This article explains how to integrate Turnstile into a website, validate the token on your server, and fix common integration problems. You’ll get step-by-step instructions for the widget, the siteverify API, and troubleshooting tips for the most frequent issues.
What Is Cloudflare Turnstile?
Turnstile is Cloudflare’s answer to traditional CAPTCHAs. Instead of asking users to identify traffic lights or type distorted text, it runs a non-interactive challenge in the background. It uses browser signals, behavior analysis, and other heuristics to decide if a visitor is human. The user sees a small widget (often just a checkbox or nothing at all) and is let through without any effort. This improves user experience and reduces friction, especially on mobile devices.
Turnstile is free for unlimited use, which makes it an attractive alternative to Google’s reCAPTCHA, which has usage limits and often shows visual puzzles. It’s also designed to be more privacy-respecting—it doesn’t track users across the web.
How Turnstile Works
Turnstile works in two parts: the client-side widget and a server-side verification call.
- Client-side: You embed a JavaScript snippet that renders the Turnstile widget on your page. The widget communicates with Cloudflare’s servers and generates a token (a long string) once it determines the visitor is human.
- Server-side: Your backend sends that token to Cloudflare’s
siteverifyendpoint along with your secret key. Cloudflare responds with a JSON object indicating whether the token is valid.
The token is time-limited (usually 5 minutes) and can only be used once. This prevents replay attacks. The whole process is designed to be invisible to the user in most cases.
How to Integrate Turnstile
Here’s the typical integration process:
- Get keys: Sign up for a Cloudflare account, go to the Turnstile dashboard, and create a new site. You’ll get a Site Key (public) and a Secret Key (private).
- Add the script: Place the following script tag in your HTML, ideally in the
<head>or before the widget.<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script> - Add the widget: Insert a div with the class
cf-turnstilewhere you want the widget to appear, and set thedata-sitekeyattribute to your site key.<div class="cf-turnstile" data-sitekey="YOUR_SITE_KEY"></div> - Handle the token: When the form is submitted, the widget automatically populates a hidden input field named
cf-turnstile-responsewith the token. You send this token along with the rest of the form data to your server.
That’s the basic client-side setup. You can also customize the widget’s theme, size, and language using data attributes or the JavaScript API.
How to Validate the Token Server-Side
Client-side integration alone is not enough—you must verify the token on your server to actually block bots. Here’s the process:
- Receive the token: Your server receives the
cf-turnstile-responsefield from the form submission. - Call the siteverify API: Make a POST request to
https://challenges.cloudflare.com/turnstile/v0/siteverifywith the following parameters:secret= your secret key,response= the token, and optionallyremoteip= the user’s IP address. - Check the response: Cloudflare returns a JSON object like:
{ "success": true, "challenge_ts": "2025-01-01T00:00:00Z", "hostname": "example.com" }
Ifsuccessistrue, the token is valid. Iffalse, anerror-codesarray explains why.
Here’s a simple PHP example:
$secret = 'YOUR_SECRET_KEY';
$token = $_POST['cf-turnstile-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$data = [
'secret' => $secret,
'response' => $token,
'remoteip' => $ip
];
$ch = curl_init('https://challenges.cloudflare.com/turnstile/v0/siteverify');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
if ($response['success']) {
// Token is valid, process the form
} else {
// Handle error
}
Always validate on the server—never trust the client alone.
Common Troubleshooting Issues
Here are the most frequent problems and how to fix them:
- Widget not rendering: Check that the script is loaded and the div has the correct class and site key. Also ensure the site key is active in the Turnstile dashboard.
- Token missing on submit: If the form uses AJAX, you may need to manually include the token in the request. Use the JavaScript API to get the token:
turnstile.getResponse(). - Token invalid on server: This often means the token expired or was already used. Ensure your form is submitted within 5 minutes and that you don’t validate the same token twice.
- Hostname mismatch: If you set a hostname restriction in your Turnstile settings, the token will be invalid for other domains. Update the settings or remove the restriction for testing.
- Secret key wrong: Double-check that you’re using the secret key, not the site key, in the siteverify call.
- HTTPS required: Turnstile requires a secure (HTTPS) context. It won’t work on plain HTTP or in local files without a local server.
Turnstile vs. reCAPTCHA
Many developers compare Turnstile to Google’s reCAPTCHA. Here’s a quick overview:
- User experience: Turnstile is generally less intrusive, with no visual puzzles in most cases. reCAPTCHA v3 also runs in the background, but v2 often shows image challenges.
- Privacy: Turnstile doesn’t use cookies for tracking and is designed to be privacy-friendly. reCAPTCHA is part of Google’s tracking ecosystem.
- Pricing: Both are free, but Turnstile has no usage limits, while reCAPTCHA has a monthly free tier (1 million assessments) and charges beyond that.
- Ease of integration: Both are similar in complexity, but Turnstile’s dashboard is simpler and less cluttered.
If you already use Google services heavily, reCAPTCHA might integrate better, but Turnstile is a strong choice for a more user-friendly and private alternative.
Security Considerations
Turnstile is not a silver bullet. It can be bypassed by sophisticated bots that emulate browser behavior. To improve security:
- Always validate on the server, never just rely on the client.
- Use the
remoteipparameter to tie the token to the user’s IP. - Consider adding rate limiting on your endpoints to mitigate brute-force attacks.
- Use Turnstile in combination with other security measures like input validation and CSRF tokens.
Also, be careful not to block legitimate users. If you set the security level too high, some users may see a challenge. Test with different settings to find the right balance.
Frequently Asked Questions
How do I get a Turnstile site key and secret key?
You need a Cloudflare account. Go to the Turnstile dashboard, click “Add Site”, enter your domain, and you’ll receive the two keys. The site key is public and goes in your HTML; the secret key is private and stays on your server.
Can I use Turnstile on localhost for development?
Yes, but you need to add localhost as a hostname in your Turnstile site settings. Also, you must access your site via http://localhost (not file://). The widget will work in a local development environment.
Why does the token expire so quickly?
The token is valid for 5 minutes by design. This prevents replay attacks. If your form takes longer than 5 minutes to fill, you can refresh the token using the JavaScript API (turnstile.reset()) or ask the user to reload the page.
Can I use Turnstile with a single-page application (SPA)?
Yes, but you need to manage the token manually. Use the JavaScript API to render the widget and get the token when needed. You can also reset it after submission. The official documentation covers SPA integration.
What are the error codes returned by siteverify?
Common error codes include missing-input-secret (secret key not provided), invalid-input-secret (secret key is invalid), missing-input-response (token not provided), invalid-input-response (token is invalid or expired), and timeout-or-duplicate (token was already used). Check the Cloudflare docs for the full list.
Does Turnstile work with all browsers?
Turnstile supports all modern browsers, including Chrome, Firefox, Safari, and Edge. It also works on mobile devices. For older browsers, it may fall back to a more interactive challenge, but it generally degrades gracefully.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Poco C51 Airtel Prepaid Locked Variant India?
- Jenkins vs GitHub Actions: Which CI/CD Fits Your Team?
- Turn Off Backup Encryption in iTunes?
- Campus Tech Innovation Hubs: What They Are
- Shared VPS Hosting: Is It Better?
- Disk Defrag Pro: What It Does and Whether You Need It