GoogleReCaptchaProvider component is a React Context provider that loads the Google ReCAPTCHA v3 script and makes the reCAPTCHA API available to all child components.
Place the
GoogleReCaptchaProvider as high as possible in your React component tree to ensure you only have one instance of Google ReCAPTCHA per page.Installation
Basic Usage
- TypeScript
- JavaScript
Props
Your Google ReCAPTCHA v3 site key. You can obtain one from the Google ReCAPTCHA admin console.
The React components that should have access to the ReCAPTCHA context.
Optional language code for the ReCAPTCHA widget. See supported languages.Example:
"en", "es", "fr", "de", etc.Whether to load the script from
recaptcha.net instead of google.com. This is useful for regions where google.com is blocked.See Google’s FAQ for more information.Enable Google ReCAPTCHA Enterprise. When enabled, you must create Enterprise keys (not standard v3 keys).See the migration guide for more information.
Configuration options for the injected
<script> tag.Content Security Policy nonce for the script tag.
Add the
defer attribute to the script tag.Add the
async attribute to the script tag.Where to append the script tag in the document.
Custom ID for the script tag.
Custom name for the global onload callback function.
Configuration for rendering the reCAPTCHA badge in a custom container element.
The ID of a DOM element or an HTMLElement reference where the reCAPTCHA badge should be rendered.If provided as a string, it will be used as both the container ID and a
<div> with this ID will be created by the GoogleReCaptcha component.Configuration parameters for the reCAPTCHA badge.
Position of the reCAPTCHA badge. Use
'inline' to render it within the custom container.Theme for the reCAPTCHA badge.
Tab index for the reCAPTCHA badge.
Callback function executed when the user successfully completes the reCAPTCHA challenge.
Callback function executed when the reCAPTCHA response expires.
Callback function executed when reCAPTCHA encounters an error.
Advanced Examples
With Custom Script Configuration
With Language Support
With Custom Badge Container
With Enterprise Edition
Using recaptcha.net Domain
Best Practices
Environment Variables: Store your reCAPTCHA site key in environment variables (e.g.,
NEXT_PUBLIC_RECAPTCHA_SITE_KEY) instead of hardcoding it.Context Value
The provider makes the following values available through React Context:executeRecaptcha: Function to execute reCAPTCHA validation (available after script loads)container: The container element reference (if custom container is used)
Cleanup
The provider automatically cleans up when unmounted:- Removes the injected script tag
- Removes the reCAPTCHA badge
- Cleans up global window variables
See Also
- useGoogleReCaptcha Hook - React Hook for accessing reCAPTCHA
- GoogleReCaptcha Component - Declarative component for reCAPTCHA validation
- withGoogleReCaptcha HOC - Higher-order component for class components