login page with reCAPTCHA v2 in Node.js

A user login page using Google reCAPTCHA v2

Today we’re going to take a look at how to setup reCAPTCHA v2 with Node.js and Express.js. It took me a while to figure out the process, and I wanted to pass along these important steps to hopefully save you some time designing your project. I’m not going to go into every nitty-gritty detail, but I will explain the basics, which will be plenty to get reCAPTCHA functional in your project.

For my setup I used recaptcha2 package, which is what I will demonstrate in this posting. If you wish to utilize a different version of reCAPTCHA than what I’m using, please review the Google reCAPTCHA docs. Note: In this tutorial, I will assume that you have an existing Express.js application in which you are wanting to setup reCAPTCHA.

Setup reCAPTCHA v2

The first thing we will need to do is setup our Site Key and Secret Key. These are found in the Google reCAPTCHA Admin Console:

  1. First, let’s log in to the Google reCAPTCHA Admin Console
    • At the top of the page, click ‘v3 Admin Console’ (Note: Fear not; we ARE implementing v2 in this tutorial).
  2. Next, click the ‘+’  (found in the upper right of the Admin Console page) to create a new reCAPTCHA.
  3. Add a label (i.e. “yourwebsitename.com“)
  4. Select reCAPTCHA type (‘select reCAPTCHA v2’ option)
    1. Select the ‘”I’m not a robot” Checkbox’ radio button
  5. Under Domains, add the web domain where your web application will live (i.e. “www.example.com“)
  6. Next, check (select) the Accept the reCAPTCHA Terms of Service checkbox.
  7. You may choose to be alerted by Google if there are issues, such as suspicious activity on your site. Send alerts to owners should be selected by default, but it’s up to you how you…
  8. And finally, click “Submit”

Retrieve reCAPTCHA Keys

Now we have the keys! Upon setup of reCAPTCHA, Google will issue two different keys, which we will need to copy and paste into our project. After navigating away from the form completion page, we may also find these by accessing our project (in the Admin Console) and clicking the cog/”Settings” icon.

Next, let’s create a .env file in the root of our project. Inside this file, add the generated sitekey and secretkey as follows:

SITEKEY=[Your site key]
SECRETKEY=[Your secret key]

Note: Remember to save as we go! 😀

Setting up the recaptcha2 npm Package

As mentioned above, the package we are going to use in this tutorial is the recaptcha2 npm package. Install the package by, after navigating to your project, typing the following into your console:

npm i recaptcha2

After the recaptcha2 package has been successfully installed in your existing express app, you will need to add the following code to your app.js:

const reCAPTCHA = require('recaptcha2');

const recaptcha = new reCAPTCHA({
  siteKey: process.env.SITEKEY,
  secretKey: process.env.SECRETKEY,
});

The above code can be added near the top of your app.js/index.js/routes.js…

Render reCAPTCHA data in a Pug.js Template

I really like to use Pug.js (formerly “Jade”) for my templating engine while working with Express. Let’s add the reCAPTCHA code to our pug.js template, as follows:

First, we will send the data to our template using a GET route in our Express.js app (again, our index.js/app.js…). We will be using the /login GET route, as follows:

app.get('/login', (req, res) => {
  res.render('login', {
    recaptcha: recaptcha.formElement(),
  });
});

Now, switch over to the Pug.js template. I will explain how to do this a little further below, but the following pug.js login template is needed to add the Google reCAPTCHA api script:

 script(src="https://www.google.com/recaptcha/api.js" async defer)

After adding the above script (again, that is explained just below this step), we can successfully use the ‘recaptcha’ data that is passed to the pug template. We just need to add the following line of code to our login form to see the reCAPTCHA. Note: we are using an unescaped pug attribute

p!= recaptcha

Ok, so here is our final example Pug.js template. This is just an example of of how our completed login may look (note the code comments):

extends layout.pug 

block content
  //- Add script element here:
  script(src="https://www.google.com/recaptcha/api.js" async defer)
  .header 
    h1 Exclusions DB
  div.main-container
    h2 Login
    form.login-form(role='form', action="/login",method="post")
      //- Place recaptcha code here:
      p!= recaptcha 
      .form-element
        label.form-label(name='username') Email
        br
        input.form-control(type='text', name="username", placeholder='Enter Username' required)
        be
      .form-element
        label.form-label(name='password') Password
        br
        input.form-control(type='password', name="password", placeholder='Password' required)
        br
        br
      .form-button
        button.btn.btn-default(type='submit') Submit
  

Now we can see the reCAPTCHA on our login page!

final login page using recaptcha

login page using reCAPTCHA v2

Wow…Looking pretty good!

Setup the /login POST Route, adding reCAPTCHA Validation

In order to log in successfully, there is still one more simple step we’ll need to complete. We will need to setup a /login POST route, like so, within our index.js/app.js:

app.post('/login', (req, res) => {
    recaptcha.validateRequest(req) // recaptcha2 method
      .then(() => {
        res.json({formSubmit:true}); // Validated and secure
      })
      .catch((err) {
        // Unvalidated and unsecure
        res.json({
          formSubmit: false,
          errors: recaptcha.translateErrors(err)
       })
    });
});

Now this should be functioning properly for us. If reCaptcha has not been satisfied, the “user” (bot) logging in will not be able to proceed. Otherwise, human users are welcome!

Closing Remarks

Well, that should just about do it! Now you know how easy it can be to setup reCAPTCHA v2 with Node.js and Express.js. Following the same process as above, you may also choose to implement this in your /register route.

I hope this short tutorial was a help to you. If so, I’d really like to hear from you. Please feel free and happy to leave a comment–or question. Until next time, happy coding!