A React hook for Google reCAPTCHA v3 integration with TypeScript support.
- π Google reCAPTCHA v3 integration
- βοΈ React Hook - Easy to use in functional components
- π TypeScript - Full type safety
- π― Lightweight - Minimal dependencies
- π Modern - Uses latest React patterns
- π§ Flexible - Customizable options and actions
# npm
npm install use-google-recaptcha
# yarn
yarn add use-google-recaptcha
# pnpm
pnpm add use-google-recaptchaBefore using this hook, you need to:
- Register your site at Google reCAPTCHA Admin Console
- Get your site key for reCAPTCHA v3
- Add your domain to the reCAPTCHA configuration
import React from 'react';
import { useGoogleReCaptcha } from 'use-google-recaptcha';
function MyComponent() {
const { execute, executing } = useGoogleReCaptcha({
key: 'your-recaptcha-site-key'
});
const handleSubmit = async () => {
try {
const token = await execute('submit');
console.log('reCAPTCHA token:', token);
// Send token to your backend for verification
// const response = await fetch('/api/verify-recaptcha', {
// method: 'POST',
// body: JSON.stringify({ token }),
// headers: { 'Content-Type': 'application/json' }
// });
} catch (error) {
console.error('reCAPTCHA error:', error);
}
};
return (
<div>
<button
onClick={handleSubmit}
disabled={executing}
>
{executing ? 'Verifying...' : 'Submit'}
</button>
</div>
);
}You can also use environment variables to store your reCAPTCHA site key:
// .env.local (Next.js)
NEXT_PUBLIC_RECAPTHA_SITE_KEY=your-site-key
// .env (Create React App)
REACT_APP_RECAPTHA_SITE_KEY=your-site-keyimport { useGoogleReCaptcha } from 'use-google-recaptcha';
function MyComponent() {
// The hook will automatically use the environment variable
const { execute, executing } = useGoogleReCaptcha();
// ... rest of your component
}options(optional): Configuration objectkey?: string- Your reCAPTCHA site key. If not provided, will use environment variablesnonce?: string- Optional nonce for Content Security Policy
An object with the following properties:
execute: (action?: string) => Promise<string>- Function to execute reCAPTCHAexecuting: boolean- Whether reCAPTCHA is currently executing
The execute function accepts an optional action parameter that helps you analyze different user interactions:
await execute('login'); // For login forms
await execute('contact'); // For contact forms
await execute('purchase'); // For purchase flows
await execute('search'); // For search functionalityThe hook supports the following environment variables:
REACT_APP_RECAPTHA_SITE_KEY- For Create React AppNEXT_PUBLIC_RECAPTHA_SITE_KEY- For Next.js
This package is written in TypeScript and includes full type definitions. You'll get autocomplete and type checking out of the box.
import { useGoogleReCaptcha, IReCaptchaInstance } from 'use-google-recaptcha';
// All types are exported for your convenience
const { execute, executing } = useGoogleReCaptcha();Remember to verify the reCAPTCHA token on your backend:
// Example Node.js/Express verification
app.post('/api/verify-recaptcha', async (req, res) => {
const { token } = req.body;
const response = await fetch('https://www.google.com/recaptcha/api/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${token}`
});
const data = await response.json();
if (data.success && data.score > 0.5) {
// Token is valid and score is acceptable
res.json({ success: true });
} else {
// Token is invalid or score is too low
res.status(400).json({ error: 'reCAPTCHA verification failed' });
}
});Contributions are welcome! Please feel free to submit a Pull Request.
MIT Β© Dmitrii Selikhov