Verify google recaptcha with Node.js


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

Leave A Comment

Your email address will not be published. Required fields are marked *