How to verify recaptcha in Node.js server call?

JavascriptFront End TechnologyProgramming ScriptsWeb Development

In this tutorial, we will learn about how to verify Google's reCAPTCHA in a Node.js server call. Google's reCAPTCHA is a CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) that is used to protect websites from spam and abuse. It does this by displaying a challenge to the user that must be solved before they can access the website.

How it works?

When a user accesses a website that is protected by reCAPTCHA, they will be presented with a challenge. This challenge can take the form of an image, audio, or text. The user must then correctly answer the challenge in order to gain access to the website.


In order to implement reCAPTCHA on a website, we must first register our website with google. We can do this by going to the reCAPTCHA website and clicking on the "Get reCAPTCHA" button.

Once we have registered our website, we will be given a Site key and a Secret key. These keys are used to authenticate our website with the reCAPTCHA service.

The next step is to add the reCAPTCHA widget to our website. This can be done by adding the following code to our website −

<div class="g-recaptcha" data-sitekey="our-site-key"></div>

Replace "our-site-key" with the Site key that we were given when we registered our website.

The final step is to add the following code to our Node.js server −

var express = require('express'); var request = require('request'); var app = express(); app.get('/', function(req, res){ var response = req.query['g-recaptcha-response']; if(!response){ return res.send('Please select Captcha'); } var secret = 'our-secret-key'; var verificationUrl = "" + secret + "&response=" + response; request(verificationUrl,function(error,response,body) { body = JSON.parse(body); if(body.success !== undefined && !body.success) { return res.send('Failed Captcha verification'); } res.send('Captcha verification passed'); }); }); app.listen(3000);

Replace "our-secret-key" with the Secret key that we were given when we registered our website.

In this code, we are using the Express web framework for Node.js. We are also using the request module to make HTTP requests.

The code above will create a server that listens on port 3000. When a user accesses the "/" route, we will first check to see if they have completed the reCAPTCHA challenge. If they have not, we will return an error message.

If the user has completed the challenge, we will make a request to the Google reCAPTCHA API to verify the response. If the response is valid, we will return a success message. Otherwise, we will return an error message.


In this article, we have learned how to implement Google's reCAPTCHA on a website using Node.js. We have also learned how to verify the user's response to the challenge.

Updated on 10-Oct-2022 12:17:33