Skip to main content

Google ReCaptcha v3 in Nodejs

Google ReCaptcha v3 in Nodejs

In this node js google v3 recaptcha example tutorial, we will use Node.js and express framework to build a Google v3 Recaptcha Security.

1. Get Google reCaptcha v3 credentials

Now, you need to register your site with 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.

2. Create a fresh project

Here you need to create project folder and then type the following command into your command prompt (cmd):

mkdir public

npm init 

We are initializing the package.json file.

{

  "name": "googlerecaptcha",

  "version": "1.0.0",

  "description": "",

  "main": "server.js",

  "scripts": {

    "start": "nodemon server"

  },

  "author": "tutsmake.com",

  "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

3. Create view file in project

Create one file name index.ejs is called views file. In this file, We are using the Bootstrap CSS Framework for this application, so we will include that CSS file in the public folder.

<!-- index.ejs -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Node js Google v3 Recaptcha Example 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">
        <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>

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

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

4. Create server.js and Handle the request at the server-side

Here, we will to do two things. First one is install one HTTP request package called request. So use the following command to install HTTP request package in Node js:

npm install request --save

Second thing creates a server.js file inside your project folder and update the following code into your server.js file:

// 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" : "something goes to wrong"});
  }
  const secretKey = "xxxx";

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

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

    if(body.success !== undefined &amp;&amp; !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 success in response.

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

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

JavaScript new features in ES2019(ES10)

The 2019 edition of the ECMAScript specification has many new features. Among them, I will summarize the ones that seem most useful to me. First, you can run these examples in  node.js ≥12 . To Install Node.js 12 on Ubuntu-Debian-Mint you can do the following: $sudo apt update $sudo apt -y upgrade $sudo apt update $sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates $curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - $sudo apt -y install nodejs Or, in  Chrome Version ≥72,  you can try those features in the developer console(Alt +j). Array.prototype.flat && Array.prototype. flatMap The  flat()  method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. let array1 = ['a','b', [1, 2, 3]]; let array2 = array1.flat(); //['a', 'b', 1, 2, 3] We should also note that the method excludes gaps or empty elements in the array: let array1 ...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...