Adding reCAPTCHA in MERN Application
Tags: webdev, security, mern, javascript
Published: 2023-11-01 03:50:00


Adding reCAPTCHA to your MERN website involves several steps. reCAPTCHA is a Google service used to protect your website from spam and abuse.

**Get reCAPTCHA API Keys:**

- Go to the reCAPTCHA website and sign in with your Google account.

![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lf46x3dvvwqg2opswovg.png)

- Create a new site by clicking on “Admin Console” and then “Create a site”.

- Choose the “reCAPTCHA v2” type (I’m assuming you want the checkbox “I’m not a robot” version) and select “I’m not a robot” Checkbox.


![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w5gwkd3vubf17t6ha25c.png)

Add your domain(s) to the list of allowed domains. This is important for security.


![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7baj1anutd484ehc2awb.png)

note: you can also add localhost here

- Accept the reCAPTCHA Terms of Service and click “Submit”.

- After creating the site, you’ll get a Site Key and a Secret Key. You will use the Site Key on the client-side and secret key on the backend.



![example pic](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wqbtgxbyanhlwvoodd4q.png)

**Integrate reCAPTCHA in your React application:**

In your HTML `<head>`, include the reCAPTCHA script.

```
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
```

Install the `react-google-recaptcha` package to use the widget:

```
npm install react-google-recaptcha
```

In your React component where you have your form, add the reCAPTCHA widget using the `react-google-recaptcha` library or by manually rendering the widget.

```
import ReCAPTCHA from "react-google-recaptcha";

function MyFormComponent() {
  const onRecaptchaChange = (value) => {
    console.log(value)
    if(value){
       // send to backend for validation
    }
  };

  return (
    <form>
      // Your form fields
      <ReCAPTCHA
        sitekey="YOUR_SITE_KEY"
        onChange={onRecaptchaChange}
      />
      <button type="submit">Submit</button>
    </form>
  );
}
```

When captcha check is correct you will receive the token in the onRecaptchaChange function, Value will be null if the user hasn’t solved the reCAPTCHA, then send the backend for more security.
It is better to add backend validation too.

**Verify reCAPTCHA Token on the Server:**

- In your server, you should verify the reCAPTCHA response sent from the client. You can use the `axios` library to send a POST request to Google's reCAPTCHA verification endpoint.

First, install `axios `if you haven't already:

```
npm install axios
```
Then, in your server route:

```
const axios = require('axios');

async function verifyRecaptcha(recaptchaResponse) {
  try {
    const response = await axios.post(
      "https://www.google.com/recaptcha/api/siteverify",
      null,
      {
        params: {
          secret: "YOUR_SECRET_KEY",
          response: recaptchaResponse,
        },
      }
    );

    return response.data.success;
  } catch (error) {
    console.error("Error verifying reCAPTCHA:", error);
    return false;
  }
}

app.post('/submit', async (req, res) => {
  const { recaptchaToken } = req.body; 

  try {
    const isRecaptchaValid = await verifyRecaptcha(recaptchaToken);

  if (!isRecaptchaValid) {
    return res.status(400).json({ error: "reCAPTCHA verification failed" });
  }else{
    //Add your success response here
}
  } catch (error) {
    console.log(error)
  }
});
```

In conclusion, integrating reCAPTCHA into your MERN website is a crucial step to enhance security and protect your forms from spam and abuse. The process involves adding reCAPTCHA to both the client-side (React) and server-side (Node.js/Express) of your application. On the client-side, you obtain reCAPTCHA API keys, integrate the reCAPTCHA widget into your React forms using a library like `react-google-recaptcha`, and handle the user's response. On the server-side, you verify the reCAPTCHA token sent from the client by making a POST request to Google's reCAPTCHA verification endpoint using the `axios` library, and based on the verification result, you decide whether to process the form data or show an error message. By following these steps, you can significantly enhance the security of your MERN application and protect it from unwanted spam and abuse.