There are two versions of reCAPTCHA offered by Google:
- reCAPTCHA v3
- reCAPTCHA v2
We will use reCAPTCHA v2.
Here is the step-by-step guide for Google recaptcha in Node.js.
Step 1: Create a project and configure it.
npm init
We are initializing the package.json file.
{
"name": "googlerecaptcha",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server"
},
"author": "Krunal Lathiya",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.2",
"ejs": "^2.5.7",
"express": "^4.15.4"
},
"devDependencies": {
"nodemon": "^1.11.0"
}
}
We have written three packages as dependencies, so go to your terminal and type the command.
npm install
Now, create one file in a root called server.js and create one folder name public in the root.
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = 3000;
app.listen(port, function(){
console.log('Server is running at port: ',port);
});
Step 2: Set up the views for our project.
Create one folder in the root called views. In that folder, create one ejs file called index.ejs. We use Bootstrap CSS Framework for this application, so include that CSS file in the public folder.
<!-- index.ejs --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Google Recaptcha Tutorial</title> <link rel="stylesheet" href="bootstrap.min.css"> </head> <body> <div class="container"><br /> <h1>Google Recaptcha Tutorial</h1><br /> <form action="/send-email" method="post"> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="name">Name:</label> <input type="text" class="form-control" name="name"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success">Send</button> </div> </div> </form> </div> </body> </html>
To access this page, we need to set up one route in a server.js file.
// server.js app.get('/', function (req, res) { res.render('index'); });
Go to your terminal, type the following command.
npm start
Switch to your browser and type this URL: http://localhost:3000
You will see a form with one field.
Step 3: Configure Google reCaptcha with your Google account.
Now, you need to register your site with this URL: https://www.google.com/recaptcha to get the API key and API secret.
Google Captcha does not natively support the localhost domain, so what you need to do is in the text box of the site name, put your local address: 127.0.0.1. That is it. Now, you can grab the API Key and API Secret.
Here, you will get two things for your ejs file from Google Console.
- Script file to fetch that API
- That Google Captcha component through which users can identify.
So, your final index.ejs file will be like this.
<!-- index.ejs --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Google Recaptcha Tutorial</title> <link rel="stylesheet" href="bootstrap.min.css"> </head> <body> <div class="container"><br /> <h1>Google Recaptcha Tutorial</h1><br /> <form method="post" action="/captcha"> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="name">Name:</label> <input type="text" class="form-control" name="name"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <div class="g-recaptcha" data-sitekey=""></div> </div> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success" style="margin-left:38px">Send</button> </div> </div> </form> </div> <script src='https://www.google.com/recaptcha/api.js'></script> </body> </html>
The data-sitekey is the key according to your domain. So please replace it with yours.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Google Recaptcha Tutorial</title> <link rel="stylesheet" href="bootstrap.min.css"> </head> <body> <div class="container"><br /> <h1>Google Recaptcha Tutorial</h1><br /> <form method="post" action="/captcha"> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <label for="name">Name:</label> <input type="text" class="form-control" name="name"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <div class="g-recaptcha" data-sitekey=""></div> </div> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="form-group col-md-4"> <button type="submit" class="btn btn-success" style="margin-left:38px">Send</button> </div> </div> </form> </div> <script src='https://www.google.com/recaptcha/api.js'></script> </body> </html>
Step 4: Handle the request on the server side.
Set up the server.js file to handle the response. But first, we need to install one HTTP request package called request. So let us do it.
npm install request --save
So, our final server.js file will look like this.
// server.js const express = require('express'), path = require('path'), bodyParser = require('body-parser'), request = require('request'); const app = express(); app.set('view engine', 'ejs'); app.use(express.static('public')); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); var port = 3000; app.get('/', function (req, res) { res.render('index'); }); app.post('/captcha', function(req, res) { if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) { return res.json({"responseError" : "Please select captcha first"}); } const secretKey = "xxxx"; const verificationURL = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress; request(verificationURL,function(error,response,body) { body = JSON.parse(body); if(body.success !== undefined && !body.success) { return res.json({"responseError" : "Failed captcha verification"}); } res.json({"responseSuccess" : "Sucess"}); }); }); app.listen(port, function(){ console.log('Server is running at port: ',port); });
Put the secret key according to your site. Then, if you submit the form with captcha verification, you will get success in response.
If you do not verify the captcha and send the form, you will get an error in response.
That’s it for this tutorial.
Follow The Below Github Steps:
- Clone the repository.
- type the command: npm install
- Go to Google-captcha console and grab the API-key and component.
- Go to server.js and replace the key with yours.
- Go to the terminal and type: npm start.
Ravi Anand
went through top to bottom. A good article and source code. thanks
vu vinh hien
thanks you