Sunday, March 07, 2021

Integrating Google Recaptcha with ExpressJS

Fighting spam and bots over the internet is a never-ending problem and that's why companies like Cloudflare kick-off their journey from the building/contributing honeypot to IPO. However, there are other few ways to prevent spam API calls, brute force attacks and they are solving captchas, and Google is one of the pioneers in providing better user experience plus spam prevention techniques. There are other online services such as Funcaptcha captcha as a service for SaaS companies.

Today, let's see about implementing Google ReCaptcha with expressjs Node server as middleware and rendering them in forms.

Integrating Google Recaptcha with ExpressJS
Integrating Google Recaptcha with ExpressJS 


npm install express-recaptcha --save


Signup for Google Account and click here to create new Recaptcha keys and specific to Version 3. Enter the domain including localhost for testing purposes and grab the Site key and Secret key to access Recaptcha APIs from Nodejs backend.

var Recaptcha = require('express-recaptcha').RecaptchaV3;

var recaptcha = new Recaptcha('SITE_KEY', 'SECRET_KEY');

Frontend Client setup

As the client-side is so specialized and varies from ReactJS, Vue, or plain vanilla javascript, I recommend you to follow Google docs to implement them.

Server Validation

As this blog post covers primarily server validation logic, ExpressJS provides excellent integration with middleware where the Recaptcha validation can be added to the routes before even route logic executes.'/', recaptcha.middleware.verify, function(req, res){
  if (!req.recaptcha.error) {
    // success code
  } else {
    // error code
As mentioned before, the middleware function that contains Recaptcha verification executes first and the results are attached to the request object for implementing the business logic. One could use the req.recaptcha.error object to verify if the Recaptcha request is successful.

Req.recaptcha object

  error: string, // error code (see table below), null if success
  data: {
    hostname: string, // the site's hostname where the reCAPTCHA was solved
    score: number, // the score for this request (0.0 - 1.0)
    action: string // the action name for this request (important to verify)
Feel free to follow the npm package of Express Recaptcha for more details and customization logic.

For bugs/hugs, feel free to comment below. Share is care.


Post a Comment

feel free to post your comments! Don't Spam here!