Google reCAPTCHA with React

When building modern web applications, ensuring the security of forms and other inputs is crucial. Google reCAPTCHA is one of the best tools to protect your site from bots and spam. In this guide, we will explore how to integrate Google reCAPTCHA into a React application. By the end of this tutorial, you’ll have a solid understanding of how to use it and ensure that your forms are protected from malicious activity.

What is Google reCAPTCHA?

Google reCAPTCHA is a free service designed to stop automated bots while allowing real users to pass through easily. It works by analyzing user interactions and ensuring that the entity filling out the form or performing some action is human. Google offers two main types of reCAPTCHA:

  • reCAPTCHA v2: The traditional checkbox-based reCAPTCHA.
  • reCAPTCHA v3: An invisible reCAPTCHA that works behind the scenes and assigns a score to the user’s interaction.

Why Use Google reCAPTCHA in Your React App?

  • Bot Protection: reCAPTCHA effectively prevents bots from submitting forms or performing actions on your site.
  • Better User Experience: While protecting your site, Google reCAPTCHA minimizes the user interaction needed, especially with reCAPTCHA v3.
  • Easy Integration: Google provides simple APIs that allow easy integration with React.

Step-by-Step Guide to Adding Google reCAPTCHA to React

1. Set Up Google reCAPTCHA

Before you start coding, you need to set up reCAPTCHA on your site.

  1. Go to the reCAPTCHA Admin Console: Visit Google reCAPTCHA Admin and register your site. You will need:
  • A label for your reCAPTCHA
  • The type of reCAPTCHA (v2 or v3)
  • Domain(s) where you’ll use reCAPTCHA
  1. Get Site and Secret Keys: Once registered, Google will provide you with a site key and a secret key. The site key will be used on your front end, while the secret key is for server-side validation.

2. Install Required Packages

To integrate Google reCAPTCHA with React, you need the react-google-recaptcha package.

npm install react-google-recaptcha

This library will help you easily integrate reCAPTCHA v2. If you plan to use reCAPTCHA v3, you can also use the react-google-recaptcha-v3 package.

3. Adding reCAPTCHA to Your React Component

Here’s a simple example of how to integrate reCAPTCHA v2 with a form.

import React, { useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';

const RECAPTCHA_SITE_KEY = 'your-site-key-here';

const ContactForm = () => {
  const [verified, setVerified] = useState(false);

  const onSubmit = (e) => {
    e.preventDefault();
    if (verified) {
      alert('Form submitted');
      // Proceed with form submission
    } else {
      alert('Please verify the CAPTCHA');
    }
  };

  const onRecaptchaChange = (value) => {
    setVerified(!!value); // If value is not null or undefined, set verified to true
  };

  return (
    <form onSubmit={onSubmit}>
      <input type="text" placeholder="Name" required />
      <input type="email" placeholder="Email" required />
      <textarea placeholder="Your message" required />
      <ReCAPTCHA
        sitekey={RECAPTCHA_SITE_KEY}
        onChange={onRecaptchaChange}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default ContactForm;

In this code:

  • The ReCAPTCHA component renders the CAPTCHA widget.
  • When the user successfully verifies the CAPTCHA, onRecaptchaChange is called, and we update the verified state.
  • On form submission, we check if the CAPTCHA is verified before proceeding.

4. Server-Side Verification (Node.js Example)

After a user successfully submits the form and passes the CAPTCHA, you’ll need to validate the CAPTCHA on the server. Here’s how you can do that in a Node.js environment.

First, install the required axios package for making HTTP requests.

npm install axios

Then, on your server:

const axios = require('axios');

const SECRET_KEY = 'your-secret-key-here';

const verifyRecaptcha = async (token) => {
  try {
    const response = await axios.post(
      `https://www.google.com/recaptcha/api/siteverify`,
      {},
      {
        params: {
          secret: SECRET_KEY,
          response: token,
        },
      }
    );
    return response.data.success;
  } catch (error) {
    console.error('Error verifying CAPTCHA', error);
    return false;
  }
};

In this code:

  • We send a POST request to Google’s API to verify the CAPTCHA token received from the client.
  • If Google validates the token, response.data.success will be true, meaning the CAPTCHA check passed.

5. Integrating reCAPTCHA v3

For reCAPTCHA v3, which works invisibly, you can use the react-google-recaptcha-v3 package. Here’s an example of integrating v3.

npm install react-google-recaptcha-v3

Then, implement it in your React component:

import { useGoogleReCaptcha } from 'react-google-recaptcha-v3';

const YourComponent = () => {
  const { executeRecaptcha } = useGoogleReCaptcha();

  const handleSubmit = async () => {
    if (!executeRecaptcha) {
      console.log('Execute recaptcha not yet available');
      return;
    }

    const token = await executeRecaptcha('yourAction');
    console.log('reCAPTCHA token:', token);
    // Send token to the server for verification
  };

  return (
    <button onClick={handleSubmit}>Submit</button>
  );
};

Here, reCAPTCHA v3 assigns a score based on the user’s interaction and does not require user action. You’ll still need to verify the token on the server, just like in reCAPTCHA v2.

Tips for a Smooth Integration

  1. Testing in Development: Use Google’s test keys for reCAPTCHA while developing your app to avoid hitting rate limits or facing incorrect configuration errors.
  2. Error Handling: Ensure proper error handling, such as informing the user when CAPTCHA verification fails.
  3. reCAPTCHA Configuration: Configure reCAPTCHA v3 thresholds based on your site’s needs. A lower score threshold (e.g., 0.3) might allow more suspicious activity, while a higher threshold (e.g., 0.7) could block more users.

Conclusion

Integrating Google reCAPTCHA into your React application is a straightforward process that enhances security and ensures only real users can interact with your forms. Whether you’re using reCAPTCHA v2 or v3, React provides easy-to-use libraries that allow seamless integration. Always remember to verify the CAPTCHA token on your server for full security.

By following this guide, you’ll have successfully integrated reCAPTCHA with React, ensuring a safer and more user-friendly experience for your visitors.


FAQs

Q: Can I use reCAPTCHA on any type of form?
Yes, reCAPTCHA can be integrated with any form, whether it’s a contact form, registration form, or even user action buttons.

Q: How do I know if reCAPTCHA is working?
You can test reCAPTCHA with Google’s test keys, or by completing the CAPTCHA challenge and checking the browser’s console for verification responses.

Thanks for reaching here.

Check out more technical articles in here.