Two-Factor Authentication with Node.js

By  on  
Google Authenticator

There are a variety of strategies for protecting your important online credentials.  We often hear about password managers and generators, but for me, the more important strategy is using two-factor authentication (2FA).  Passwords can be guessed, phone numbers can be spoofed, but using two-factor authentication essentially requires that user be in possession of a physical device with an app like Google Authenticator, loaded with a secret key for the given app, which provides an extra layer of security.

I didn't use to take two-factor authentication seriously, until someone stole my domain name and tried to launder it to a safe haven for thieved domains.  While I don't know how exactly they did it, I'm fairly certain they got access to my email address, created filters so I wouldn't see the emails, etc.  Had I used two-factor authentication, neither my email or GoDaddy accounts could have been accessed.  Or you could take it from Cody Brown who had $8,000 in cryptocurrency stolen in minutes because the vendor used phone number validation to allow transactions to be approved.  Today I use two-factor authentication for all of my important email, work, and financial accounts.

Since I use 2FA so often, I wanted to see how the process is managed by a developer for its users.  That would include generating the secret key, creating its QR code representation, scanning the code into Google Authenticator (done by the user), and then validating that GA-given code against the user's key.  I found an easy to use Node.js library, speakeasy, to do so!

Setup Step 1:  Generate a Secret Key

Assuming you've installed speakeasy via npm install speakeasy, the two-factor authentication setup is kicked off by generating a unique secret key for the user:

var speakeasy = require('speakeasy');

var secret = speakeasy.generateSecret({length: 20});
console.log(secret.base32); // Save this value to your DB for the user


This secret key should be stored with the user's record in your database, as it will be used as a reference to validate 2FA codes in the future.

Setup Step 2:  Generate a QR Image

Apps like Google Authenticator allow users to scan a QR code or enter the text key.  Scanning an image is much faster so offering the QR code will be of great convenience to your user:

var QRCode = require('qrcode');

QRCode.toDataURL(secret.otpauth_url, function(err, image_data) {
  console.log(image_data); // A data URI for the QR code image

QRCode.toDataURL provides an image data URI that you can use for the img src attribute.  If you aren't familiar with a QR code, it will look something like this:

QR Code

User Step 1:  Scan the QR Code / Add Site to Authenticator

At this point the user should have opened Google Authenticator (or Authy, etc.) and scanned the QR code; an entry for your web app will be added within the device's app.  From this point forward, whenever the user wants to log in (or perform any action you'd like to be protected), your system should recognize the user wants to use 2FA and you should require they enter the token from their app.

Google Authenticator

For the purposes of debugging, you can get what should be the user code value at a given time via:

// Load the secret.base32 from their user record in database
var secret = ...

var token = speakeasy.totp({
  secret: secret,
  encoding: 'base32'

User Step 2: Providing the Token / Validating the Token

When your web app prompts the user for the current 2FA token, and the user provides a 6 digit token, the web app must validate that token:

// This is provided the by the user via form POST
var userToken = params.get('token');

// Load the secret.base32 from their user record in database
var secret = ...

// Verify that the user token matches what it should at this moment
var verified = speakeasy.totp.verify({
  secret: secret,
  encoding: 'base32',
  token: userToken

If the token matches, the user can be trusted; if the token does not match, the web app should prompt the user to try again.  Remember that Authenticator provides a new token every {x} seconds so an incorrect token shouldn't immediately raise a red flag; the token may have simply expired by the time the user submitted the form.

Live Demo

The speakeasy developers have created a live speakeasy 2FA demo for you to play with so that you can understand the steps involved from both a user and a developer perspective.

This post is only meant to be a brief, high level overview of implementing two-factor authentication -- please read the speakeasy documentation to get a more detailed explanation as well as learn about more specific 2FA options.  In an ideal world, two-factor authentication would be enabled by default for most logins, however it can be confusing for the majority of web users (think of the very non-technical user), so I can understand why 2FA is considered an extra security measure for now.  A big thanks to speakeasy's developers for their easy to use Node.js library, awesome documentation, and simple demo!

Recent Features

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

Incredible Demos

  • By
    Create a Clearable TextBox with the Dojo Toolkit

    Usability is a key feature when creating user interfaces;  it's all in the details.  I was recently using my iPhone and it dawned on my how awesome the "x" icon is in its input elements.  No holding the delete key down.  No pressing it a...

  • By
    Submit Button Enabling

    "Enabling" you ask? Yes. We all know how to disable the submit upon form submission and the reasons for doing so, but what about re-enabling the submit button after an allotted amount of time. After all, what if the user presses the "stop"...


  1. Another easy way to implement 2-Factor Authentication is to hand off the authentication work to something like AWS Cognito. Not only can it handle 2FA, but it can take care of all your authentication needs, freeing you up to focus on other things.

  2. Oleks

    Thanks for the nice article! I created some simple docker service for my project based on this info for my projects, somebody could find useful (no qr code scanning though):

  3. David

    Hi! Is there a good guide you’d recommend for generating backup codes? They don’t seem to be part of the TOTP spec from what I understand.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!