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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...