Google reCAPTCHA Node.js tutorial

We have already covered Google recaptcha using PHP and in this tutorial we will cover Google reCAPTCHA form using Ajax and Node.js as backend.

LIVE DEMO DOWNLOAD

Here is the steps we’ll take to develop this program.

  • Submit form using Ajax.
  • Get the google response key in Node.js Server.
  • Reverify the key and give the response to UI.

To submit form using Ajax we will use jQuery.form library. For Server we will use Express and for HTTP calls we will use request.

Related learning : Basic HTTP calls using Request

Let’s do it.

Our Package.json

Create new directory and generate package.json file in it. Use npm init command to generate the package.json file, its the best practice. Here is my package.json file for reference.

package.json
{
  "name": "google-racapcha-node",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/codeforgeek/google-racapcha-node.git"
  },
  "author": "Shahid shaikh",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/codeforgeek/google-racapcha-node/issues"
  },
  "homepage": "https://github.com/codeforgeek/google-racapcha-node#readme"
}

Let’s install required dependencies.

npm i --save express request body-parser

Like i mentioned we’ll use express as web framework, request for HTTP call, body-parser to extract the POST variable in Express.

Related learning : Handle GET and POST data in Express.Js

We will use following libraries in user interface :

  • jquery
  • jquery.form

We will use CDN as a source for both libraries.

Register your site at Google reCAPTCHA

Register your web site at Google recaptcha platform to get keys needed to code the form. Click here to go to Google reCAPTCHA website.

After signing in, add your website details.

Google recaptcha

After registration Google will provide you following :

  • Site key
  • Secret key

Creating Google reCAPTCHA form in HTML

Here is our HTML code to generate simple form with Google reCAPTCHA.

index.html
<html>
  <head>
    <title>Google recapcha demo - Codeforgeek</title>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id="comment_form" action='/submit' method="post">
      <input type="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <div class="g-recaptcha" data-sitekey="--paste your site key here--"></div><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
    </form>
  </body>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
  <script>
   // Will put our custom code here.
  </script>
</html>

We have created simple form with action as /submit. This implies that once user submit the form, browser will POST the form data into url+’/submit’ location. So if you are running the app at localhost:3000 then browser will submit the form data at localhost:3000/submit. We need to have our API to accept the connection and POST data in that url.

Add your site-key provided by Google into Google recaptcha div.

Here is our JavaScript code to perform Ajax form submit.

  <script>
    $(document).ready(function() {
      $('#comment_form').submit(function() {
        $(this).ajaxSubmit({
          error: function(xhr) {
            status('Error: ' + xhr.status);
          },
         success: function(response) {
          console.log(response);
         }
        });
        //Very important line, it disable the page refresh.
        return false;
      });
    });
  </script>

Add this code right after loading the scripts in HTML page.

Nodejs server

We have our form ready, let’s code our Server file and expose /submit API we mentioned above.

Related learning : Build a RESTful API using Node.js

app.js
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));

app.get('/',function(req,res) {
  // Sending our HTML file to browser.
  res.sendFile(__dirname + '/index.html');
});

app.post('/submit',function(req,res){
  // g-recaptcha-response is the key that browser will generate upon form submit.
  // if its blank or null means user has not selected the captcha, so return the error.
  if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {
    return res.json({"responseCode" : 1,"responseDesc" : "Please select captcha"});
  }
  // Put your secret key here.
  var secretKey = "--paste your secret key here--";
  // req.connection.remoteAddress will provide IP address of connected user.
  var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress;
  // Hitting GET request to the URL, Google will respond with success or error scenario.
  request(verificationUrl,function(error,response,body) {
    body = JSON.parse(body);
    // Success will be true or false depending upon captcha validation.
    if(body.success !== undefined && !body.success) {
      return res.json({"responseCode" : 1,"responseDesc" : "Failed captcha verification"});
    }
    res.json({"responseCode" : 0,"responseDesc" : "Sucess"});
  });
});

// This will handle 404 requests.
app.use("*",function(req,res) {
  res.status(404).send("404");
})

// lifting the app on port 3000.
app.listen(3000);

Running the app

To run the application, switch to project folder and run the Node app using

node app.js

command.

Go to localhost:3000 to view the app.

Filling up correct captcha

Fill up the form and submit the captcha.

Google recaptcha form

You should receive following message in alert box.

Google recaptcha form submit

Upon unselecting the Google recaptcha, you will receive following error.

Google recaptcha form

I have reproduce bad captcha or spam form validation too by hardcoding the success variable in the back-end code.Let me know in comments if you want that piece of code too.

Conclusion

Google reCAPTCHA is no doubt the most innovative captcha available for free. We have covered implementing this Using PHP in this tutorial and now with Node.js. Feel free to share and point out any mistakes if you found any.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126