Setting up Google reCAPTCHA in a ReactJS app

Posted on Posted in Blog

hero-recaptcha-demo

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 get a pair of keys, a Site Key and a Secret Key.

screen-shot-2016-03-25-at-2-47-36-pm-768x143

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.

1// This is the only dependency you need to include in your project.
2import ReCAPTCHA from 'react-google-recaptcha';
3
4// Include reCAPTCHA component wherever you want to include it
5<ReCAPTCHA
6    ref="recaptcha"
7    sitekey="Your client site key"
8    onChange={this.onChange.bind(this)}/>
9    
10// Make sure you've a callback function defined in your parent component
11// that you supply in the onChange attribute of ReCAPTCHA component.
12// This callback will get invoked after user has passed the reCAPTCHA
13// challenge. The callback will receive a response string as an argument.
14// Be sure to store this string somewhere because you'll need to send it
15// to server when user submits the form.
16onChange(response) {
17this.setState({
18'g-recaptcha-response': response
19});
20}

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.

1// "request" library has far friendlier API than Node's default 'http' library
2import request from 'request';
3 
4// yes it's a weird func name, can you think of a better name?
5function verifyHumanity(req) {
6  // Q is a nice little promise library I'm using in my project
7  const d = Q.defer();
8  const recaptchaResponse = req.body['g-recaptcha-response'];
9 
10  request.post('https://www.google.com/recaptcha/api/siteverify', {
11    form: {
12      secret: RECAPTCHA_SECRET_KEY,
13      response: recaptchaResponse,
14      remoteip: req.connection.remoteAddress
15    }
16  }, (err, httpResponse, body)=>{
17    if(err) {
18      d.reject(new Error(err));
19    } else {
20      const r = JSON.parse(body);
21      if (r.success) {
22        d.resolve(r.success);
23      } else {
24        d.reject(new Error());
25      }
26    }
27  });
28
29  return d.promise;
30}
31 
32// here's how to use the function in your controller
33router.post('/my-form', (req, res) => {
34    verifyHumanity(req)
35        .then(()=>{
36            // success
37        })
38        .catch(()=>{
39            // failure
40            res.status(400);
41            res.send({
42                error: 'Please verify that you\'re a human'
43            });
44        });
45});

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

Previously published here.

One thought on “Setting up Google reCAPTCHA in a ReactJS app

  1. Captcha fails to render on first render() and also shows console warning:

    ReCAPTCHA couldn’t find user-provided function: onloadcallback

Leave a Reply

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