Integrate Google reCAPTCHA in a React Application

As web and mobile applications have become more popular, so too has the risk of spam and other malicious activity. CAPTCHAs can be a handy security measure worth integrating to prevent these types of security threats.

A CAPTCHA is a minimal security feature, commonly integrated with web forms to prevent automated attacks by spambots. It ensures that the user accessing an application is indeed human, and not a bot executing malicious code.

4

What Is CAPTCHA?

The acronym CAPTCHA stands for Completely Automated Public Turing test to tell Computers and Humans Apart. It refers to a computer-generated test that checks to determine if a particular user interacting with your application is a human and not a bot.

There are different types of CAPTCHA tests you can integrate into your application such as text-based and audio-based CAPTCHAs. However, the most popular and effective type is Google reCAPTCHA. It checks to distinguish between real users and bots using advanced risk analysis algorithms.

iCloud+ Website on MacBook Sitting on Kitchen Island

Google reCAPTCHA comes in two versions:

This guide will explore Google reCAPTCHA V2. Read on to learn how to integrate it into a React application.

BBC iPlayer showing on a smart TV.

Register the React Application on the reCAPTCHA Admin Console

To get started, you need to register your application on reCAPTCHA’s developer console. Head over toGoogle’s reCAPTCHA Admin Console,sign in with your Google account, and fill in the required form details.

Provide the label name, selectreCAPTCHA V2, and on the drop-down box, choose the verify requests using the “I’m not a robot” checkbox option. Lastly, provide your application’s domain name. For local development, typelocalhostas the domain name.

AI Chatbots open in multiple tabs

Once it’s registered your app, the site will redirect you to a new page with your generated secret and site keys.

Create a React Client

This project is two-fold: you will create a React client that renders a simple login form with the Google reCAPTCHA and an Express backend that makes POST requests to reCAPTCHA’s API to verify the token generated after a user completes the reCAPTCHA challenge.

Create a project folder locally to house your project files. Next,create the React applicationand change the current directory to that of the client. In the root directory of your client folder, create a .env file to store the API secret key and site key.

Code on laptop on ground

you’re able to find this project’s code in itsGitHub repository.

Install the Required Packages

Install Axios, you’ll use this library to make HTTP requests from the browser and React-Google-reCAPTCHA. This package provides a React-specific implementation for the reCAPTCHA API.

Integrate Google reCAPTCHA in the React Application

Open thesrc/App.js file, delete the boilerplate React code, and add the code below:

This component will render a simple login form that includes the Google reCAPTCHA widget.

First, import the React, Axios, and react-google-recaptcha packages:

Then define three state variables: successMsg, errorMsg, and validToken. Your code will update these states upon successful form submission and reCAPTCHA validation. Additionally, get the site and secret keys from the ENV file.

Define a useRef hook that references the reCAPTCHA component, to capture the token generated after a user completes the reCAPTCHA challenges.

Then, create a handleSubmit function to call when a user submits the login form. This function obtains the token from the reCAPTCHA component and then calls theresetmethod to reset the reCAPTCHA to allow subsequent checks.

In addition, it checks if the token exists, and calls the verifyToken function to verify the token. Once it’s verified the token, it will update the validToken state with the API response data.

Finally, define the verifyToken function which will send a POST request to an Express server endpoint using Axios, passing the reCAPTCHA token and the secret key in the request body. If the request is successful, it pushes the response data to the APIResponse array and returns the array as a result.

Lastly, return a form with the reCAPTCHA component. This component takes in the reference hook and site key as props to configure and display the reCAPTCHA widget.

When a user submits the form, the component renders a success or error message based on the value of validToken state. If the reCAPTCHA token is valid, meaning a user successfully completed the reCAPTCHA challenges, it displays the success message, otherwise, it displays the error message.

Finally, run the development server and head over to your browser of http://localhost:3000 to view the results.

Create the Express Backend

To get started, in the root directory of the entire project folder,create an Express web server,and install these packages:

Set Up the Express Server

Next, open the index.js file in the server project folder, and add this code:

This code does the following:

Finally, run the node server and test the reCAPTCHA feature functionality.

Can reCAPTCHAs Guarantee Security Against Spambots?

According to Google, its reCAPTCHA service has a success rate of over 99%, meaning only a small percentage of spam can bypass the reCAPTCHA security feature.

reCAPTCHA is not foolproof, since determined bad actors can still find workarounds. But it remains an essential tool that can significantly reduce the risk from spambots.

We’ve all had to tick the box, or the photos, to prove we’re real humans, but how important actually are CAPTCHAs? Here’s what you need to know.

Love fades, even for the best open-source darling.

You’re conveying the wrong meaning when you send these emojis.

I plugged random USB devices into my phone and was pleasantly surprised by how many actually worked.

Your phone is a better editor than you give it credit for.

You don’t need to fork out for expensive hardware to run an AI on your PC.

Technology Explained

PC & Mobile