Free Google reCAPTCHA Alternative: Cloudflare Turnstile

Free Google reCAPTCHA Alternative: Cloudflare Turnstile

If you are operating a website, spam can be a big problem for you. Bots and spammers can exploit your website by sending unwanted messages, registering fake user accounts, or injecting malicious content. Luckily, there are many ways to protect your website from these threats, and one of the most effective ways is using a CAPTCHA.

In this article, we will discuss how to add Turnstile Cloudflare CAPTCHA to your website to protect it from spam and other threats.

What is Turnstile Cloudflare CAPTCHA?

Turnstile is Cloudflare’s smart CAPTCHA alternative that can be embedded into any website. It uses a variety of non-intrusive challenges to verify that visitors are human, without requiring them to solve CAPTCHAs. This can improve the user experience and reduce the amount of time that humans spend solving CAPTCHAs.

How turnstile cloudflare captcha work

Turnstile works by using a variety of factors to determine whether a visitor is a bot or a human. These factors include:

  • The visitor's IP address

  • The visitor's browser fingerprint

  • The visitor's behavior on the website

If Turnstile determines that a visitor is a bot, it will present them with a challenge. These challenges can be anything from clicking a button to solving a math problem. If the visitor completes the challenge successfully, they will be allowed to continue on to the website.

Turnstile is a more secure and privacy-preserving alternative to traditional CAPTCHAs. It does not require visitors to provide any personal information, and it does not track their behavior on the website. This makes it a better choice for websites that are concerned about user privacy.

Turnstile can be embedded in various forms in an application, from a visual widget to a completely invisible widget running in the background.

Turnstile widget types include:

  • A non-interactive challenge.

  • A non-intrusive interactive challenge (such as clicking a button), if the visitor is a suspected bot.

  • An invisible challenge to the browser.

To use Turnstile, you will need to create a Cloudflare account and enable Turnstile for your website. You can then embed the Turnstile widget into your website. Once you have done this, Turnstile will automatically start verifying visitors and presenting them with challenges if necessary.

A Step-by-Step Guide to Adding Turnstile Cloudflare Captcha to Your Website

To start using the Turnstile widget, you will need to obtain a sitekey and a secret key. The sitekey and secret key are always associated with one widget and cannot be reused for other widgets.

The sitekey is public and used to invoke the Turnstile widget on your site.

The sitekey and secret key are generated upon the creation of a widget, allowing communication between your site and Cloudflare to verify responses for a solved challenge from Turnstile. Make sure you keep the secret key safe for security reasons.

​​New sites

  1. Log in to the Cloudflare dashboard and select your account.

  2. Go to Turnstile.

  3. Select Add a site and fill out the form.

  4. Copy your sitekey and secret key.

​​Existing sites

  1. Log in to the Cloudflare dashboard and select your account.

  2. Go to Turnstile.

  3. In the widget overview, select Settings.

  4. Copy your sitekey and secret key.

Add the Turnstile widget to your site

To add the Turnstile widget:

  1. Insert the Turnstile script snippet in your HTML’s <head> element:
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
  1. For client-side integration, you have the option of choosing between explicit rendering and implicit rendering.
    However, today we will focus on implicit rendering. For explicit rendering, you can refer to the Cloudflare documentation.

  2. Turnstile is often used to protect forms on websites such as login forms, contact forms, and more. After inserting the JavaScript script tag, customers can embed <div class="cf-turnstile"></div> into their site to protect their forms.

Client Side Example

<form action="/login" method="POST">
   <input type="text" placeholder="username"/>
   <input type="password" placeholder="password"/>
   <div class="cf-turnstile" data-sitekey="<YOUR_SITE_KEY>"></div>
   <button type="submit" value="Submit">Log in</button>
</form>

An invisible input with the name cf-turnstile-response is added and will be sent to the server with the other fields.

Server Side Example

// This is the demo secret key. In production, we recommend
// you store your secret key(s) safely.
const SECRET_KEY = '1x0000000000000000000000000000000AA';

async function handlePost(request) {
    const body = await request.formData();
    // Turnstile injects a token in "cf-turnstile-response".
    const token = body.get('cf-turnstile-response');
    const ip = request.headers.get('CF-Connecting-IP');

    // Validate the token by calling the
    // "/siteverify" API endpoint.
    let formData = new FormData();
    formData.append('secret', SECRET_KEY);
    formData.append('response', token);
    formData.append('remoteip', ip);

    const url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
    const result = await fetch(url, {
        body: formData,
        method: 'POST',
    });

    const outcome = await result.json();
    if (outcome.success) {
        // ...
    }
}

This code snippet is a JavaScript function that handles a POST request to validate a Turnstile Cloudflare CAPTCHA.

First, it defines a constant SECRET_KEY with a demo secret key (in production, it is recommended to store the secret key securely).

Then, in the async function handlePost(request), the function waits for a POST request using await request.formData(). The function also gets the CAPTCHA token from the request body, cf-turnstile-response and the IP address of the client that made the request through the CF-Connecting-IP header.

After that, the function creates a new formData object and appends the secret key, token, and IP address to it. Then, it defines the url constant that points to the Turnstile Cloudflare /siteverify API endpoint. Finally, it executes a fetch() function with a POST method to validate the CAPTCHA token.

If the validation is successful (outcome.success is true), the CAPTCHA has been verified and this function can continue with further processing of the submitted data. If the validation fails, the CAPTCHA verification has failed and the user's request should be rejected as they may be a bot.