Andi Ashari

Tech Voyager & Digital Visionary

Implementing reCAPTCHA v3 in HTML, JavaScript, and Express.js

Implementing reCAPTCHA v3 in HTML, JavaScript, and Express.js

Integrating Google’s reCAPTCHA v3 into your web application enhances security without compromising user experience. This invisible CAPTCHA system assesses user interactions to detect bots, offering a score to determine the authenticity of each interaction. Here, we’ll guide you through adding reCAPTCHA v3 to a web application using HTML, JavaScript, and Express.js.

Prerequisites

Before proceeding, ensure you have:

  • Basic knowledge of HTML, JavaScript, and Express.js.
  • An active Google account to access the reCAPTCHA Admin console for your site keys.

Step-by-Step Integration

Register Your Site with Google reCAPTCHA

First, visit the Google reCAPTCHA Admin console and register your site. Select reCAPTCHA v3 and note down the site key and secret key provided.

Frontend Setup in HTML and JavaScript

HTML:

Integrate the reCAPTCHA JavaScript API into your HTML page. Place this script tag in the <head> section:

<script src="https://www.google.com/recaptcha/api.js?render=your_site_key"></script>

Replace your_site_key with the actual site key obtained from the Google Admin console.

JavaScript:

Add a function to handle form submission, invoking reCAPTCHA when the user performs an action (like clicking a submit button):

<script>
  function handleSubmit(e) {
    e.preventDefault();
    grecaptcha.ready(function () {
        grecaptcha.execute('your_site_key', { action: 'submit' }).then(function (token) {
            // Add the token to a hidden form field
            document.getElementById('recaptchaResponse').value = token;
            // Submit the form
            document.getElementById('your-form-id').submit();
        });
    });
}
</script>

In your form, add a hidden input to store the reCAPTCHA token:

<form id="your-form-id" action="/submit-form" method="POST">
    <!-- Your form fields -->
    <input type="hidden" id="recaptchaResponse" name="recaptchaResponse">
    <button type="submit" onclick="handleSubmit(event)">Submit</button>
</form>

Backend Validation with Express.js

In your Express.js server, you’ll need to verify the reCAPTCHA response token with Google’s verification API.

Install Required Package:

Use axios or any HTTP client to make requests from your server:

npm install axios

Express.js Route:

Create a route to handle the form submission:

const express = require('express');
const axios = require('axios');
const app = express();

app.post('/submit-form', async (req, res) => {
    const secretKey = 'your_secret_key'; // Replace with your secret key
    const token = req.body.recaptchaResponse;
    // Verify URL
    const verifyURL = new URL(`https://www.google.com/recaptcha/api/siteverify`);
    verifyURL.searchParams.append('secret', secretKey);
    verifyURL.searchParams.append('response', token)
    // Make a request to verifyURL
    const verificationResponse = await axios.post(verifyURL.toString());
    if (verificationResponse.data.success && verificationResponse.data.score >= 0.5) {
        // If score is greater than 0.5 then only user will be verified
        // Do your stuffs here if user is verified
    } else {
        // If score is less than 0.5 then user is not verified/failed
        // Do your stuffs here if user is not verified
    }
});

Best Practices

  • Regularly monitor the reCAPTCHA scores in the admin console to adjust the threshold according to your site’s needs.
  • Remember to keep actions consistent and meaningful across your site for accurate scoring.
  • Secure your secret key and avoid exposing it on the client side.

Conclusion

Incorporating reCAPTCHA v3 in your web application with HTML, JavaScript, and Express.js is a robust way to improve security while maintaining a smooth user experience. This setup not only deters bots but also provides valuable insights into traffic patterns on your site. Remember to adjust and fine-tune the reCAPTCHA settings based on the analytics provided in the Google reCAPTCHA admin console.