Open In App

How to verify recaptcha in Node.js server call ?

Last Updated : 30 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Google reCAPTCHA:  reCAPTCHA is a CAPTCHA system that enables web hosts to distinguish between human and automated access to websites. This service is offered by Google.

There are two versions of reCAPTCHA offered by google:

  1. reCAPTCHA v3
  2. reCAPTCHA v2

In this article, we will see about reCAPTCHA v2.

Approach:

  • Register your site at google reCAPTCHA
  • Submit HTML form.
  • Get the response key in the Node.js server
  • Re-verify the key and give response to user end.

Step 1: Register your site at google reCAPTCHA

Register your website at Google reCAPTCHA platform to get keys i.e. Site key and Secret key needed to code the HTML form.

Click here to go to Google reCAPTCHA website. 

Demo to Register site at Google reCAPTCHA

Step 2: Creating Google reCAPTCHA form in HTML

Here, We are going to create a simple HTML form with action as /submit, one input field, and a button. Meanwhile, we need to add google reCAPTCHA CDN in our HTML document and a div tag in the form to get reCAPTCHA in the HTML document.

CDN: <script src="https://www.google.com/recaptcha/api.js" async defer></script>
DIV TAG: <div class="g-recaptcha" data-sitekey="your_site_key"></div> 

Note: Your need to replace “your_site_key” with your Site Key.

Example:

Filename: index.html

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">
 
    <!-- CSS file -->
    <link rel="stylesheet" href="style.css">
 
    <!-- Google reCAPTCHA CDN -->
    <script src=
    </script>
</head>
 
<body>
    <div class="container">
        <h1>Google recaptcha</h1>
 
        <!-- HTML Form -->
        <form action="/submit" method="post">
            <input type="text" name="name" id="name"
                   placeholder="Enter Name" required>
            <br>
 
            <!-- div to show reCAPTCHA -->
            <div class="g-recaptcha"
                 data-sitekey="your_site_key">
            </div>
            <br>
             
            <button type="submit">Submit</button>
        </form>
         
    </div>
</body>
 
</html>


Filename: style.css

CSS




.container {
  border: 1px solid rgb(73, 72, 72);
  border-radius: 10px;
  margin: auto;
  padding: 10px;
  text-align: center;
}
 
h1 {
  margin-top: 10px;
}
 
input[type="text"] {
  padding: 10px;
  border-radius: 5px;
  margin: 10px;
  font-family: "Times New Roman", Times, serif;
  font-size: larger;
}
 
button {
  border-radius: 5px;
  padding: 10px;
  color: #fff;
  background-color: #167deb;
  border-color: #0062cc;
  font-weight: bolder;
  cursor: pointer;
}
 
button:hover {
  text-decoration: none;
  background-color: #0069d9;
  border-color: #0062cc;
}
 
.g-recaptcha {
  margin-left: 513px;
}


Output:

HTML Form

Step 3: Node.js Server:

We have our form ready, let’s code our Server file. On the server-side, we are going to use two packages, one is express for the server as a web framework and another is isomorphic-fetch for http/https call.

Create new directory and generate package.json file in it. Use npm init command to generate the package.json file, its the best practice. Here is my package.json file for reference.

Filename: package.json

Javascript




{
  "name": "google_recaptcha",
  "version": "1.0.0",
  "description": "Google recaptacha v2 demonstration.",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "Asmit Sirohi",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "isomorphic-fetch": "^3.0.0"
  }
}


Now, Let’s code for Server file where HTML form will submit data.

Step 4: Verify the captcha:

In order to verify the captcha, We need to make a post request to the following URL.

  • URL: https://www.google.com/recaptcha/api/siteverify?secret=<secret_key>&response=<response_key>
  • secret_key: This key you will get from google console i.e. Secret Key.
  • response_key: This key comes from the client-side when a user submits the form.

Note:

  • g-recaptcha-response is the name of response key that browser will generate upon form submit. If its blank or null means user has not selected the captcha, so return the error.
  • Your need to replace “your_secret_key” with your Secret Key.

Filename: app.js

Javascript




// Importing express package
const express = require("express");
// Importing isomorphic-fetch package
const fetch = require("isomorphic-fetch");
 
// instantiating express package
const app = express();
 
// Making public folder static where index.html file is present
// By making it static, we can easily serve index.html page
app.use(express.static("public"));
 
// To accept HTML form data
app.use(express.urlencoded({ extended: false }));
 
// Here, HTML form is submit
app.post("/submit", (req, res) => {
  const name = req.body.name;
  // getting site key from client side
  const response_key = req.body["g-recaptcha-response"];
  // Put secret key here, which we get from google console
  const secret_key = "<your_secret_key>";
 
  // Hitting POST request to the URL, Google will
  // respond with success or error scenario.
  const url =
`https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${response_key}`;
 
  // Making POST request to verify captcha
  fetch(url, {
    method: "post",
  })
    .then((response) => response.json())
    .then((google_response) => {
 
      // google_response is the object return by
      // google as a response
      if (google_response.success == true) {
        //   if captcha is verified
        return res.send({ response: "Successful" });
      } else {
        // if captcha is not verified
        return res.send({ response: "Failed" });
      }
    })
    .catch((error) => {
        // Some error while verify captcha
      return res.json({ error });
    });
});
 
// lifting the app on port 4000.
const PORT = 4000;
app.listen(PORT, () => console.log(`Server is running on PORT ${PORT}`));


Running the app:

To run the application, switch to the project folder and run the Node app using the command.

node app.js

Go to localhost:4000 to view the app.

Output:

  • When Captcha Verified

  • When Captcha is not verify



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads