How to setup Google reCAPTCHA in a ReactJS app?

Google’s reCAPTCHA is an industry standard when it comes to fighting bots. Integrating it in a regular web app has almost become a no-brainer, thanks to plugins available on almost every platform to do the job. With this expectation, I started integrating it in my latest app built on ReactJS but encountered many roadblocks. Without going into details, I’m sharing here fastest recipe for integrating it with your ReactJS app.

1. Sign up for reCAPTCHA

Follow this link and get your app registered with Google. When you’ve registered, you should a pair of keys, a Site Key and a Secret Key.

Screen Shot 2016-03-25 at 2.47.36 PM

2. Frontend Integration

There’s a plethora of reCAPTCHA plugins available for ReactJS at NPM, but the one I found working and easy to use is react-google-recaptcha. As mentioned on the plugin page, integrating it in your code is pretty simple.


// This is the only dependency you need to include in your project.
import ReCAPTCHA from 'react-google-recaptcha';

// Include reCAPTCHA component wherever you want to include it
<ReCAPTCHA
    ref="recaptcha"
    sitekey="Your client site key"
    onChange={this.onChange.bind(this)}/>

// Make sure you've a callback function defined in your parent component
// that you supply in the onChange attribute of ReCAPTCHA component.
// This callback will get invoked after user has passed the reCAPTCHA
// challenge. The callback will receive a response string as an argument.
// Be sure to store this string somewhere because you'll need to send it
// to server when user submits the form.
onChange(response) {
    this.setState({
        'g-recaptcha-response': response
    });
}

3. Backend Integration

At your backend server, the controller that receives the form submission request needs to send an HTTP request to Google to verify if the request from a human being and not from a bot. Below is a verification function in context of NodeJS/ExpressJS stack.

// "request" library has far friendlier API than Node's default 'http' library
import request from 'request';

// yes it's a weird func name, can you think of a better name?
function verifyHumanity(req) {
  // Q is a nice little promise library I'm using in my project
  const d = Q.defer();
  const recaptchaResponse = req.body['g-recaptcha-response'];

  request.post('https://www.google.com/recaptcha/api/siteverify', {
    form: {
      secret: RECAPTCHA_SECRET_KEY,
      response: recaptchaResponse,
      remoteip: req.connection.remoteAddress
    }
  }, (err, httpResponse, body)=>{
    if (err) {
      d.reject(new Error(err));
    } else {
      const r = JSON.parse(body);
      if (r.success) {
        d.resolve(r.success);
      } else {
        d.reject(new Error());
      }
    }
  });

  return d.promise;
}

// here's how to use the function in your controller
router.post('/my-form', (req, res) => {
    verifyHumanity(req)
        .then(()=>{
            // success
        })
        .catch(()=>{
            // failure
            res.status(400);
            res.send({
                error: 'Please verify that you\'re a human'
            });
        });
});

That should be it. Did this blogpost help you in anyway? Do let me know, I’d love to hear.

Published by

Umar Ashfaq

Umar Ashfaq is a full-stack web developer. His core strength is building neat UIs with JavaScript on web but he also enjoys server side Java, NodeJS and Objective C. Follow him on twitter @umarashfaq87

Leave a Reply

Your email address will not be published. Required fields are marked *