Node js Google reCaptcha tutorial; This quick guide will help you ascertain how to step by step implement the Google ReCaptcha in the Node js application from absolute scratch.
To integrate the google ReCaptcha in the node js application, we require the Google reCaptcha site key and secret key.
This guide will cover how to get the google captcha site key and secret key not only but also help you work with the latest version of Google ReCaptcha version 3.
Google reCAPTCHA is like a security mechanism that empowers your site and helps to secure your websites from fraud and abuse.
reCAPTCHA is a free service that helps distinguish between humans and bots and secures from fraudulent activities, spam and abuse.
Node JS Google reCAPTCHA v3 Example
- Step 1: Set Up Node Project
- Step 2: Install Node Dependencies
- Step 3: Get Google ReCaptcha Details
- Step 4: Create Captcha Form
- Step 5: Build Node Server File
- Step 6: Run Node Application
Set Up Node Project
We have to set up a brand new node project for integrating Google ReCaptcha in node js.
Without wasting a much time, run the provided command.
mkdir node-test
The above command created a new folder in your system.
However, if you want you may also create it manually.
As soon as the folder is generated, get into the folder.
cd node-test
You are now ready to initialize the npm init command.
npm init
Above command asks some questions on terminal window, make sure to provide the details as per the questions asked.
A new package.json file will be generated in your node project.
Also, create the index.js file for your node project.
Next, you have to register the server file inside the “main” property inside the package.json file.
{
"main": "index.js",
}
Install Node Dependencies
In this step, you have to add or install the required node packages.
It’s pretty easy, just copy the given command on the terminal and hit enter.
npm install body-parser express ejs
Small changes in the server file require the server to be restarted repeatedly.
You can get rid of this issue by using the following package.
npm install nodemon --save-dev
Get Google ReCaptcha Details
In this step, we will show you how to obtain google captcha credentials.
Click on the create ReCaptcha link and login with your email id.
In the label field, add the label, which will make it easier for you to recognize your site in the near future.
Look at the ReCaptcha type section, select the type of reCAPTCHA for site key. Note: A site key only works with a single reCAPTCHA site type.
Add the domains, that you want to incorporate the Google ReCaptcha.
Accept the terms of services and click on Submit button.
From the next screen you can get site key and secret key.
Create Captcha Form
In this step, you have to create a view file that holds the code for showing form with captcha.
Therefore, create a “views” folder, also create captcha-view.ejs file into this folder.
Next, add the given code into the views/captcha-view.ejs file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Node Google Recaptcha v3 Example</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
</head>
<body>
<div class="container mt-5">
<form method="post" action="/captcha">
<input type="hidden" id="catcha-res" name="catcha-res" />
<input type="hidden" name="action" value="verify_gcaptcha" />
<div class="col-md-12"></div>
<div class="form-group col-md-12">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" />
</div>
<div class="col-12"></div>
<div class="form-group mt-3">
<button type="submit" class="btn btn-primary">Send</button>
</div>
</form>
</div>
<script src="https://www.google.com/recaptcha/api.js?render=Add_reCAPTCHA_Site_Key_Here"></script>
<script>
grecaptcha.ready(function () {
grecaptcha
.execute("Add_reCAPTCHA_Site_Key_Here", {
action: "verify_gcaptcha",
})
.then(function (token) {
document.getElementById("catcha-res").value = token;
});
});
</script>
</body>
</html>
Bootstrap comes in handy when you need to create the UI components swiftly; hence we are using Bootstrap 5 to design the form.
Build Node Server File
In this step, we will show you how to prepare the server file. This file will hold the app connection, apis for showing and making request.
Before jump on to write some code, make sure to install the given package.
npm install request
Head over to index.js file, and add the given code into the file.
const express = require('express')
const request = require('request')
const bodyParser = require('body-parser')
const app = express()
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
let port = 4000
app.get('/', function (req, res) {
res.render('captcha-view')
})
app.post('/captcha', function (req, res) {
if (
req.body['catcha-res'] === undefined ||
req.body['catcha-res'] === null ||
req.body['catcha-res'] === ''
) {
return res.json({ responseError: 'something went wrong' })
}
const secretKey = 'Add_reCAPTCHA_Secret_Key_Here'
const isUrlValid =
'https://www.google.com/recaptcha/api/siteverify?secret=' +
secretKey +
'&response=' +
req.body['catcha-res'] +
'&remoteip=' +
req.socket.remoteAddress
request(isUrlValid, function (error, response, body) {
body = JSON.parse(body)
if (body.success !== undefined && !body.success) {
return res.json({ responseError: 'Captcha verification failed' })
}
res.json({ responseSuccess: 'Sucess' })
})
})
app.listen(port, function () {
console.log('Server working at: ', port)
})
Run Node Application
In the final section, we will start the node application using the given command:
nodemon
You can now open the app on the given url:
On the web page, make sure to look at the corners for Google reCAPTCHA label.
Summary
Throughout this small yet eloquent tutorial, we learned how to get the google ReCaptcha site key and secret keys.
Not only but also learn how to implement Google reCaptcha in the Node js application. To incorporate the captcha in the node is super easy and protects your site from spam, fraud and abuse.