Implement Recaptcha V3 in Laravel 12 + Inertia + React + TypeScript

June 8, 2025

Install npm package


npm install react-google-recaptcha-v3

 

add envs

 

.env.example

GOOGLE_RECAPTCHA_SITE_KEY=
GOOGLE_RECAPTCHA_SECRET_KEY=

 

Return recaptchaSiteKey by default:

 

app/Http/Middleware/HandleInertiaRequests.php

'recaptchaSiteKey' => config('services.recaptcha.site_key'),

 

Add Laravel Rule:

 

app/Rules/Recaptcha.php

public function validate(string $attribute, mixed $value, Closure $fail): void
{
   $response = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
       'secret' => config('services.recaptcha.secret_key'),
       'response' => $value,
   ]);
   $json = $response->json();
   if (
       !$json['success'] ||
       !isset($json['score']) ||
       $json['score'] < 0.5
   ) {
       $fail('Invalid reCAPTCHA.');
   }
}

 

Add rule to your form:

 

'g-recaptcha-response' => ['required', 'string', new Recaptcha],

 

Add recaptcha to you services config file:

 

config/services.php

'recaptcha' => [
   'site_key' => env('GOOGLE_RECAPTCHA_SITE_KEY'),
   'secret_key' => env('GOOGLE_RECAPTCHA_SECRET_KEY'),
],

 

Add Recaptcha Provider to React app:

 

resources/js/app.tsx

import { GoogleReCaptchaProvider } from 'react-google-recaptcha-v3';

root.render(
   <GoogleReCaptchaProvider reCaptchaKey={props.initialPage.props.recaptchaSiteKey}>
       <App {...props} />
   </GoogleReCaptchaProvider>,
);

 

In File where your form is at:

 

import { useGoogleReCaptcha } from 'react-google-recaptcha-v3';

…

const { executeRecaptcha } = useGoogleReCaptcha();

…

const submit: FormEventHandler = async (e) => {
   e.preventDefault();
   const token = await executeRecaptcha('submit');
   data['g-recaptcha-response'] = token;
   post(route('login'), {
       onSuccess: () => reset('password'),
   });
};

And display the error
{errors['g-recaptcha-response'] && (
   <InputError message="Something went wrong" />
)}