How to Integrate Google reCAPTCHA v2

How to Integrate Google reCAPTCHA v2 with JavaScript

Protecting your forms from spam and bots is essential in modern web development. One of the most reliable ways to do that is by integrating Google reCAPTCHA. In this article, we’ll walk through a simple example using reCAPTCHA v2 and JavaScript.

🔐 What is reCAPTCHA?

Google reCAPTCHA is a free service that helps protect websites from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart.

We’ll use reCAPTCHA v2 (checkbox) in this example.

🛠️ Step-by-Step Integration

1. Get Your Site Key and Secret Key

Go to Google reCAPTCHA Admin Console, register your site, and select reCAPTCHA v2 → “I'm not a robot” checkbox.

  • Site Key: Used in the frontend
  • Secret Key: Used on the server for verification

2. HTML Form Example

<form id="contact-form" action="/submit" method="POST">
  <input type="text" name="name" placeholder="Your Name" required />
  <input type="email" name="email" placeholder="Your Email" required />

  <!-- Google reCAPTCHA widget -->
  <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>

  <button type="submit">Submit</button>
</form>

<!-- Load the Google reCAPTCHA script -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Replace YOUR_SITE_KEY with the one you got from Google.

3. Client-Side JavaScript Validation

document.getElementById("contact-form").addEventListener("submit", function (e) {
  const response = grecaptcha.getResponse();
  if (!response) {
    e.preventDefault();
    alert("Please complete the reCAPTCHA!");
  }
});

4. Server-Side Verification (Node.js Example)

const express = require('express');
const fetch = require('node-fetch');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

const SECRET_KEY = 'YOUR_SECRET_KEY';

app.post('/submit', async (req, res) => {
  const token = req.body['g-recaptcha-response'];
  const verificationURL = `https://www.google.com/recaptcha/api/siteverify?secret=${SECRET_KEY}&response=${token}`;

  const response = await fetch(verificationURL, { method: 'POST' });
  const data = await response.json();

  if (data.success) {
    res.send("Form submitted successfully.");
  } else {
    res.send("reCAPTCHA failed. Please try again.");
  }
});

Replace YOUR_SECRET_KEY with your actual secret key.

📌 Final Notes

  • reCAPTCHA is a simple yet effective way to protect your forms.
  • You can also explore reCAPTCHA v3 for invisible verification.
  • Always validate tokens on the server — client-side validation is not enough.

Comments

Popular posts from this blog

Do You Really Need Advanced Algorithms to Be a Great Developer in 2025?

Advanced Chrome Dino Game (HTML + JS + Sprites)

Boost Productivity Using AI and REST APIs