DEV Community

Cover image for How to add Google ReCAPTCHA in your React website
Kurt De Austria
Kurt De Austria

Posted on

How to add Google ReCAPTCHA in your React website

What is a CAPTCHA?

A CAPTCHA test is basically a way to check if you're a real person or just a bot. CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart," and you've probably seen them all over the web. They're a common tool to stop bots, but they do have their downsides.

Even though CAPTCHAs are there to block bots, they’re automated too. They pop up in certain spots on a website and decide on their own if you pass or fail the test.


What is ReCAPTCHA?

reCAPTCHA is a free service from Google that’s basically an upgrade to the old CAPTCHA tests. It was originally developed by researchers at Carnegie Mellon University, and Google picked it up in 2009.

What makes reCAPTCHA different is that it’s more advanced than regular CAPTCHA. Sometimes, like with traditional CAPTCHA, you might be asked to enter text from images that computers struggle to read. But with reCAPTCHA, the text comes from real-world sources, like street signs, printed books, or old newspapers. So, it’s not just random letters — it’s real information that helps improve things like map accuracy and digital archives.

I recently integrated reCAPTCHA in my side project shrt.lr, a URL shortener, to avoid spams and bots that could potentially mess up with my website. Using React and Express JS we will integrate it on both client and server side.


Create a ReCAPTCHA in Google

Sign in and create a Site key in Google reCaptcha

Enter your label:
Label

Under Captcha type, select Challenge v2 and use the "I'm not a robot" Checkbox
captcha type

For domains, type "localhost" with no ports and "http"
Domains

but if you have a website already, type your domain (e.g yourwebsite.com, yourwebsite.xyz), then click Submit.

KeysYou will be given a SITE KEY and SECRET KEY.


Client Side Integration (React TS + Vite app)

Paste the SITE KEY in to your .env file.

VITE_SITE_KEY="YOUR_SITE_KEY"
Enter fullscreen mode Exit fullscreen mode

Install react-google-reCAPTCHA

npm install --save react-google-reCAPTCHA
Enter fullscreen mode Exit fullscreen mode

Once done, you can now use the ReCAPTCHA tag in your app.

import ReCAPTCHA from "react-google-recaptcha"

function App() {
const SITE_KEY = import.meta.env.VITE_SITE_KEY
// For submit button
const [capVerified, setCapVerified] = useState<boolean>(false);

// Get the API to verify the captcha
  const verifyCaptcha = async (token: any) => {
    const res = await post('verifyCap', { capVal: token })
    setCapVerified(res.data.message.success) // toggles enable and disable for submit button
  }

return (
 <>
  {/* INPUT FORM ... */}
   <ReCAPTCHA
    sitekey={`${SITE_KEY}`}
    onChange={(val) => { verifyCaptcha(val) }}
    theme='dark'
    />

   <button
    disabled={!capVerified}
    className="px-6 py-7"
    type="submit">Submit</button>
 </>
 )
}

export default App
Enter fullscreen mode Exit fullscreen mode

onChange() allow us to fetch the token value that ReCAPTCHA returns after a user solved the challenge. The token is a long string that needs to be verified if the user is not a bot.

To check, run the app and open it on your browser

npm run dev
Enter fullscreen mode Exit fullscreen mode

This is what it looks like in my website
Image1

Image2

It works! but we are not done yet! We need to verify the token value on our server side. To verify the captcha, we will use the Google API for this. We need to insert the SECRET KEY and the TOKEN into this API:
https://www.google.com/recaptcha/api/siteverify?secret=${process.env.SITE_SECRET}&response=${captchaValue}

This API will return a JSON value like this:

{
    "message": {
        "success": true,
        "challenge_ts": "2024-09-28T05:54:49Z",
        "hostname": "localhost"
    }
}
Enter fullscreen mode Exit fullscreen mode

More of this on Google ReCAPTCHA documentation

Now to integrate this on our server side...


Server-Side Integration (Express JS)

Paste the SECRET KEY in to your .env file.

SITE_SECRET="YOUR_SECRET_KEY"
Enter fullscreen mode Exit fullscreen mode

First, install axios

npm install axios
Enter fullscreen mode Exit fullscreen mode

Create a POST API end point

    // Verify reCaptcha
    app.post('/verifyCap', async (req, res) => {
        const captchaValue = req.body.capVal; 
        try {
            const { data, error } = await axios.post(
                `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.SITE_SECRET}&response=${captchaValue}`,
            );
            res.status(200).json({
                "message": data
            }) // Send back the reCAPTCHA verification data
        } catch (error) {
            console.error(error);
            res.status(500).json({
                "error": 'Captcha verification failed'
            });
        }
    });

Enter fullscreen mode Exit fullscreen mode

Done! You have successfully integrated reCAPTCHA in your website!
If you have questions, feel free to ask!

My website: https://kurt-chan.vercel.app/

THANK YOU FOR READING!

Top comments (0)