Install Google reCaptcha in your React/Next js app.

Published on:
Modified on:

To prevent the bots from sending you thousand message a day from your contact form, you should use some system to detect if the visitor is a real human or a bot pretending to be a human.

To do so, you can use google reCaptcha. reCaptcha can determine if a visitor is a human or a bot using a score. Thats all done at their end so we do not have to worry about that. This article will show how we can add google reCaptcha v3 or invisible captcha into a reactjs/nextjs website.

Step 1:
Install react-google-recaptcha-v3 into your project by running this in your ternimal in vscode.

npm i react-google-recaptcha-v3
Enter fullscreen mode Exit fullscreen mode

Step 2:
Then go to the admin console of the google reCaptcha. You have to login using your gmail account.

Step 3:
Register a new site

  • Add a label (can be your site name or any name you prefer)
  • Select recaotcha type to v3 (score based)
  • Add your domain(s)
  • Agree to the terms and conditions and
  • Press Submit

Step 4:
You will get 2 keys under reCaptcha Keys section

Step 5:
Copy the site key because thats the key we need for this project

Step 6:
Go to your project in vscode, and go to file you want to add your google reCaptcha v3 (for this example we will add to the contact page where our form lives)

Step 7:
Import 2 utilities from the package we have installed in step 1

import { GoogleReCaptcha, GoogleReCaptchaProvider } from "react-google-recaptcha-v3";
Enter fullscreen mode Exit fullscreen mode

Step 8:
Wrap the entire component with the provider like this

const contact = () => {
    return (
        <GoogleReCaptchaProvider reCaptchaKey="<YOUR SITE KEY FROM STEP 5>">
            //rest of your code goes here
Enter fullscreen mode Exit fullscreen mode

Step 9:
We need a state to store the reCaptcha value, so lets import the setState function from react and initiate a state.

const [captcha, setCaptcha] = useState(null);
Enter fullscreen mode Exit fullscreen mode

Step: 10
Inside of your form, before the submit button add the capthca component we imported in step 7

<textarea {...register("Message", {})} placeholder="Your Message" className='message' />
<GoogleReCaptcha onVerify={(val) => setCaptcha(val)} />
<input type="submit" value="Send" className='submit' />
Enter fullscreen mode Exit fullscreen mode

This will set the captcha value to the captcha state we made.

Step: 11
Now inside your onSubmit function you can conditionally send the message or reject it based on the captcha value

const onSubmit = data => {
    if (captcha) {
        //send the mail
Enter fullscreen mode Exit fullscreen mode

Voilà! you are all set. Now bots can not annoy you with junk mails.