DEV Community

Cover image for Implementing Google reCAPTCHA in Node.js Application
Pankaj Kumar
Pankaj Kumar

Posted on

Implementing Google reCAPTCHA in Node.js Application

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.

Image description

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

Let's have a look over html file,


<body>
<div class='form-group col-md-4 col-md-offset-4' style="background-color:#e2e2e2; margin-top:5%;">
<h2>Google recaptcha Demo with Node.js</h2>
<form id="contact_us_form" action='/submit' method="post">
<input class="form-control" type="text" placeholder="Enter your name here" size="50">

<textarea class="form-control" name="comment" rows="6" cols="40"></textarea>
<div class="g-recaptcha" data-sitekey="6LcNZ20UAAAAANQ6WwGtyB75JcZIkoWQTReMd_TO"></div>
<input type="submit" name="submit" class="btn btn-primary" value="Submit">
</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() {
$('#contact_us_form').submit(function() {
$(this).ajaxSubmit({
error: function(xhr) {
status('Error: ' + xhr.status);
},
success: function(response) {
alert(response.responseDesc);
}
});
return false; // to disable page refresh
});
});
</script>

Enter fullscreen mode Exit fullscreen mode

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-implementation-node-app",
"version": "1.0.0",
"description": "",
"main": "app.js",
"repository": "NA",
"author": "Suraj Roy",
"license": "MIT",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4",
"request": "^2.88.0"
}
}

Enter fullscreen mode Exit fullscreen mode

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 server end.


const express = require('express'),
bodyParser = require('body-parser'),
request = require('request'),
app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : false}));

app.get('/',(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" : "Validate captcha first"});
}

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" : "Captcha verification has Failed. Try again."});
}
res.json({"responseCode" : 0,"responseDesc" : "Captcha validated succesfully!"});
});
});

// 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');
});

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

And our app will look like below on the browser:

Image description

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.

This article is originally posted over jsonworld

Top comments (0)