Tech Blog

Coding, Technology

Verify google recaptcha with Node.js

By Kishan Dasani3 min read
← Back to blog

Overview

Google Recaptcha is a captcha system provided by Google to distinguish between humans and robots.

There are two versions of Recaptcha, namely

  1. Recaptcha v2
  2. Recaptcha v3

This blog will help you understand how google Recaptcha can be used along with node.js and a simple HTML page.

Approach

There are following basic steps to follow here.

  1. Register your site on the google Recaptcha admin console.
  2. HTML form to display the Recaptcha.
  3. Get the token as a response from the Recaptcha verification.
  4. Send the token to the node.js server and get a response.

Step 1: Site registration on Recaptcha console

  1. Head to the Recaptcha Admin console.
  2. Register your site with Recaptcha V2 selected as Recaptcha type and get the credentials that are Site Key and Secret Key.

Step 2: Making an HTML form with Recaptcha

Here, we will be making a simple HTML file with a form with the type submit, one input field, and one button.

Note: replace ‘generated_site_key_here’ with the site key you get from the admin console.

Example file: index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="./styles.css" rel="stylesheet">
  <script src="https://www.google.com/recaptcha/api.js" async defer>
  </script>
</head>
<body>
  <div class="container">
    <h1>Google recaptcha verification with Node.js Server</h1>
    <form action="/post" method="post">
       <div class="g-recaptcha" data-sitekey="generated_site_key_here"></div>
       <br>
       <button type="submit">Submit</button>
     </form>
  </div>
</body>
</html>

Example file: styles.css

.container {
   border: 1px solid rgb(73, 72, 72);
   border-radius: 10px;
   margin: auto;
   padding: 10px;
   text-align: center;
}
h1 {
   margin-top: 10px;
}
button {
   border: none;
   border-radius: 10px;
   padding: 15px;
   color: #fff;
   background-color: #4285f4;
   font-weight: bolder;
   cursor: pointer;
}
button:hover {
   text-decoration: none;
   background-color: #0069d9;
}
.g-recaptcha {
   margin-left: 550px;
}

Step 3: Node.js server

  1. Create a new directory and do npm init which will generate a package.json file.
  2. We will be using two external packages, express and request to make external http/https calls.

Example file: package.json

{
  "name": "recaptcha",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  "express": "^4.17.1",
  "request": "^2.88.2"
  }
}

Step 4: Recaptcha Verification

In order to verify the Recaptcha, we need to make a post request to the Google server.

URL: https://www.google.com/recaptcha/api/siteverify?secret=<generated_secret_key>&response=<response_key>

geneated_ecret_key: This is the key you’ll get from the admin console. Replace that with your key.

Response_key: This key comes from the client when a user submits the request.

Example file: app.js

const express = require("express");
const { promisify } = require('util');
const request = promisify(require('request'));
const app = express();
app.use(express.static(__dirname + '/public'));
app.use(express.urlencoded({ extended: false }));
app.get('/', function (req, res) {
  res.sendFile('/index.html');
});
app.post("/post", async (req, res) => {
  const name = req.body.name;
  const response_key = req.body["g-recaptcha-response"];
  const secret_key = "<generated_site_key>";
  const options = {
  url: `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${response_key}`,
  headers: { "Content-Type": "application/x-www-form-urlencoded", 'json': true }
  try {
      const re = await request(options);
      if (!JSON.parse(re.body)['success']) {
         return res.send({ response: "Failed" });
      }
      return res.send({ response: "Successful" });
      } catch (error) {
         return res.send({ response: "Failed" });
      }
});
const PORT = 3000;
app.listen(PORT, () => console.log(`Server is running on PORT ${PORT}`));

Note: 

g-recaptcha-response is the name of the response key that the browser will generate upon form submission.

Running the app:

  1. To run the application, go to the terminal and type node app.js, go to localhost:4000 to view the app running.
  2. Fill in the details & click Submit.
  3. You’ll see one of the following responses.


When Recaptcha is successfully verified


When Recaptcha verification fails

Keep reading

You may be interested in

Browse all articles →
How Angular is Different from AngularJS
September 27, 20227 min read

How Angular is Different from AngularJS

What is Angular? Angular is a popular open-source Typescript framework and free to use. Considered to be a JavaScript-based framework,TypeScript.is its primary programming language. TypeScript is Developed by Microsoft and its superset of JavaScript, which simply means that TypeScript has all the capabilities that JS has and more additional features. Angular is majorly used for […]

By Sachin DevadigaRead More →
Angular constructor vs ngOnInit
September 15, 20223 min read

Angular constructor vs ngOnInit

Overview: If you are new to angular or have been working with it for a while, you will have questions like: Is it necessary to inject dependencies in the constructor and bind data? When should we use ngOnInit ? What is the difference between constructor and OnInit?. So, in this blog we will answer all […]

By Priyanka SRead More →
Angular – Difference between ng-container and ng-template
July 13, 20222 min read

Angular – Difference between ng-container and ng-template

Overview: ng-container and ng-template, both are angular elements which will work like containers with HTML elements, but with different purpose/use cases. Lets see what is the use of ng-container and ng-template below: ng-container: In some cases when you do not want to add an extra HTML element to the DOM , for example like div […]

By Priyanka SRead More →