Google reCAPTCHA v3 with Node.js

You are Here:

What is Google's reCAPTCHA?

Google's reCAPTCHA is a free service that protects your website from spam and abuse.

Help Tips: Our Contact Us page is protected by google reCAPTCHA. Please check it out.

Google's reCAPTCHA v3

In October 2018, Google introduces reCAPTCHA v3, which helps you detect abusive traffic on your website without any user friction. It returns a score (1.0 is very likely a good interaction, 0.0 is very likely a bot) based on the interactions with your website and provides you more flexibility to take appropriate actions.

Getting Started

In this post I will show you how to integrate reCAPTCHA v3 into a website with Node.js backend.

Creating a Simple Subscription Form

First we need to create an HTML page with a simple form where we need to integrate reCAPTCHA v3.

reCAPTCHA Simple Form

Just copy and paste the following example code to create a simple subscription form with HTML.

Example

HTML Online Editor
<!DOCTYPE html> <html> <head> <title>Simple Subscription Form</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h2>Simple Subscription Form</h2> <form> <label>Email Address:</label> <input type="email" id="uEmail"> <button type="button">Submit</button> </form> <script> $(document).ready(function(){ $("button").click(function(){ $.post("/test-mail",{ email: $("#uEmail").val(), },function(res){ alert(res); }); }); }); </script> </body> </html>

Registration

Now get credentials for your website. Lets go to https://www.google.com/recaptcha/intro/v3.html and click on Admin console button.

reCAPTCHA Registration

You'll get to "Register a new site" form where you should provide the following parameters:

  1. Label - Just a name of the setup
  2. reCAPTCHA type - Choose reCAPTCHA v3
  3. Domains - Add a list of domains (include localhost for testing) where you need to integrate reCAPTCHA v3.
  4. Owners - Add a list of email address who can control your reCAPTCHA v3 setup.
  5. Accept the reCAPTCHA Terms of Service - Accept it
  6. Send alerts to owners - Tick this box
  7. Now, click on submit button.
Register a new site

After submitting the "Register a new site" form, you'll get to "Adding reCAPTCHA to your site" form where you will get your SITE KEY and SECRET KEY.

  1. SITE KEY - Should be used in all your HTML page (client-side) where you need to integrate reCAPTCHA v3. This key is visible to everyone.
  2. SECRET KEY - Should be used in your index.js (server-side) main file.
Adding reCAPTCHA to your site

Now we are done with Registration.

Implementing reCAPTCHA v3 in Client-Side

To implementing reCAPTCHA v3 in Client-Side on your page is to include the necessary JavaScript resource to your HTML Page

  1. Load the JavaScript API to your "simple subscription form".

    HTML Online Editor
    <script src="https://www.google.com/recaptcha/api.js?render=YOUR-SITE-KEY"></script>

    Note: Replace 'YOUR-SITE-KEY' with your actual SITE KEY

  2. Call grecaptcha.execute on each action you wish to protect

    HTML Online Editor
    <script> grecaptcha.ready(function() { // do request for recaptcha token // response is promise with passed token grecaptcha.execute('YOUR-SITE-KEY') .then(function(token) { // add token value to form myToken = token; }); }); </script>

You are done with the client-side. Your final client-side code for "simple subscription form" is as follows

Example

While posting email address to the server you have to send the recaptcha token as well.

Note: Replace 'YOUR-SITE-KEY' with your actual SITE KEY

HTML Online Editor
<!DOCTYPE html> <html> <head> <title>Simple Subscription Form</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://www.google.com/recaptcha/api.js?render=YOUR-SITE-KEY"></script> </head> <body> <h2>Simple Subscription Form</h2> <form> <label>Email Address:</label> <input type="email" id="uEmail"> <button type="button">Submit</button> </form> <script> var myToken; $(document).ready(function(){ $("button").click(function(){ $.post("/reCAPTCHA-test-mail",{ email: $("#uEmail").val(), token: myToken },function(res){ alert(res); }); }); grecaptcha.ready(function() { // do request for recaptcha token // response is promise with passed token grecaptcha.execute('YOUR-SITE-KEY') .then(function(token) { // add token value to form myToken = token; }); }); }); </script> </body> </html>

Implementing reCAPTCHA v3 in Server-Side

To implementing reCAPTCHA v3 in Server-Side, you have to add the following npm packages to your index.js file:

API request should contain the following parameters:

POST ParameterTypeDescription
secretKeyRequiredSpecifies the SECRET-KEY given to you.
tokenRequiredSpecifies the user response token provided by the reCAPTCHA client-side integration on your site.
remoteIpOptionalSpecifies the user's IP address.

Example

Note: Replace 'YOUR-SECRET-KEY' with your actual SECRET KEY

Node.js Compiler
var express = require("express"); var rp = require("request-promise"); var bodyParser= require("body-parser"); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({limit: '5mb', extended: true})); app.get("/simple-form", function(req, res){ res.sendFile(__dirname +"/simple-form.html"); }); app.post("/reCAPTCHA-test-mail", function(req, res) { const secretKey = "YOUR-SECRET-KEY"; var token = req.body.token var email = req.body.email; var uri = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + token; var options = { method: 'POST', uri: uri, json: true }; if (token) { rp(options) .then(function(parsedBody) { if (parsedBody.success && parsedBody.score > 0.1) { // Save user email address to your database res.send("Success - You are human"); } else { res.send("Failed - You are bot"); } }) .catch(function(err) { res.send("Error - request Failed"); }); } else res.send("Error - Token Failed"); }); app.listen(8000, function(){ console.log("port is listening to 8000"); });

API response

The API response is a JSON object.

JSON Response
{ "success": true|false, "challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ) "hostname": string, // the hostname of the site where the reCAPTCHA was solved "error-codes": [...] // optional }

Error code reference

Error codeExplanation
missing-input-secretThe secret parameter is missing.
invalid-input-secretThe secret parameter is invalid or malformed.
missing-input-responseThe response parameter is missing.
invalid-input-responseThe response parameter is invalid or malformed.
bad-requestThe request is invalid or malformed.
timeout-or-duplicateThe response is no longer valid: either is too old or has been used previously.

The following image shows that the reCAPTCHA v3 is add the our "simple subscription form".

Form with reCAPTCHA v3

Now lets test this form

Testing the simple subscription form

Things to be Noted

  • Each reCAPTCHA user response token is valid for two minutes, and can only be verified once to prevent replay attacks.
  • reCAPTCHA v3 returns a score (1.0 is very likely a good interaction, 0.0 is very likely a bot). Based on the score, you can take variable action in the context of your site.
  • A reCAPTCHA key is normally tied to a set of individual domains or package names
    Specified domainWebsite domainWill reCAPTCHA work?
    yoursite.comyoursite.comYes
    www.yoursite.comYes
    subdomain.yoursite.comYes
    subdomain.yoursite.com:8000Yes

Reminder

Hi Developers, we almost covered 5% of Node.js Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in Node.js.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author