Implementing google reCAPTCHA in node.js application

Cronjob

Hi Coders, today we will create a demo to implement google reCAPTCHA in any nodejs application. So now the question is what is google reCAPTCHA.

What is google reCAPTCHA?

reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive CAPTCHAs to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.

So lets proceed step by step:

Step 1: Register your site at Google reCAPTCHA

Register your web site at Google recaptcha platform to get keys needed to code the form. Click here to go to Google reCAPTCHA website. So login over google add your website details.

Step 2: Frotent part, Creating Google reCAPTCHA form in HTML

Let's have a look over html file, 

 

 
<body>
<div class='form-group' style="margin-top: 100px; width : 600px; margin-left : 25%;">
<h1>Google recaptcha Demo with Node.js</h1>
<form id="comment_us_form" action='/submit' method="post">
<input type="email" placeholder="Type your email" size="40"><br><br>
<textarea name="comment" rows="8" cols="39"></textarea><br><br>
<div class="g-recaptcha" data-sitekey="Enter site key here"></div><br>
<input type="submit" name="submit" value="Post comment"><br><br>
</form>
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script>
<script>
$(document).ready(function() {
$('#comment_us_form').submit(function() {
$(this).ajaxSubmit({
error: function(xhr) {
status('Error: ' + xhr.status);
},
success: function(response) {
alert(response.responseDesc);
}
});
return false;
});
});
</script>
 

 

Put site key under google recaptcha div. We can see there is a simple form with saction '/submit'. And when user clicks over submit form, browser will POST data over server created method. So if you are running the app at localhost:3000 then browser will submit the form data at localhost:3000/submit. 

Step 3 : Server Creation.

Have a look on the first file of server, package.json

 

 
{
"name": "google-racapcha-node",
"version": "1.0.0",
"description": "",
"main": "app.js",
"repository": "NA",
"author": "Suraj Roy",
"license": "MIT",
"dependencies": {
"body-parser": "^1.15.0",
"express": "^4.13.4",
"request": "^2.69.0"
}
}
 

 

In the above fiile we can see the packages need  for the demo app and basic information of the app.
So move to next file server.js, where post method is defined to handle the request and perform the actual task at serve end.

 

 
let express = require('express'),
bodyParser = require('body-parser'),
request = require('request'),
app = express();
 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));
 
app.get('/',function(req,res) {
// Sending our HTML file to browser.
res.sendFile(__dirname + '/index.html');
});
 
app.post('/submit',function(req,res){
/* Browse generates the google-recapcha-response key on form submit.
if its blank or null means user has not selected the captcha then blow error loop occurs.*/
if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {
return res.json({"responseCode" : 1,"responseDesc" : "Please select captcha"});
}
 
let secretKey = "6LcNZ20UAAAAACJ270WFWVBeEky5kZ8i1kJPRbWY"; // Put your secret key here.
let verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + req.body['g-recaptcha-response'] + "&remoteip=" + req.connection.remoteAddress;
// Google will respond with success or error scenario on url request sent.
request(verificationUrl,function(error,response,body) {
body = JSON.parse(body);
// Success will be true or false depending upon captcha validation.
if(body.success !== undefined && !body.success) {
return res.json({"responseCode" : 1,"responseDesc" : "Failed captcha verification"});
}
res.json({"responseCode" : 0,"responseDesc" : "Sucess"});
});
});
 
// for handling 404 requests.
app.use("*",function(req,res) {
res.status(404).send("404");
})
 
app.listen(3000,function(){
console.log('app listening on port:3000');
});
 

 

Now we have completed all the stuff to create the demo, so by typing the below command run the app and go to browser and open the url : http://localhost:3000

node server.js

 
And our app will look like below on  the browser:
 
So in the created demo every time google reCAPTCHA is needed to validate while submitting the form.
 

Pretty cool! Finally our task completes here.

That’s all for now. Thank you for reading and I hope this post will be very helpful for implimentation of googlel reCAPTHCA in nodejs application.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

You can download complete code from here. Download Code