React Google reCAPTCHA v3 Integration

1.11.0 · active · verified Tue Apr 21

react-google-recaptcha-v3 is a React library that simplifies the integration of Google reCAPTCHA v3 into web applications. It provides a `GoogleReCaptchaProvider` component to manage the reCAPTCHA script loading and context, along with a `useGoogleReCaptcha` hook and a `withGoogleReCaptcha` HOC for executing reCAPTCHA validation programmatically. The library is currently at version 1.11.0 and maintains an active release cadence with regular updates and fixes. It differentiates itself by offering flexible script injection control via `scriptProps` and explicit support for Google reCAPTCHA Enterprise, requiring specific key types and 'Scoring' integration. This library focuses on an invisible reCAPTCHA experience, providing a score to differentiate human from bot interactions without interrupting the user flow.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `GoogleReCaptchaProvider` and use the `useGoogleReCaptcha` hook to execute reCAPTCHA v3 verification upon form submission. It shows handling of loading states and the retrieved token, and highlights the necessity of providing a site key.

import React, { useState, useCallback, useEffect } from 'react';
import { GoogleReCaptchaProvider, useGoogleReCaptcha } from 'react-google-recaptcha-v3';

const RECAPTCHA_SITE_KEY = process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY ?? 'YOUR_SITE_KEY';

const RecaptchaForm = () => {
  const { executeRecaptcha } = useGoogleReCaptcha();
  const [token, setToken] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleReCaptchaVerify = useCallback(async () => {
    setLoading(true);
    setError(null);
    if (!executeRecaptcha) {
      setError('reCAPTCHA not loaded yet!');
      setLoading(false);
      return;
    }

    try {
      const result = await executeRecaptcha('form_submission');
      setToken(result);
      console.log('reCAPTCHA token:', result);
      // In a real application, send this token to your backend for verification
    } catch (e) {
      console.error('reCAPTCHA execution failed:', e);
      setError('Failed to get reCAPTCHA token.');
    } finally {
      setLoading(false);
    }
  }, [executeRecaptcha]);

  useEffect(() => {
    // Optionally execute reCAPTCHA on component mount or a specific event
    // handleReCaptchaVerify(); 
  }, [handleReCaptchaVerify]);

  return (
    <div>
      <h1>Contact Us</h1>
      <form onSubmit={(e) => { e.preventDefault(); handleReCaptchaVerify(); }}>
        {/* Your form fields here */}
        <p>This form is protected by reCAPTCHA.</p>
        <button type="submit" disabled={loading}>
          {loading ? 'Verifying...' : 'Submit Form'}
        </button>
        {token && <p>Token received: {token.substring(0, 15)}...</p>}
        {error && <p style={{ color: 'red' }}>Error: {error}</p>}
      </form>
    </div>
  );
};

export default function App() {
  if (!RECAPTCHA_SITE_KEY || RECAPTCHA_SITE_KEY === 'YOUR_SITE_KEY') {
    console.error('Please provide a reCAPTCHA site key via NEXT_PUBLIC_RECAPTCHA_SITE_KEY environment variable or directly in the code.');
    return <div>Error: reCAPTCHA site key is missing.</div>;
  }
  return (
    <GoogleReCaptchaProvider reCaptchaKey={RECAPTCHA_SITE_KEY} scriptProps={{ defer: true, async: true }}>
      <RecaptchaForm />
    </GoogleReCaptchaProvider>
  );
}

view raw JSON →