DEV Community

Cover image for Stop Bots Before They Ruin Your App — Add Google reCAPTCHA v3 to Next.js
Muhammad Hamid Raza
Muhammad Hamid Raza

Posted on

Stop Bots Before They Ruin Your App — Add Google reCAPTCHA v3 to Next.js

Is Your Next.js App Secretly Inviting Bots to the Party? šŸ¤–

Picture this: you just shipped a shiny new file upload feature. Users love it. Then at 3 AM, a bot floods your server with 10,000 fake uploads, your storage bill explodes, and your inbox looks like a spam museum.

Yeah. Not fun.

That's exactly why Google reCAPTCHA v3 exists — and if you're building with Next.js, adding it is honestly way easier than you'd expect. Think of it like hiring a silent bouncer for your app. Users never see anything, never have to click "I'm not a robot," and the bot doesn't get in.

In this guide, you'll learn how to protect your Next.js app with reCAPTCHA v3 step by step — even if you've never touched it before.


What Is Google reCAPTCHA v3?

Let's clear something up first. There are different versions of reCAPTCHA.

  • v2 is the annoying one where you click crosswalks in blurry photos for 3 minutes.
  • v3 works silently in the background. No puzzles, no checkboxes, no frustration.

reCAPTCHA v3 watches how users interact with your site and assigns them a score from 0.0 to 1.0. A score close to 1.0 means "yep, this is a human." A score near 0.0 means "this is definitely a bot — block it."

You decide the threshold. Set it to 0.5 and anything below gets blocked. It's like a credit score for your users, except the only thing at stake is whether a bot can exploit your app.

Real-world example: imagine you have a contact form. reCAPTCHA v3 silently runs in the background when a user opens the page. By the time they hit submit, Google already has a verdict ready.


Why This Matters for Your Next.js App

Security isn't something you add after you get hacked. It's something you build in from the start.

Here's why reCAPTCHA v3 is worth caring about in a Next.js project specifically:

Next.js apps often expose API routes — and those routes are public by default. Without any protection, a bot can hit your /api/upload or /api/contact endpoint as many times as it wants. Rate limiting helps, but it's not enough on its own.

reCAPTCHA v3 adds an invisible verification layer. Before any sensitive action happens — file upload, form submission, login attempt — you verify the user is human. Simple, effective, and Google does the heavy lifting.

Have you ever seen a company's database leak because of automated injection attacks? A lot of those start with unprotected API endpoints. Don't let your app be that story.


Benefits with Real-Life Examples

  • No friction for real users — Unlike v2, users don't have to solve anything. Your UX stays clean and fast. Real users don't even know it's there.

  • Automatic bot blocking — Bots hitting your upload endpoint? They'll get a score of 0.1 and get blocked before they can do any damage. Your server stays healthy.

  • Works with any action — You can trigger reCAPTCHA verification on login, form submit, file upload, or literally any user action. It's flexible.

  • Free for most apps — Google gives you 1 million verifications per month for free. Unless you're running a massive platform, you'll never hit that limit.

  • Works seamlessly with Next.js App Router — The setup works with both the Pages Router and the modern App Router. You create a server-side API route to verify tokens, and you're done.


Comparison: reCAPTCHA v2 vs reCAPTCHA v3

Feature reCAPTCHA v2 reCAPTCHA v3
User interaction Click checkboxes, solve puzzles None — completely invisible
UX impact Annoying and disruptive Zero friction
Score system Pass/fail only 0.0 to 1.0 score
Flexibility Limited High — score threshold is customizable
Bot detection accuracy Good Better — uses behavioral analysis
Setup complexity Simple Slightly more setup, worth it

The verdict? If you care about user experience AND security, v3 is the clear winner. v2 is the CAPTCHA that makes your users want to close the tab.


Best Tips / Do's and Don'ts

āœ… Do's:

  • Do add your domain in Google Admin Console. This is the #1 reason setups fail. Add localhost for development and your actual domain for production.
  • Do keep the Secret Key server-side only. Never expose RECAPTCHA_SECRET_KEY in frontend code. It goes in .env.local and only gets used in your API route.
  • Do use the NEXT_PUBLIC_ prefix for the Site Key. The Site Key is safe to expose client-side — that's what the prefix is for.
  • Do restart your dev server after adding environment variables. Next.js doesn't hot-reload .env.local changes.
  • Do adjust the score threshold based on your use case. File uploads might warrant 0.7 for stricter filtering. A newsletter signup might be fine at 0.5.

āŒ Don'ts:

  • Don't skip the RecaptchaWrapper component. The useGoogleReCaptcha hook only works inside the GoogleReCaptchaProvider. Forgetting this is a classic mistake.
  • Don't verify the token on the client side. The token must be sent to your backend, which then calls Google's API. Client-side verification defeats the entire purpose.
  • Don't hardcode your keys. Seriously. Not even in a "temporary" commit. Use environment variables, always.
  • Don't block users just because the score is slightly below 0.5. Sometimes legitimate users score a bit low. Consider showing an alternative (like a simple email verification) instead of a hard block for borderline scores.

Common Mistakes People Make

1. Forgetting to add localhost to allowed domains
This is the most common first-time mistake. You set everything up, run npm run dev, and get verification errors. Head to the Google reCAPTCHA admin console and add localhost to your allowed domains list.

2. Exposing the Secret Key in frontend code
The Site Key (NEXT_PUBLIC_RECAPTCHA_SITE_KEY) is meant to be public. The Secret Key (RECAPTCHA_SECRET_KEY) is not. If you accidentally use the wrong variable naming or paste the secret key in a client component, your security is completely broken.

3. Not wrapping the right component
The useGoogleReCaptcha hook must be used inside a component that is a child of GoogleReCaptchaProvider. If you try to use the hook outside the provider, you'll get a runtime error. Wrap the right parent component — not just a random layout.

4. Ignoring the reCAPTCHA badge
By default, the reCAPTCHA v3 badge appears in the bottom-right corner of your site. Hiding it violates Google's terms of service. If it clashes with your design, you can hide the badge with CSS but must include a text disclosure on your page instead.

5. Not handling token expiry
reCAPTCHA tokens expire after 2 minutes. If your user sits on a page for a while before submitting a form, the token will be stale. Always execute reCAPTCHA right before the protected action, not when the page loads.


You're One Step Away from a Safer App šŸš€

Adding reCAPTCHA v3 to your Next.js app is honestly one of those things that feels complex at first but turns out to be pretty straightforward once you understand the pieces. It's as easy as unlocking your phone once you know the password — the first time is the only hard part.

Here's a quick recap of what you need to do:

  1. Get your Site Key and Secret Key from Google
  2. Store them in .env.local
  3. Install react-google-recaptcha-v3
  4. Create a verification API route in Next.js
  5. Wrap your component with RecaptchaWrapper
  6. Call executeRecaptcha before any sensitive action

That's it. Your app now has an invisible security layer that filters out bots without annoying your real users.

Want to level up your Next.js knowledge even more? Explore more practical developer guides, tutorials, and tips at hamidrazadev.com — written by a developer, for developers. No fluff, just real stuff. šŸ’Ŗ

Top comments (0)