Skip to main content

Using reCAPTCHA v3 with Node.js

Registration

First we need to get credentials for our website. Lets go to https://www.google.com/recaptcha/intro/v3.html and click on “Admin console” button.

reCAPTCHA v3 Home Page

You’ll get to “Register a new site” form where you should provide the following parameters:

  • Label — just a name of the configuration
  • reCAPTCHA type — you should select v3
  • Domains — yourdomain.com, www.yourdomain.com and localhost
Example site configuration

After submitting the form you will get your Site and Secret keys:

Site and secret keys

Site key will be put on your web page and will be visible to everyone.

Secret key should be passed as an environment variable to your backend server.

Integration

Lets create a simple web application using Node.js and Express.

mkdir recaptcha_v3 && cd recaptcha_v3
touch server.js
touch .env
mkdir public
touch public/index.html

npm init -y
npm install express body-parser dotenv isomorphic-fetch

Lets create a start script in package.json so that we will be able to run our server with npm start.

"scripts": {
"start": "node server.js"
},

Lets configure Express in server.js so that we can serve index.html from public.

const express = require('express');

const app = express();
const port = 3000;

app.use(express.static('public'));

app.listen(port, () => console.log(`Listening on port ${port}!`));

First thing is to add reCAPTCHA to your index.html page. Replace <SITE_KEY> with your value.

<script src="https://www.google.com/recaptcha/api.js?render=<SITE_KEY>"></script>

Then you need to get the token:

grecaptcha.ready(function() {
grecaptcha.execute('<SITE_KEY>', {action: 'demo'})
.then(function(token) {
// this token will be passed together with your data
});
});

In our example we will be sending JSON data to POST /send endpoint:

var data = {
hello: hello,
token: token
};
fetch('/send', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(data)
})
.then(...)

So, lets create a simple index.html with the following content:

<h1>reCAPTCHA v3 Demo</h1>
<input type="text" id="hello" value="Hello World" />
<button type="button" id="send_button">Send</button>
<hr>
<div id="result"></div>

<script src="https://www.google.com/recaptcha/api.js?render=6Lc7abAUAAAAAJt28TbC0dciNKqcHq4S_uMYBJgG"></script>
<script>
function showResult(text) {
document.querySelector('#result').innerHTML = text;
}

function handleClick(token) {
return function() {
var hello = document.querySelector('#hello').value;
var data = {
hello: hello,
token: token
};

fetch('/send', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(data)
})
.then(response => response.text())
.then(text => showResult(text))
.catch(error => showResult(error));
}
}

grecaptcha.ready(function() {
grecaptcha.execute('6Lc7abAUAAAAAJt28TbC0dciNKqcHq4S_uMYBJgG', {action: 'demo'})
.then(function(token) {
document.querySelector('#send_button').addEventListener('click', handleClick(token));
});
});
</script>

If you run npm start and open http://localhost:3000/ you’ll see the following page:

Example Page

Verification

On server side you need to verify the token using reCAPTCHA API.

Send POST request to the following URL with secret_key and token received from the client:

const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;

You need to add SECRET_KEY to .env file so that it can be read by Node.js process.

SECRET_KEY=6Lc7abAUAAAAAOQHz...

Below is the complete code for our Express endpoint:

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const fetch = require('isomorphic-fetch');

const app = express();
const port = 3000;

app.use(express.static('public'));
app.use(bodyParser.json());

const handleSend = (req, res) => {
const secret_key = process.env.SECRET_KEY;
const token = req.body.token;
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;

fetch(url, {
method: 'post'
})
.then(response => response.json())
.then(google_response => res.json({ google_response }))
.catch(error => res.json({ error }));
};

app.post('/send', handleSend);

app.listen(port, () => console.log(`Listening on port ${port}!`));

Result

If everything went well, you’ll see the following validation response:

Validation response

The following attributes are available in the response:

{
"success": true|false, // whether this request was a valid reCAPTCHA token for your site
"score": number // the score for this request (0.0 - 1.0)
"action": string // the action name for this request (important to verify)
"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
}

You need to check that request was successful, the score is in the acceptable range, the action is valid, etc.

For more information about the validation process and scores interpretation see https://developers.google.com/recaptcha/docs/v3#score

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...