๐ React Google ReCaptcha Ultimate
tool that easily and quickly add Google ReCaptcha for your website or application
Install
$ npm i react-google-recaptcha-ultimate # or $ yarn add react-google-recaptcha-ultimate
๐ฆ Philosophy
๐ React Google ReCaptcha Ultimate this is a library that will allow you to easily and quickly add Google ReCaptcha for your website or application. The main difference from other libraries is that all current versions of Google ReCaptcha are supported here.
Features
- Support all recaptcha versions โ support v3, v2-checkbox, v2-invisible
- Enterprise mode โ support enterprise
- TypeScript support out of the box โ full typed package
- SSR โ package work with server side render
Usage
Install ๐ React Google ReCaptcha Ultimate with npm or yarn
$ npm i react-google-recaptcha-ultimate # or $ yarn add react-google-recaptcha-ultimate
V3
Google ReCaptcha v3 returns a score for each request without user friction. The score is based on interactions with your site and enables you to take an appropriate action for your site.
import { GoogleReCaptchaProvider } from 'react-google-recaptcha-ultimate'; const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); root.render( <GoogleReCaptchaProvider type="v3" siteKey="Your recaptcha sitekey" > <App /> </GoogleReCaptchaProvider> );
V2 invisible
Google ReCaptcha v2 invisible does not require users to solve any puzzles or enter any codes. Instead, it runs in the background and analyzes user behavior on the web page to determine if they are genuine users or potential bots.
import { GoogleReCaptchaProvider } from 'react-google-recaptcha-ultimate'; const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); root.render( <GoogleReCaptchaProvider type="v2-invisible" siteKey="Your recaptcha key" > <App /> </GoogleReCaptchaProvider> );
V2 checkbox
When a user interacts with the Google ReCaptcha v2 checkbox, advanced algorithms analyze their behavior to distinguish between humans and bots. If the system suspects suspicious activity, additional challenges may be presented, such as image selections or puzzle-solving tasks.
import { GoogleReCaptchaProvider, GoogleReCaptchaCheckbox } from 'react-google-recaptcha-ultimate'; const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); root.render( <GoogleReCaptchaProvider type="v2-checkbox" siteKey="Your recaptcha key" > <GoogleReCaptchaCheckbox onChange={(token) => { console.log(token); }} /> </GoogleReCaptchaProvider> );
Checkbox component
PropsTypeDefaultRequired?NoteidStringNoId of componentactionStringNoAn action name is used to describe user-initiated events. More infoclassNameStringNoStyles for componentcontainerString or HTMLElementNoContainer ID where the recaptcha badge will be renderedcallback() => voidNoThe name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback.errorCallback() => voidNoThe name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry.expiredCallback() => voidNoThe name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.languageStringNooptional prop to support different languages that is supported by Google Recaptcha. Seethemedark
or lightlight
NoThe color theme of the widget.sizecompact
or normalnormal
NoThe size of the widget.onChange(token: string) => voidNoWhen called with string (token), it means token retrieved. When called with false as an argument, it means the response expired and the user needs to re-verify. When called with Error, it means an error occurred and the widget cannot continue (usually network disconnection)
Enterprise
Google ReCaptcha Enterprise is built on the existing reCAPTCHA API and it uses advanced risk analysis techniques to distinguish between humans and bots. In order to enable enterprise mode, you need to set the flag isEnterprise
in GoogleReCaptchaProvider
. Also in this mode you can pass specials actions
.
Examples
v2 checkbox
import { GoogleReCaptchaProvider, GoogleReCaptchaCheckbox } from 'react-google-recaptcha-ultimate'; const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); root.render( <GoogleReCaptchaProvider type="v2-checkbox" siteKey="Your recaptcha key" isEnterprise > <GoogleReCaptchaCheckbox action="Your action name" onChange={(token: string) => { console.log(token); }} /> </GoogleReCaptchaProvider> );
v3 or v2 invisible
import { GoogleReCaptchaProvider } from 'react-google-recaptcha-ultimate'; const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); root.render( <GoogleReCaptchaProvider type="Your type of recaptcha" siteKey="Your recaptcha key" isEnterprise > <App /> </GoogleReCaptchaProvider> );
API
GoogleReCaptchaProvider
react-google-recaptcha-ultimate
provides a GoogleReCaptchaProvider
provider component that should be used to wrap around your components.
GoogleReCaptchaProvider
โs responsibility is to load the necessary reCaptcha script and provide access to reCaptcha to the rest of your application.
Usually, your application only needs one provider. You should place it as high as possible in your React tree. Itโs to make sure you only have one instance of Google Recaptcha per page, and it doesnโt reload unnecessarily when your components re-rendered.
Same thing applied when you use this library with framework such as Next.js or React Router and only want to include the script on a single page. Try to make sure you only have one instance of the provider on a React tree and to place it as high (on the tree) as possible.
GoogleReCaptchaProvider for v3 and v2-invisible
All the props that can be passed in provider for v2-invisible and v3:
PropsTypeDefaultRequiredNotetypev3
or v2-invisible
YesYour recaptcha versionsiteKeyStringYesYour recaptcha key, get one from herelanguageStringNoOptional prop to support different languages that is supported by Google RecaptchaisEnterpriseBooleanNoWhen you enable to use the enterprise version, you must create new keys. These keys will replace any Site Keys you created in reCAPTCHA. Check the migration guide.onLoad() => voidNoCallback function to load reCAPTCHAonError() => voidNoCallback function to error reCAPTCHAhostrecaptcha.net
or google.com
NoLoad script from recaptcha.net
or google.com
scriptPropsObjectNoAll props used by <script>
tagexplicit.containerString or HTMLElementNoContainer ID where the recaptcha badge will be renderedexplicit.tabIndexNumber0NoThe tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier.explicit.inheritBooleanNoUse existing data-* attributes on the element if the corresponding parameter is not specified. The parameters will take precedence over the attributes.explicit.callback() => voidNoThe name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback.explicit.errorCallback() => voidNoThe name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry.explicit.expiredCallback() => voidNoThe name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.explicit.badgeinline
or bottomleft
or bottomright
or hiddenbottomright
NoReposition the reCAPTCHA badge.
GoogleReCaptchaProvider for v2-checkbox
All the props that can be passed in provider for v2-checkbox. We also recommend using the checkbox component rather than explicitly loading the recaptcha checkbox.
PropsTypeDefaultRequiredNotetypev2-checkbox
YesYour recaptcha versionsiteKeyStringYesYour recaptcha key, get one from herelanguageStringNoOptional prop to support different languages that is supported by Google RecaptchaisEnterpriseBooleanNoWhen you enable to use the enterprise version, you must create new keys. These keys will replace any Site Keys you created in reCAPTCHA. Check the migration guide.onLoad() => voidNoCallback function to load reCAPTCHAonError() => voidNoCallback function to error reCAPTCHAhostrecaptcha.net
or google.comgoogle.com
NoLoad script from recaptcha.net
or google.com
scriptPropsObjectNoAll props used by <script>
tagexplicit.containerString or HTMLElementNoContainer ID where the recaptcha badge will be renderedexplicit.tabIndexNumber0NoThe tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier.explicit.inheritBooleanNoUse existing data-* attributes on the element if the corresponding parameter is not specified. The parameters will take precedence over the attributes.explicit.callback() => voidNoThe name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback.explicit.errorCallback() => voidNoThe name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry.explicit.expiredCallback() => voidNoThe name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.explicit.actionStringNoAn action name is used to describe user-initiated events correspondingexplicit.themedark
or lightlight
NoThe color theme of the widget. Depends on type of reCaptchaexplicit.sizecompact
or normalnormal
NoThe size of the widget. Depends on type of reCaptcha
Checkbox component
PropsTypeDefaultRequired?NoteidStringNoId of componentactionStringNoAn action name is used to describe user-initiated events. More infoclassNameStringNoStyles for componentcontainerString or HTMLElementNoContainer ID where the recaptcha badge will be renderedcallback() => voidNoThe name of your callback function, executed when the user submits a successful response. The g-recaptcha-response token is passed to your callback.errorCallback() => voidNoThe name of your callback function, executed when reCAPTCHA encounters an error (usually network connectivity) and cannot continue until connectivity is restored. If you specify a function here, you are responsible for informing the user that they should retry.expiredCallback() => voidNoThe name of your callback function, executed when the reCAPTCHA response expires and the user needs to re-verify.languageStringNooptional prop to support different languages that is supported by Google Recaptcha. Seethemedark
or lightlight
NoThe color theme of the widget.sizecompact
or normalnormal
NoThe size of the widget.onChange(token: string) => voidNoWhen called with string (token), it means token retrieved. When called with false as an argument, it means the response expired and the user needs to re-verify. When called with Error, it means an error occurred and the widget cannot continue (usually network disconnection)
useGoogleReCaptcha hook
If you prefer a React Hook approach, you can choose to use the custom hook useGoogleReCaptcha
. We recommend using this hook for v2 invisible and v3 to trigger recaptcha execution.
The executeV3
and executeV2Invisible
function returned from the hook can be undefined when the recaptcha script has not been successfully loaded.
import { GoogleReCaptchaProvider, useGoogleReCaptcha } from 'react-google-recaptcha-ultimate'; const App = () => { const { executeV3 } = useGoogleReCaptcha(); // Create an event handler so you can call the verification on button click event or form submit const handleReCaptchaVerify = useCallback(async () => { if (!executeV3) { console.log('Execute recaptcha not available'); return; } const token = await executeV3(); }, [executeV3]); // You can use useEffect to trigger the verification as soon as the component being loaded useEffect(() => { handleReCaptchaVerify(); }, [handleReCaptchaVerify]); return <button onClick={handleReCaptchaVerify}>verify</button>; }; const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); root.render( <GoogleReCaptchaProvider siteKey="Your recaptcha key"> <App /> </GoogleReCaptchaProvider> );
withGoogleReCaptcha HOC
withGoogleReCaptcha
is a HOC (higher order component) that can be used to integrate reCaptcha validation with your component and trigger the validation programmatically. It injects the wrapped component with googleReCaptcha
object.
The object contains the executeV3
and executeV2Invisible
function that can be called to validate the user action.
You are recommended to use the custom hook useGoogleReCaptcha
over the HOC whenever you can. The HOC can be removed in future version.
import { GoogleReCaptchaProvider, withGoogleReCaptcha, WithGoogleReCaptchaParams } from 'react-google-recaptcha-ultimate'; const App = (props) => { // Create an event handler so you can call the verification on button click event or form submit const handleReCaptchaVerify = useCallback(async () => { if (!props.executeV3) { console.log('Execute recaptcha not available'); return; } const token = await props.executeV3(); }, [props.executeV3]); // You can use useEffect to trigger the verification as soon as the component being loaded useEffect(() => { handleReCaptchaVerify(); }, [handleReCaptchaVerify]); return <button onClick={handleReCaptchaVerify}>verify</button>; }; export const WithGoogleRecaptchaApp = withGoogleReCaptcha(App); const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement); root.render( <GoogleReCaptchaProvider siteKey="Your recaptcha key"> <WithGoogleRecaptchaApp /> </GoogleReCaptchaProvider> );
generateGoogleReCaptchaScriptSrc
The function generateGoogleReCaptchaScriptSrc
function may be needed for applications with ssr to get a link for the recaptcha script and load it before rendering the UI.
ParametersTypeRequiredNotehostrecaptcha.net
or google.com
NoLoad script from recaptcha.net
or google.com
isEnterpriseBooleanYesrenderStringYessiteKey of reCaptchahlStringNoProp to support different languages that is supported by Google Recaptchabadgeinline
or bottomleft
or bottomright
NoReposition the reCAPTCHA badge. Depends on type of reCaptcha. If not provide badge is hidden
generateGoogleReCaptchaHiddenBadgeStyles
The function generateGoogleReCaptchaHiddenBadgeStyles
function returns hidden styles for Google ReCaptcha badge.