Next.js
Integrate the react google recaptcha with Next.js
Install the required package using your preferred package manager:
npm install @google-recaptcha/react
pnpm add @google-recaptcha/react
yarn add @google-recaptcha/react
bun add @google-recaptcha/react
This package provides React components and hooks for client-side reCAPTCHA integration.
For Next.js applications, you have few options for reCAPTCHA integration, but first you need create client provider component
"use client";
import type { ComponentProps } from "react";
import { GoogleReCaptchaProvider as _GoogleReCaptchaProvider } from "@google-recaptcha/react";
export type ReCaptchaProviderProps = ComponentProps<typeof _GoogleReCaptchaProvider>;
export const GoogleReCaptchaProvider = (props) => (
<_GoogleReCaptchaProvider {...props} />
);
Add provider to your layout component
import type { ReactNode } from "react";
import { GoogleReCaptchaProvider } from "./google-recaptcha-provider";
interface RootLayoutProps {
children: ReactNode;
}
const RootLayout = ({ children }: RootLayoutProps) => (
<html lang="en">
<body>
<main>
<GoogleReCaptchaProvider type="v3" siteKey="your_site_key">
{children}
</GoogleReCaptchaProvider>
</main>
</body>
</html>
);
export default RootLayout;
const googleReCaptcha = useGoogleReCaptcha();
const onSubmit = async () => {
const token = await googleReCaptcha.executeV3();
...
}
Optimize script loading
You can optimize performance by pre-loading the reCAPTCHA script using Next.js Script component combined with the core utility function. The GoogleReCaptchaProvider
automatically detects if the reCAPTCHA script is already loaded and will not add a duplicate script tag
import type { ReactNode } from 'react';
import Script from 'next/script';
import { GoogleReCaptchaProvider } from './google-recaptcha-provider';
interface RootLayoutProps {
children: ReactNode;
}
const RootLayout = ({ children }: RootLayoutProps) => {
const scriptSrc = generateGoogleReCaptchaScriptSrc({
isEnterprise: false,
render: 'your_site_key',
hl: 'en'
});
return (
<html lang='en'>
<head>
<Script src={scriptSrc} strategy='afterInteractive' />
</head>
<body>
<main>
<GoogleReCaptchaProvider type='v3' siteKey='your_site_key'>
{children}
</GoogleReCaptchaProvider>
</main>
</body>
</html>
);
};
export default RootLayout;