This repository provides a practical example of how to integrate Google reCAPTCHA v3 into a Next.js project using App Router and Server Actions.
- The contact form is rendered on the client.
- When submitted, a reCAPTCHA token is generated using
grecaptcha.execute
. - The token is appended to
FormData
and sent to a Server Action. - The Server Action verifies the token via the Google API.
- If valid, the server processes the request (e.g., sends an email).
Create a .env.local
file with the following keys:
NEXT_PUBLIC_GOOGLE_RECAPTCHA_SITE_KEY=your_site_key
GOOGLE_RECAPTCHA_SECRET_KEY=your_secret_key
- Go to the Google reCAPTCHA Admin Console
- Register a new site
- Choose reCAPTCHA v3
- Add your domain (e.g., example.com)
- Copy the Site Key and Secret Key
- Paste them into the .env.local file as shown above
⚠️ Important: reCAPTCHA validation may not work properly on localhost. For accurate validation, deploy your project to a public domain like Vercel or Netlify and register that domain in reCAPTCHA settings.
In the src/actions/send-contact-action.ts
file, there's a section where the email sending logic should be added after reCAPTCHA validation. This section is marked with the following comment:
// ✅ Replace this part with sending email with the service of your choice (e.g. Resend, SendGrid)
Replace that line with the integration code for your preferred email service provider, such as:
Don't forget to add your preferred email service provider API key in the .env.local file.