Google ReCaptcha

Having Google reCaptcha on your website can really be beneficial in order not get spammed by bots and robots. Let’s see how to implement that the frontend way.

Backend

Ok, so as a frontend developer, do I need a backend solution for that? The good news is, No.

You can only rely on Google APIs only which is really easy and straight forward and in this post we will go through every step in order to do it together.

start your engines

Pricing

The good news is that it’s free. Well, not completely free, but you get charged after 10,000 (10K) assessments per month, if that happened, I believe you will be rich by then :D.

Let’s Start

Make sure you are signed to your google account and go to: https://www.google.com/recaptcha/admin/create

Start by adding a label to your Google captcha, let’s say: my-very-hard-captcha-for-my-blog or you can just label it with your domain, so for me it should be: josepham.me

Google reCaptcha Types

Now, let’s select the Google reCaptcha type, for me I love the invisible one, but of course you can select whichever you want

Google reCaptcha Types Explained

1. Google reCAPTCHA v2

Description: reCAPTCHA v2 presents a challenge to the user, usually in the form of identifying objects in images or clicking a checkbox that says “I’m not a robot.” It verifies human behavior through these tasks and other signals.

Variants:

  • “I’m not a robot” Checkbox: The user clicks a checkbox, and reCAPTCHA monitors their interaction and other signals to determine if they’re human.
  • Invisible reCAPTCHA: No challenge is shown to the user unless reCAPTCHA determines further verification is needed. It runs in the background and can trigger a challenge based on user behavior.

2. Google reCAPTCHA v3

Description: reCAPTCHA v3 is an advanced, risk-analysis-based approach that runs completely in the background. It assigns a score to user interactions based on their behavior and other contextual signals, with no user interaction required.

Domains

So, for domains, if you are just testing the captcha, just enter: localhost. Otherwise, enter your domain, so for me it would be: josepham.me

Hi “Submit” and that’s it.

You will get two keys, SAVE THEM !

The Code Part

Now, we need to include the captcha in our website, how do we do that?

First of all, let’s include our google script

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Add this in your head tag of your HTML.

and then in your form submission, we do this.

Let’s say we have a form for username, email and some stuff.

We add a click listener on the submit button and prevent the form from being submitted with `event.preventDefault()`.

We call the captcha execute method and checks for the return, if it’s null, then the captcha failed, if it continues, then everything is good.

Don’t forget to replace SITE ID in the div with your stored site id.

So, the complete code will be something like that:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>reCAPTCHA Form with Callback</title>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
    <form id="myForm" action="YOUR_FORM_SUBMISSION_URL" method="POST">
        <h2>Contact Us</h2>
        
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br><br>
        
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br><br>
        
        <label for="message">Message:</label><br>
        <textarea id="message" name="message" rows="4" cols="50" required></textarea><br><br>
        
        <!-- reCAPTCHA widget with callback -->
        <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY" data-callback="onReCaptchaSuccess"></div><br>
        
        <button type="submit" id="submitBtn" disabled>Submit</button>
    </form>

    <script>
        function onReCaptchaSuccess(token) {
            document.getElementById('submitBtn').disabled = false;

            document.getElementById('myForm').addEventListener('submit', function(event) {
                event.preventDefault();

                var recaptchaResponse = grecaptcha.getResponse();
                if (recaptchaResponse.length === 0) {
                    alert('reCAPTCHA validation failed. Please try again.');
                    return;
                }

                // If reCAPTCHA is completed, submit the form (add your submission logic here)
                // Example: AJAX submission or traditional form submission

                // Traditional form submission (uncomment to use)
                // this.submit();

                // AJAX form submission example (comment out if not needed)
                var formData = new FormData(this);
                formData.append('g-recaptcha-response', recaptchaResponse);

                fetch(this.action, {
                    method: 'POST',
                    body: formData
                }).then(function(response) {
                    return response.json();
                }).then(function(data) {
                    console.log(data);
                    // Handle the response from the server here
                }).catch(function(error) {
                    console.error('Error:', error);
                });
            });
        }
    </script>
</body>
</html>

And that’s it, simple right??

Here’s a robot potato because you lasted all the way down.

robot potato

Check out the rest of the frontend articles.