Google Recaptcha In Node.js Tutorial From Scratch

Google Recaptcha In Node.js Tutorial From Scratch topic we will cover today. Google Recaptcha is a kind of security through you can prevent the computer bots, spammers to enter your website. We are using Node.js and express framework to build a Google Recaptcha Security. So let us get started.

Step 1: Create a project and configure it.

Create your project folder and inside type following command in your terminal.

npm init

We are initializing the package.json file.

{
  "name": "googlerecaptcha",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon server"
  },
  "author": "Krunal Lathiya",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.7",
    "express": "^4.15.4"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
}

We have written three packages as dependencies, so go to your terminal and type the command.

npm install

Now, create one file in a root called server.js and also create one folder name public in the root.


// Server.js

var express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser');

var app = express();
   app.set('view engine', 'ejs');
   app.use(express.static('public'));
   app.use(bodyParser.urlencoded({extended: true}));
   app.use(bodyParser.json());
   var port = 3000;

app.listen(port, function(){
    console.log('Server is running at port: ',port);
});

Here, I have required all the modules and used express in our application. Static files are served from public folder and use body-parser middleware to extract the data from Post request. We have used ejs as a templating engine for our application.

Step 2: Set up the views for our project. 

Create one folder in root called views. In that folder, create one ejs file called index.ejs. We are using Bootstrap CSS Framework for this application, so include that CSS file in public folder.

<!-- index.ejs -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Google Recaptcha Tutorial</title>
    <link rel="stylesheet" href="bootstrap.min.css">
  </head>
  <body>
    <div class="container"><br />
      <h1>Google Recaptcha Tutorial</h1><br />
      <form action="/send-email" method="post">
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="name">Name:</label>
            <input type="text" class="form-control" name="name">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Send</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

To access this page, we need to set up one route in a server.js file.

// server.js

app.get('/', function (req, res) {
    res.render('index');
});

Go to your terminal, type following command.


npm start

Switch to your browser and type this URL: http:///localhost:3000

You will see a form with one field.

Step 3: Configure Google reCaptcha with your Google account. 

Now, you need to register your site with this URL: https://www.google.com/recaptcha to get the API key and API secret.

Google Captcha does not natively support the localhost domain so what you need to do is in the text box of the site name, put your local address: 127.0.0.1. That is it. Now, you can grab the API Key and API Secret.
Here, you will get two things for you ejs file from Google Console.

  1. Script file to fetch that API
  2. That Google Captcha component through which users can identify.

So, your final index.ejs file will be like this.

<!-- index.ejs -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Google Recaptcha Tutorial</title>
    <link rel="stylesheet" href="bootstrap.min.css">
  </head>
  <body>
    <div class="container"><br />
      <h1>Google Recaptcha Tutorial</h1><br />
        <form method="post" action="/captcha">
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="name">Name:</label>
            <input type="text" class="form-control" name="name">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <div class="g-recaptcha" data-sitekey=""></div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success" style="margin-left:38px">Send</button>
          </div>
        </div>
      </form>
    </div>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </body>
</html>

data-sitekey is the key according to your domain. So please replace with yours.

 

Google Recaptcha Tutorial

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Google Recaptcha Tutorial</title>
    <link rel="stylesheet" href="bootstrap.min.css">
  </head>
  <body>
    <div class="container"><br />
      <h1>Google Recaptcha Tutorial</h1><br />
        <form method="post" action="/captcha">
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="name">Name:</label>
            <input type="text" class="form-control" name="name">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <div class="g-recaptcha" data-sitekey=""></div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success" style="margin-left:38px">Send</button>
          </div>
        </div>
      </form>
    </div>
    <script src='https://www.google.com/recaptcha/api.js'></script>
  </body>
</html>

Step 4: Handle the request at the server-side.

Now, set up the server.js file to handle the response. But first, we need to install one HTTP request package called request. So let us do it.

npm install request --save

So, our final server.js file will look like this.

// server.js

const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    request = require('request');

const app = express();
   app.set('view engine', 'ejs');
   app.use(express.static('public'));
   app.use(bodyParser.urlencoded({extended: true}));
   app.use(bodyParser.json());
   var port = 3000;

app.get('/', function (req, res) {
    res.render('index');
});

app.post('/captcha', function(req, res) {
  if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null)
  {
    return res.json({"responseError" : "Please select captcha first"});
  }
  const secretKey = "xxxx";

  const verificationURL = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress;

  request(verificationURL,function(error,response,body) {
    body = JSON.parse(body);

    if(body.success !== undefined && !body.success) {
      return res.json({"responseError" : "Failed captcha verification"});
    }
    res.json({"responseSuccess" : "Sucess"});
  });
});

app.listen(port, function(){
    console.log('Server is running at port: ',port);
});

Put the secret key according to your site. If you submit the form with captcha verification, you will get a success in response.

 

captcha code in nodejs

If you do not verify captcha and send the form then, you will get an error in response.

 

Google captcha in Node.js example

So, our final tutorial is over.

Github Link: https://github.com/KrunalLathiya/nodejsgooglecaptcha

Steps: 

  1. Clone the repository.
  2. type the command: npm install
  3. Go to Google captcha console and grab the api-key and component.
  4. Go to server.js and replace the key with yours.
  5. Go to terminal and type: npm start.

If you have any questions, ask in a comment below.

You might also like More from author

Leave A Reply

Your email address will not be published.