A Step-by-Step Guide on How to Set up ReCAPTCHA in Your React Application

In the dynamic world of web development, ensuring the security of your applications is paramount. One powerful tool to protect your React application from spam and malicious activities is Google’s ReCAPTCHA. In this blog post, we’ll walk you through the process of integrating ReCAPTCHA into your React application, step by step.

Why ReCAPTCHA?

ReCAPTCHA is a widely used and trusted service provided by Google, designed to distinguish between human and automated bots. By implementing ReCAPTCHA, you add an extra layer of security to your application, safeguarding it against spam, fraud, and other malicious activities.

Prerequisites:

Before we dive into the implementation, make sure you have the following:

  1. A Google account to access the reCAPTCHA API.
  2. A React application set up using a tool like Create React App.

Setting up a React Application

Using the create-react-app package, generate a new react application on your machine by running the command:

Bash
npx create-react-app demo_app

Next, create a mock sign-in page with a form by updating the App component:

JavaScript
import React from "react"
import "./App.css"

function App() {
  return (
    <form>
      <input id='username' name='username' placeholder="Username" />
      <input type="password" id='password' name='password' placeholder="Password" />
      <button>Login</button>
    </form>
  )
}

export default App;

Then rewrite the ./App.css file to make the application a little bit pleasing to the eyes:

CSS
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

form {
  width: 300px;
  display: flex;
  flex-direction: column;
}

input,
button {
  text-align: center;
  height: 50px;
  margin: 15px 0;
  border: 1px solid #000;
}

button {
  background-color: #187efadf;
  color: #fff;
  cursor: pointer;
}

button:disabled {
  background: #a5a5a5;
  cursor: not-allowed;
}

Then start the application server by running the command via your command line:

Bash
npm start

You should have a running application at http://localhost:3000/ as such:

Generating reCAPTCHA Secret Keys

There are three current versions of Google’s reCAPTCHA:

  • reCAPTCHA v2
  • reCAPTCHA v3
  • reCAPTCHA Enterprises

For the purpose of this article, we are making use of the reCAPTCHA v2 which has the famous “I’m not a robot” checkbox.

First, you need to get a Client Key from the Google reCAPTCHA admin console by clicking here, which leads to this page below:

Enter the label to be able to identify the different projects or sites on Google reCAPTCHA. Select reCAPTCHA v2 under the reCAPTCHA type option then the ”I’m not a robot” Checkbox option.

The Domains option allows you to configure the number of domains (including subdomains) that has access to the registration. Since our react application is in development, you will add “localhost” in the Domain option.

Accept the reCAPTCHA terms of service then click the submit button to generate some keys that will be used later in this article.

To use the site key as an embedded environment variable in your react application, create a .env file in the root directory of your application. Copy the code below into the .env file and replace the site key with the one you generated from the Admin Console.

Bash
REACT_APP_RECAPTCHA_SITE_KEY=your_site_key

Integrate ReCAPTCHA into Your React Component

To integrate reCAPTCHA into your React application, we are making use of the react-google-recaptcha packages which provide a React component for reCAPTCHA v2.

First, install the package into your program by running this command via your command line:

Bash
npm install react-google-recaptcha
# or
yarn add react-google-recaptcha

The react-google-recaptcha package provides a ReCAPTCHA component to be used, for instance, as such:

JavaScript
import ReCAPTCHA from "react-google-recaptcha";
 
function onChange(value) {
	// what happens when 
  console.log("captcha value:", value);
}
 
ReactDOM.render(
  <ReCAPTCHA
    sitekey="The client site key from the Google reCAPTCHA admin console"
    onChange={onChange}
  />,
  document.body
)

The sitekey and onChange props are only necessary for the basic functionality of the ReCAPTCHA component but there are some optional props that can configure the appearance or the operations of the component. Some of the props :

  • sitekey: the client key from Google reCAPTCHA Admin Console
  • onChange: the function that is called when a user completes the captcha successfully
  • theme: (light or dark) sets the theme of the reCAPTCHA widget
  • type: (image or audio) defines the type of initial captcha
  • tabindex: the tabindex of the element
  • onExpired: the function that is called when a captcha has expired
  • size: (compactnormal, or invisible) allows you to define the size of the reCAPTCHA widget or do an invisible captcha.

Next, you will make use of the package in your program by updating the App component as such:

JavaScript
import React from "react";
import "./App.css";
import  ReCAPTCHA  from "react-google-recaptcha";

function App() {
  const [isCaptchaSuccessful, setIsCaptchaSuccess] = React.useState(false)

  function onChange(value) {
    setIsCaptchaSuccess(true)
    console.log("captcha value: ", value);
  }

  return (
    <>
      <form>
        <input id="username" name="username" placeholder="Username" />
        <input
          type="password"
          id="password"
          name="password"
          placeholder="Password"
        />
        <ReCAPTCHA
          sitekey={process.env.REACT_APP_RECAPTCHA_SITE_KEY}
          onChange={onChange}
          />
          <button disabled={!isCaptchaSuccessful}>Login</button>
      </form>
    </>
  );
}

export default App;

The isCaptchaSuccessful state is used to ensure the submit button is disabled until the captcha challenge is successfully completed.

As it is not recommended to validate only from the client side, you not only rely on the reCAPTCHA implementation on the client side. You can send the token derived from the onChange props and verify it from the server side using Google’s reCAPTCHA server-side API. You can find more about this here.

create-react-app cannot bundle environment variables from the .env file at runtime so you need to rebuild the react app by ending the previous server you started and starting a new one with the command:

Bash
npm start

Then the reCAPTCHA widget with a disabled submit button would be visible on your application as such:

Passing the challenge would make the button accessible as such:

Conclusion

At the end of this article, we discussed what reCAPTCHA is and how it can prevent your application from malicious bots or automated programs. You also demonstrated how to integrate reCAPTCHA into a React application.

I hope you find the article helpful to help you prevent your React applications from bots or malicious automated programs.

Related Posts

semantic html

SEO Secret Weapon: Leverage Semantic HTML for Better Results

In the ever-evolving world of SEO, the key to success lies in clear communication, not just with your users, but also with search engines. This is where…

React Data Fetching & Management

Level Up Your React: Data Fetching & Management

Welcome back to the React 101 series! In this edition, we’ll learn about how to fetch data from APIs and manage data flow within your React applications….

secure nodejs

Securing Your Node.js Application: Best Practices and Strategies

Node.js is a popular and powerful runtime for building server-side applications with JavaScript. However, as with any web application, security should be a top priority. In this…

learning css variables

Learn CSS Variables and Theme Your Websites Like a Master

Elevate your web development game by embracing the power of CSS theming and providing users with a visually captivating and personalized experience.

React 19 New Features

React 19: New Features and Upcoming Major Releases in 2024

Get ready for some exciting news from the ReactJS official blog! If you love ReactJS, you’re in for a treat. We’ll take you through the latest cool stuff, like the supercharged React Compiler, the game-changing Actions, and new features in React Canary.

building ui elements with jsx

Building UI Elements with JSX and Components

Ready to dive into React? This chapter unlocks the secrets of JSX – writing HTML right in your JavaScript! We’ll also explore components, the reusable powerhouses of React .

Leave a Reply

Your email address will not be published. Required fields are marked *