Google ReCaptcha v3 in Node JS Express

Google V3 Recaptcha In Node.js express app; in this tutorial; i will show you how to implement Google Recaptcha v3 in node js express app.

Google eCAPTCHA is a security service that protects your websites from fraud and abuse. And reCAPTCHA works by taking any of the scanned words that cannot be recognised and presenting them to a human alongside a known word for interpretation. By typing the known word correctly, you identify yourself as a human and the reCAPTCHA system gains some confidence that you have correctly digitised the second.

Implementing Google reCAPTCHA v3 in Node.js

  • Step 1 – Get Key Id and Secret Form Google ReCaptcha
  • Step 2 – Create a Node js Express App
  • Step 3 – Create Form
  • Step 4 – Install Required Modules
  • Step 5- Start Node js Express Recaptcha App

Step 1 – Get Key Id and Secret Form Google Recaptcha

Visit this URL: https://www.google.com/recaptcha to get the API key and API secret.

Note:- 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.

Step 2 – Create a Node js Express App

Create node js express app by executing the following command into your command prompt:

mkdir public

npm init 

Then initializing the package.json file; as shown below:

{

  "name": "googlerecaptcha",

  "version": "1.0.0",

  "description": "",

  "main": "server.js",

  "scripts": {

    "start": "nodemon server"

  },

  "author": "laratutorials.com",

  "license": "ISC",

  "dependencies": {

    "body-parser": "^1.17.2",

    "ejs": "^2.5.7",

    "express": "^4.15.4"

  },

  "devDependencies": {

    "nodemon": "^1.11.0"

  }

}

Then visit your terminal and execute the following command on terminal:

npm install

Step 3 – Create Form

Create html markup form; so visit your app root directory and create index.html file and add the following code into it:

<!-- index.ejs -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Node js Google v3 Recaptcha Example Tutorial - Laratutorials</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">
        <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
        <input type="hidden" name="action" value="validate_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">
            <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?render=your reCAPTCHA site key here"></script>
<script>
    grecaptcha.ready(function() {
    // do request for recaptcha token
    // response is promise with passed token
        grecaptcha.execute('your reCAPTCHA site key here', {action:'validate_captcha'})
                  .then(function(token) {
            // add token value to form
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>
  </body>
</html>

Step 4 – Install Required Modules

Execute the following command on terminal to install some required modules in your node js express app:

npm install express --save
npm install body-parser --save
npm install request --save

Then create a new file name server.js and import above installed required modules in server.js file:

// server.js
const express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    request = require('request');
const app = express();
  
   app.use(express.static('public'));
   app.use(bodyParser.urlencoded({extended: true}));
   app.use(bodyParser.json());
   var port = 3000;

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

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" : "something goes to wrong"});
  }
  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);
});

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

Step 5- Start Node js Express Recaptcha App

Execute the following command on terminal to start node js express recaptcha app:

npm start

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

Recommended Node JS Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.