How to Implement Google reCAPTCHA in React.js with TypeScript
Google reCAPTCHA is a powerful tool that helps prevent automated bots from abusing your website’s forms and actions. In this blog post, we’ll walk through implementing both reCAPTCHA v2 (interactive) and reCAPTCHA v3 (non-interactive) in a React.js project using TypeScript. We’ll also discuss how to handle common tasks such as resetting reCAPTCHA and verifying the token.
Why Use Google reCAPTCHA?
Google reCAPTCHA protects your web applications from spam and abuse by detecting whether the user interacting with your application is human or a bot. It provides two main versions:
- reCAPTCHA v2: The traditional CAPTCHA, which may require user interaction.
- reCAPTCHA v3: Runs silently in the background and uses a score to determine the likelihood that a user is legitimate.
Setting Up Google reCAPTCHA
- Register Your Site with Google reCAPTCHA
- Visit the Google reCAPTCHA Admin Console.
- Register your site and get your site key and secret key.
- You can also add localhost as one of the domain to test the reCaptcha in development (Make sure the site key is never exposed anywhere)
- Install Required Packages
- For reCAPTCHA v2, use
react-google-recaptcha
. - For reCAPTCHA v3, use
react-google-recaptcha-v3
.
Install the appropriate package based on your reCAPTCHA version:
# For reCAPTCHA v2
npm install react-google-recaptcha
# For reCAPTCHA v3
npm install react-google-recaptcha-v3
Example 1: Implementing reCAPTCHA v2 (Interactive) in React.js
reCAPTCHA v2 requires user interaction and displays either a checkbox or an image challenge.
Step 1: Basic Setup for reCAPTCHA v2
Here’s how you can implement reCAPTCHA v2 in a TypeScript-based React.js project:
import React, { useRef, useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';
const RecaptchaV2Example: React.FC = () => {
const recaptchaRef = useRef<ReCAPTCHA>(null);
const [isCaptchaVerified, setIsCaptchaVerified] = useState(false);
const handleCaptchaChange = (token: string | null) => {
setIsCaptchaVerified(!!token);
};
const handleSubmit = () => {
if (isCaptchaVerified) {
alert('CAPTCHA verified, form submitted!');
} else {
alert('Please verify the CAPTCHA before submitting.');
}
};
return (
<div>
<ReCAPTCHA
ref={recaptchaRef}
sitekey="YOUR_SITE_KEY" // Replace with your actual site key
onChange={handleCaptchaChange}
/>
<button onClick={handleSubmit}>Submit</button>
</div>
);
};
export default RecaptchaV2Example;
Step 2: Resetting the CAPTCHA Programmatically
If you want to allow the user to reset the CAPTCHA without refreshing the page, you can reset it programmatically like this:
const resetCaptcha = () => {
recaptchaRef.current?.reset();
setIsCaptchaVerified(false);
};
Now, call resetCaptcha()
when needed.
Example 2: Implementing reCAPTCHA v3 (Non-Interactive) in React.js
reCAPTCHA v3 works silently in the background and assigns a score based on user interaction. It does not require any direct interaction from the user.
Step 1: Basic Setup for reCAPTCHA v3
import React, { useEffect } from 'react';
import { loadReCaptcha, ReCaptcha } from 'react-google-recaptcha-v3';
const RecaptchaV3Example: React.FC = () => {
useEffect(() => {
loadReCaptcha('YOUR_SITE_KEY'); // Replace with your reCAPTCHA v3 site key
}, []);
const handleSubmit = () => {
ReCaptcha.execute('submit_action').then((token) => {
console.log('reCAPTCHA v3 Token:', token);
// Send the token to your backend for verification
});
};
return (
<div>
<button onClick={handleSubmit}>Submit</button>
</div>
);
};
export default RecaptchaV3Example;
Step 2: Verifying the Token on the Server
After receiving the token from reCAPTCHA, send it to your backend for verification:
const axios = require('axios');
const verifyCaptcha = async (token) => {
const secretKey = 'YOUR_SECRET_KEY'; // Replace with your secret key
const response = await axios.post(
`https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${token}`
);
const data = response.data;
console.log('reCAPTCHA verification result:', data);
};
Handling CAPTCHA Expiration in reCAPTCHA v2
In reCAPTCHA v2, tokens expire after about 2 minutes. To handle this, you can use the onExpired
callback:
<ReCAPTCHA
sitekey="YOUR_SITE_KEY"
onChange={handleCaptchaChange}
onExpired={() => setIsCaptchaVerified(false)} // Reset the CAPTCHA verification state
/>
This ensures users can reverify themselves once the CAPTCHA expires.
Conclusion
Adding Google reCAPTCHA to your React.js applications helps to protect your forms and actions from abuse and spam. reCAPTCHA v2 offers interactive verification, while reCAPTCHA v3 provides a frictionless user experience by operating in the background. Both options provide powerful security, and depending on your use case, you can choose the one that fits your needs best.
By following the examples and instructions above, you can easily integrate reCAPTCHA in your TypeScript-based React projects.
Show some love ❤️ if you find it useful !!
Thank You! Keep Coding!