DEV Community

zainaboyedeji
zainaboyedeji

Posted on

How to integrate Google Recaptcha in your NextJS Project

How to Integrate Google reCAPTCHA in Your Next.js Project

Spam bots are everywhere. Whether you're building a contact form, login page, newsletter signup, or registration form, protecting your application from automated abuse is essential.

One of the easiest and most reliable ways to do this is by integrating Google reCAPTCHA into your Next.js application.

In this guide, you'll learn how to add Google reCAPTCHA v2 ("I'm not a robot") to a Next.js project, validate the token on the server, and follow best practices for keeping your application secure.


What is Google reCAPTCHA?

Google reCAPTCHA is a free security service that helps distinguish real users from bots.

There are three main versions:

  • reCAPTCHA v2 Checkbox – Displays the familiar "I'm not a robot" checkbox.
  • reCAPTCHA v2 Invisible – Runs in the background and only shows a challenge when needed.
  • reCAPTCHA v3 – Assigns users a score instead of showing a challenge.

For this tutorial, we'll use reCAPTCHA v2 Checkbox because it's straightforward to implement and works well for most forms.


Prerequisites

Before getting started, make sure you have:

  • Node.js installed
  • A Next.js project
  • A Google account

If you don't already have a project, create one:

npx create-next-app@latest recaptcha-demo
cd recaptcha-demo
Enter fullscreen mode Exit fullscreen mode

Step 1: Register Your Site

Visit the Google reCAPTCHA Admin Console:

https://www.google.com/recaptcha/admin/create

Create a new site by:

  • Giving it a label
  • Choosing reCAPTCHA v2
  • Selecting "I'm not a robot" Checkbox
  • Adding your domain

For local development, add:

localhost
Enter fullscreen mode Exit fullscreen mode

After registration, Google provides two keys:

  • Site Key
  • Secret Key

You'll use both in your application.


Step 2: Install the Package

Install the React wrapper.

npm install react-google-recaptcha
Enter fullscreen mode Exit fullscreen mode

or

yarn add react-google-recaptcha
Enter fullscreen mode Exit fullscreen mode

Step 3: Add Environment Variables

Create a .env.local file.

NEXT_PUBLIC_RECAPTCHA_SITE_KEY=your_site_key
RECAPTCHA_SECRET_KEY=your_secret_key
Enter fullscreen mode Exit fullscreen mode

Important

Variables prefixed with NEXT_PUBLIC_ are exposed to the browser. Your secret key should never use this prefix.

Restart your development server after adding environment variables.


Step 4: Create the Form

Create a simple contact form.

"use client";

import { useRef, useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";

export default function ContactForm() {
  const recaptchaRef = useRef<ReCAPTCHA>(null);

  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    const token = recaptchaRef.current?.getValue();

    if (!token) {
      alert("Please complete the reCAPTCHA");
      return;
    }

    setLoading(true);

    const response = await fetch("/api/verify", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ token }),
    });

    const data = await response.json();

    if (data.success) {
      alert("Verification successful!");
      recaptchaRef.current?.reset();
    } else {
      alert("Verification failed.");
    }

    setLoading(false);
  }

  return (
    <form onSubmit={handleSubmit}>
      <ReCAPTCHA
        ref={recaptchaRef}
        sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY!}
      />

      <button disabled={loading}>
        {loading ? "Verifying..." : "Submit"}
      </button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

At this point, the checkbox will appear on your page.

However, this alone is not secure.

Anyone can bypass client-side validation.

That's why the token must be verified on the server.


Step 5: Verify the Token on the Server

Create:

app/api/verify/route.ts
Enter fullscreen mode Exit fullscreen mode
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const { token } = await req.json();

  const secret = process.env.RECAPTCHA_SECRET_KEY;

  const response = await fetch(
    "https://www.google.com/recaptcha/api/siteverify",
    {
      method: "POST",
      headers: {
        "Content-Type":
          "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams({
        secret: secret!,
        response: token,
      }),
    }
  );

  const data = await response.json();

  return NextResponse.json({
    success: data.success,
  });
}
Enter fullscreen mode Exit fullscreen mode

When a user submits the form:

  1. The browser sends the token to your API.
  2. Your API sends it to Google.
  3. Google verifies the token.
  4. Your server decides whether the request is valid.

This prevents attackers from simply generating fake requests.


Step 6: Test Your Integration

Run the development server.

npm run dev
Enter fullscreen mode Exit fullscreen mode

Visit your page.

You should see the familiar checkbox:

☑ I'm not a robot
Enter fullscreen mode Exit fullscreen mode

After checking it and submitting the form, your API should return:

{
  "success": true
}
Enter fullscreen mode Exit fullscreen mode

Understanding the Verification Response

Google returns more than just a success value.

Example:

{
  "success": true,
  "challenge_ts": "...",
  "hostname": "localhost",
  "score": 0.9
}
Enter fullscreen mode Exit fullscreen mode

For v2, the most important field is:

success
Enter fullscreen mode Exit fullscreen mode

For v3, you'll also evaluate:

  • score
  • action

Common Errors

Invalid site key

Make sure:

  • Your site key matches your domain.
  • You're using the correct environment variable.

Invalid secret key

Double-check your server environment variables.

Never expose the secret key in the browser.


Timeout

reCAPTCHA tokens expire after about two minutes.

If a user waits too long before submitting the form, request a new token.


Domain mismatch

Google only accepts requests from registered domains.

Remember to add:

localhost
Enter fullscreen mode Exit fullscreen mode

during development.


Best Practices

To get the most out of reCAPTCHA:

  • Always verify tokens on the server.
  • Keep your secret key private.
  • Reset the widget after successful submission.
  • Combine reCAPTCHA with server-side validation.
  • Add rate limiting to sensitive endpoints.
  • Log failed verification attempts for monitoring.

Should You Use reCAPTCHA v2 or v3?

Feature v2 v3
Checkbox
User interaction Required None
Bot score
Easier to implement ⚠️
Better user experience

If you're building a simple contact form or registration page, reCAPTCHA v2 is often the easiest choice. If you want a frictionless experience and are comfortable working with risk scores, reCAPTCHA v3 is a better long-term option.


Conclusion

Adding Google reCAPTCHA to a Next.js application is a simple but effective way to reduce spam and automated abuse. While rendering the widget on the client is straightforward, the real security comes from verifying the generated token on your server before processing any user request.

By following the steps in this guide, you've learned how to:

  • Register a site with Google reCAPTCHA.
  • Add the reCAPTCHA widget to a Next.js form.
  • Store your site and secret keys securely using environment variables.
  • Verify the reCAPTCHA token in a Next.js API route.
  • Apply best practices to keep your forms secure.

With these measures in place, your forms are better protected against bots while still providing a smooth experience for legitimate users.

Top comments (0)