Step-by-Step Setup for Google reCAPTCHA v3 in Next.js (Frontend) + CodeIgniter 4 (Backend) ๐Ÿ”น Step 1: Get reCAPTCHA v3 API Keys Go to https://www.google.com/recaptcha/admin/create Select reCAPTCHA v3 Register your domain (e.g. localhost, example.com) Youโ€™ll receive: Site Key (for frontend) Secret Key (for backend) ๐Ÿ”น Step 2: Add reCAPTCHA v3 to Register Form Install: bash Copy Edit npm install react-google-recaptcha-v3 Update frontend/app/register/page.tsx: tsx Copy Edit 'use client'; import React, { useEffect, useState } from 'react'; import { GoogleReCaptchaProvider, useGoogleReCaptcha } from 'react-google-recaptcha-v3'; import Form from 'react-bootstrap/Form'; import Button from 'react-bootstrap/Button'; import Alert from 'react-bootstrap/Alert'; import api from '@/lib/axios'; import Cookies from 'js-cookie'; import { useRouter } from 'next/navigation'; function RegisterFormInner() { const { executeRecaptcha } = useGoogleReCaptcha(); const [formData, setFormData] = useState({ name: '', email: '', password: '', confirmPassword: '' }); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); const router = useRouter(); const handleChange = (e) => setFormData({ ...formData, [e.target.name]: e.target.value }); const handleSubmit = async (e) => { e.preventDefault(); if (!executeRecaptcha) { setError('Recaptcha not ready.'); return; } if (formData.password !== formData.confirmPassword) { setError('Passwords do not match'); return; } const token = await executeRecaptcha('register'); try { setLoading(true); const res = await api.post('/register', { ...formData, captcha: token }); if (res.data.message === 'Verification email sent.') { router.push('/verify?email=' + formData.email); } } catch (err) { setError('Registration failed.'); } finally { setLoading(false); } }; return (
{error && {error}} Name Email Password Confirm Password
); } export default function RegisterPage() { return ( ); } ๐Ÿ” Replace "YOUR_SITE_KEY" with your Google reCAPTCHA v3 site key. ๐Ÿ”น Step 3: Backend Validation (CodeIgniter 4) In your AuthController.php: php Copy Edit private function validateCaptcha($token) { $secret = 'YOUR_SECRET_KEY'; $client = \Config\Services::curlrequest(); $response = $client->post('https://www.google.com/recaptcha/api/siteverify', [ 'form_params' => [ 'secret' => $secret, 'response' => $token, ] ]); $result = json_decode($response->getBody(), true); return isset($result['success']) && $result['success'] === true && $result['score'] >= 0.5; } ๐Ÿ” Replace 'YOUR_SECRET_KEY' with your Google reCAPTCHA secret key. ๐Ÿ”น Step 4: Use It in register() Method Before proceeding to save the pending user: php Copy Edit if (!$this->validateCaptcha($this->request->getVar('captcha'))) { return $this->fail('reCAPTCHA validation failed.', 422); } โœ… Done! You're Protected This will now: Run Googleโ€™s invisible bot detection Block suspicious/bot registrations Allow legit users through