How to add reCAPTCHA validation to your MERN stack app

  • Go to https://www.google.com/recaptcha/admin/create to register a new site.
  • Choose Challenge v2 from the reCAPTCHA type section
  • Add localhost as the domain of your site. Do not include the port of your application, e.g. localhost:8080 etc.

After registering the new site you will get your secret key and site. We will need the site key on the frontend and the secret key on the backend for verification.

The process:

  • User completes the I am not a robot challenge.
  • On the successful completion of the challenge a reCAPTCHA Token is generated on the frontend and sent to the backend for verification.
  • The Backend uses the SECRET_KEY and the reCAPTCHA Token to send a POST request to the following url:

·         `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${recaptchaToken}`

If the response object’s success property is true then the verification is successful.

Here is the frontend and the backend code:

Frontend: 

import React, { useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';

const App = () => {
  const [recaptchaToken, setRecaptchaToken] = useState(null);

  const handleRecaptchaChange = (value) => {
    setRecaptchaToken(value);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

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

    const response = await fetch('http://localhost:8080/captcha/verify', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ recaptchaToken }),
    });

    const data = await response.json();

    if (data.message === 'reCAPTCHA Verified successfully Bro!') {
      // Proceed with form submission
      alert('Form submitted successfully!');
    } else {
      alert('reCAPTCHA verification failed!');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <ReCAPTCHA
        sitekey="6LcF-iYrAAAAAHgPWXuptbekZQouFc-qAgSduNWD"  // Replace with your Site Key
        onChange={handleRecaptchaChange}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default App;

Backend: 


app.post("/captcha/verify", async (req, res) => {
  console.log(process.env.RECAPTCHA_SECRET_KEY);
  const { recaptchaToken } = req.body;

  try {
    const response = await fetch(
      `https://www.google.com/recaptcha/api/siteverify?        secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${recaptchaToken}`,
      {
        method: 'POST', // Use POST method
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded', // Set appropriate headers
        },
      }
    );

    const data = await response.json();
    console.log("data: ", data)

    if (data.success) {
      return res.status(200).json({ message: "reCAPTCHA Verified successfully Bro!" });
    } else {
      return res.status(400).json({ message: "reCAPTCHA Failed" });
    }
  } catch (error) {
    console.error("Error verifying reCAPTCHA", error);
    return res.status(500).json({ message: "Server error" });
  }
});

Thanks!

Comments

Popular posts from this blog

Razorpay Payment Integration (MERN STACK)

Google OAuth implementation in MERN stack