Node JS Implement Google reCAPTCHA v2 Tutorial

Google reCaptcha v2 in Node js tutorial; In this comprehensive tutorial we will share with you how to add the Google ReCaptcha version 2 in the Node js application step by step and that too from absolute zero.

Google reCAPTCHA is an essential security tool it provides additional layer of security to your sites.

It secures your website from unwanted bots, malicious spams and help differentiate between humans and bots.

This guide will show you how to pretty comfortably set up google captcha v2 in Node js using site key and secret key.

We need the Google reCaptcha credentials site key and secret key to incorporate the Google ReCaptcha in the node js application.

Also, we will definitely help you create and get the reCaptcha credentials for protecting node js application from spam.

We are going to use latest version of Node and Express js, also couple of packages to create Google reCaptcha security system in your node app.

In the previous chapter we covered how to add Google ReCaptcha version 3 in node js. Make sure to checkout.

How to Add Google ReCaptcha v2 in Node Js App

  • Step 1: Build Node Project
  • Step 2: Install Required Packages
  • Step 3: Create Google ReCaptcha Details
  • Step 4: Create Captcha View
  • Step 5: Configure Server File
  • Step 6: Run Application

Build Node Project

Let’s create a blank new folder using the given command.

It will be a pivot point for Google reCaptcha system.

mkdir node-demo

There is another way to create the directory, you can create the folder manually.

cd node-demo

Next, we have to type and invoke the following command.

npm init

Also, we need to create the server.js file, make sure to register in package.json file.

{
  "main": "server.js",
}

Install Required Packages

In order to create the spam protection in node js we need to add the couple of packages.

npm install express

We are using the nodemon module for node server invocation.

npm install nodemon --save-dev

Create Google ReCaptcha Details

Click on the create ReCaptcha for creating credentials.

In the label field, add the captcha project name.

Google ReCaptcha

Choose the type of reCAPTCHA v2.

Add the domains, that you want to incorporate the Google ReCaptcha.

Accept the terms of services and click on Submit button.

Get Google ReCaptcha Details

Now, you can copy site key and secret key.

Create Captcha View

Next, create a ‘public’ folder, then create index.html file.

Eventually, insert the provided code into the public/index.html file.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Node Google Recaptcha v2 Example</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <div class="container mt-5">
      <form method="post" action="/submit">
        <div class="form-group col-md-4">
          <label for="name">Name:</label>
          <input
            type="text"
            class="form-control"
            name="name"
            id="name"
            required
          />
        </div>

        <div class="col-12 mt-3">
          <div class="g-recaptcha" data-sitekey="SITE_KEY_GOES_HERE"></div>
        </div>

        <div class="form-group mt-3">
          <button type="submit" class="btn btn-primary">Submit</button>
        </div>
      </form>
    </div>
  </body>
</html>

Configure Server File

Now, we need to create the server file for establishing the app connection, apis etc.

For making the request in node we need given package.

npm install isomorphic-fetch

Move onto the server.js file then insert the following code.

const express = require('express')
const fetch = require('isomorphic-fetch')

const app = express()

app.use(express.static('public'))
app.use(express.urlencoded({ extended: false }))

app.post('/submit', (req, res) => {
  const name = req.body.name
  const resKey = req.body['g-recaptcha-response']
  const secretKey = '<SECRET_KEY_GOES_HERE>'
  const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${resKey}`

  fetch(url, {
    method: 'post',
  })
    .then((response) => response.json())
    .then((google_response) => {
      if (google_response.success == true) {
        return res.send({ response: 'Successful' })
      } else {
        return res.send({ response: 'Failed' })
      }
    })
    .catch((error) => {
      return res.json({ error })
    })
})

const PORT = 3000

app.listen(PORT, () => console.log(`Server working on: ${PORT}`))

Run Application

Finally, type the following command to start the node app.

nodemon

You may use the given url to check the node captcha:

http://localhost:3000

Here is the output you will see on the browser:

Node JS Implement Google reCAPTCHA v2 Tutorial