reCaptcha verification with EmailJS
Tags: react, tutorial, javascript
Published: 2020-07-29 17:07:18

*This blog is part of a series where I document rebuilding a website that relies on HTML, CSS and Bootstrap in React.js using the Next.js framework to improve performance, reduce costs and increase my workflow for future changes.*

The finished website: https://wallisconsultancy.co.uk
The source code: https://github.com/james-wallis/wallisconsultancy

## What is EmailJS

In the previous blog I introduced EmailJS, a service designed to send emails on behalf of websites with no backend server, and added to the Wallis Consultancy React.js application that is being built. 

## What is reCaptcha

> reCAPTCHA is a free service from Google that helps protect websites from spam and abuse. A “CAPTCHA” is a turing test to tell human and bots apart. It is easy for humans to solve, but hard for “bots” and other malicious software to figure out. By adding reCAPTCHA to a site, you can block automated software while helping your welcome users to enter with ease.

*[Source - support.google.com](https://support.google.com/recaptcha/answer/6080904?hl=en)*

EmailJS supports Google reCaptcha verification before sending an email and you can restrict it to not send an email if a reCaptcha code is not sent in the request object.

For more detailed information see the topic on the EmailJS website: [Adding CAPTCHA verification | EmailJS](https://www.emailjs.com/docs/user-guide/adding-captcha-verification/)

## Adding reCaptcha verification to EmailJS

An issue with the current wallisconsultancy.co.uk website is that the contact form can be easily abused by spam as it has no "human verification" method. 

Let's fix this issue by adding Google reCaptcha support to the website.

### Setting up reCaptcha

#### Creating a Google reCaptcha application
To setup EmailJS for my application we need to create a new application for Google reCaptcha.

To do this:
1. Navigate to https://www.google.com/recaptcha
1. Select `admin console` in the top right of the screen.
1. Select `register a new site`
1. Fill in the details
  * Make sure you select `reCAPTCHA v2` as EmailJS does not support `v3`
  * I gave `localhost` as the site URL so that I can use it in development. It’s recommended that you keep your development and production reCaptcha separate so I created another application with wallisconsultancy.co.uk as the site URL.

Once you've done this you will be given a `secret key`, keep this for the next step.

![Google reCaptcha sign up form](https://dev-to-uploads.s3.amazonaws.com/i/lam7wueuigi6aq2n3tpt.png)
*The Google reCaptcha sign up form*

#### Connecting Google reCaptcha and EmailJS
Next, we need to configure EmailJS to require a reCaptcha verification before sending an email by adding the secret key generated in the previous step to `CAPTCHA` tab of the [EmailJS template](https://dashboard.emailjs.com/admin/templates) section.

![reCaptcha setup on EmailJS](https://dev-to-uploads.s3.amazonaws.com/i/mgrum9oi5ns1amezolgy.jpg)
*Adding the reCaptcha secret key to the EmailJS template*

EmailJS is now configured so that it won't send emails without the reCaptcha code.

### Adding reCaptcha to React

Let's modify the React application to send the reCaptcha code to EmailJS in the request object.

I'm using the [react-google-recaptcha](https://www.npmjs.com/package/react-google-recaptcha) component to display the reCaptcha box. It supplies an `onChange` function that has the reCaptcha code as a parameter.

I modified the flow of the contact form like so:
1. User enters details
1. On `send` the page changes to show the reCaptcha instead of the contact form
1. User completes reCaptcha and the `onChange` function is called.
1. React component combines the form values and reCaptcha code into a single `params` that is sent to EmailJS.

Example usage:
```javascript
import emailjs from 'emailjs-com';
import ReCAPTCHA from 'react-google-recaptcha';

export default function MessageForm() {
  // This should be implemented as a form
  const [name, email, message] = ['name', 'email', 'message'];


  const sendEmail = (captchaValue) => {
    const params = {
      ...formState,
      'g-recaptcha-response': captchaValue,
    };

    emailjs.send(
      process.env.EMAIL_JS_SERVICE,
      process.env.EMAIL_JS_TEMPLATE,
      params,
      process.env.EMAIL_JS_USER,
    )
      .then(({ status }) => {
        console.log("EMAILJS SENT", status.code);
      }, (err) => {
        console.log("EMAILJS ERROR", err);
      });
  };

  return (
    <ReCAPTCHA
      sitekey={process.env.CAPTCHA_SITE_KEY}
      onChange={sendEmail}
    />
  );
}
```

*The complete code for the contact form on the Wallis Consultancy React application can be found [on Github](https://github.com/james-wallis/wallisconsultancy/blob/master/components/messageForm.js).*

That's it, we've now setup an EmailJS powered contact form with Google reCaptcha so that we can safely deploy our application without the form being abused by bots to spam to the email recipient.

## Round up
In this blog I’ve explored how reCaptcha can reduce the amount of spam sent from a contact form on a website and configured it to work with EmailJS.

In the next blog I will complete the development of wallisconsultancy.co.uk by using plugins to increase the performance of the website and the SEO score.