Google Recaptcha Node.JS (Express.js) Tutorial

When it comes to the security of modern web app’s, Google Security Products are best in the industry and powered by Machine Learning and Ai. In this Tutorial, we will learn about Google reCAPTCHA setup in Node.js and Express.js framework of Nodejs. Google reCAPTCHA Protects your web app from bots, Abusers, and spammers.Which can be used to protect your Blog, website, web app, forum etc.

Things you need to know:

Basics of Node.js and Express.js.

See also  Renaming files with Node.js - How to Guide

Article Contents

Creating New Node.js project using NPM and configuring it for Google reCAPTCHA

First, we need to create package.json file for our project, which you can generate automatically using our guide, generate package.json file automatically in nodejs.

  • create the new directory for the project using mkdir NodeProject
  • Initiate the project using npm init and fill all the required data and package.json file will look like this:
    {
      "name": "google-recaptcha-nodejs",
      "version": "1.0.0",
      "description": "Google reCAPTCHA Node.js Tutorial",
      "main": "app.js",
      "scripts": {
        "start": "node app"
      },
      "repository": {
        "type": "git",
        "url": "git+https://github.com/vithalreddy/google-racapcha-nodejs.git"
      },
      "author": "stackFame",
      "license": "ISC",
      "dependencies": {
        "body-parser": "^1.17.2",
        "ejs": "^2.5.7",
        "express": "^4.15.4"
      },
      "devDependencies": {
        "nodemon": "^1.11.0"
      }
    }
  • Install the project dependencies using npm install or npm i.
  • we will start the project by creating an app.js file as the main entry point of the project.
    // app.js file
    
    const express = require('express');
    const path = require('path');
    const bodyParser = require('body-parser');
    const port = 3000;
    
    var app = express();
    //setting view engine as ejs
    app.set('view engine', 'ejs');
    //setting expressjs static folder
    app.use(express.static('public'));
    
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
    });
    
    app.listen(port, function(){
        console.log('app is running at port: ',port);
    });

    Here, we are using express framework for making things easy and ejs as templating engine and Public folder as expressjs’s static folder and we are also using body-parser to parse HTTP request’s data.we are ready to start with google reCaptcha.

setting up views for Google reCAPTCHA in our node.js project

as we are using EJS ( embedded javascript ) as templating engine, we can directly embed javascript in HTML tags, we are going create views based on our requirements as follows

  • create the views folder inside our project directory.
  • We are also going to use BootStrap frontend frame for the frontend, create an index.ejs file as below
    <!-- index.ejs file -->
    
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Google Recaptcha in Node.js Tutorial</title>
        <link rel="stylesheet" href="bootstrap.min.css">
      </head>
      <body>
        <div class="container">
          <h1>Google Recaptcha in Node.js Tutorial</h1>
          <form action="/form-data" 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>
  •  Create a route for this file in the app.js file.
    // app.js
    
    app.get('/', function (req, res, next) {
        res.render('index.ejs');
    });
  • You can test your app by running your node app using npm start and go to localhost:3000

Configuring Google reCAPTCHA  with Google account and using it in Nodejs

You’ll will get an error if you try use localhost, so what you can do is you can use 127.0.0.1 local ip address.

  • you need to app google reCAPTCHA api cdn link in index.ejs file just above </body> tag
    <!-- index.ejs file-->
    
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Google Recaptcha in Node.js Tutorial</title>
        <link rel="stylesheet" href="bootstrap.min.css">
      </head>
      <body>
        <div class="container"><br />
          <h1 claa="text-center">Google Recaptcha in Node.js 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">
                  <!-- add your domain data-sitekey below-->
                  <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>

    Google Recaptcha Nodejs Tutorial

setting server requests for Google reCaptcha in Nodejs (Express.js)

  • For handling HTTP request we need to install request NPM module with save flag.
    npm install request --save
  •  Final app.js will look like this
    // app.js file
    
    const express = require('express');
    const path = require('path');
    const bodyParser = require('body-parser');
    const request = require('request');
    const port = 3000;
    
    const app = express();
    
    app.set('view engine', 'ejs');
    app.use(express.static('public'));
    
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    
    
    app.get('/', function (req, res, next) {
        res.render('index.ejs');
    });
    
    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" : captcha error"});
      }
      const secretKey = "*******";
    
      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"});
      });
    });
    
    // catch 404 and forward to error handler 
    app.use(function(req, res, next) { 
    var err = new Error('Not Found'); err.status = 404; next(err); 
    });
    
    app.listen(port, function(){
        console.log('Server is running at port: ',port);
    });

     

  • if everything went well, then you will get a success message {"responseSuccess" : "Sucess"}  and if anything goes wrong you will get error message {"responseError" : captcha error"}

if you want to use NPM module for google recaptch then you can check out https://www.npmjs.com/package/recaptcha2

Conclusion:

Google’s reCAPTCHA is the best solution available free fight spammers, bots and abusers online. I hope this tutorial helped you to setup reCaptcha using Nodejs and if you have any doubts and queries please comment below.

 

Leave a Comment