Two Factor Authentication

Implement Two Factor Authentication (2FA) With Node JS Using Speakeasy

In this post, I want to explain about Implementation of Two Factor Authentication with Node.js.

Two Factor Authentication became more important nowadays for security purposes, Most of the sites which handle money or anything related to payment using two-factor authentication to make sure they are having right authenticated users on their website.

Here we are going to look into two-factor authentication implementation of Node.js using speakeasy.


speak easy

Description about Speakeasy available on the website.

Speakeasy is a one-time passcode generator, ideal for use in two-factor authentication, that supports Google Authenticator and other two-factor devices.

As it states, It is a one-time passcode generator and we should send that passcode to the user via email or SMS. When the user enters the passcode using speakeasy we can validate the one-time password and if password matches we can validate the user. Speakeasy makes implementation of two-factor authentication easy one.

This blog post will help anyone who wants to enable two-factor authentication in their application.

Node.js Implementation of SpeakEasy

First, You need to save speakeasy node package into your application and in node we can use npm.

npm install –save speakeasy

The package will get installed in your node module directory. Next step will be including it in your node application.

//Include speakeasy into your node file.
var speakeasy = require("speakeasy");

//Generate a secret key First.
var secret = speakeasy.generateSecret({length: 30});


//using speakeasy generate one time token.
var token = speakeasy.totp({
secret: secret.base32,
encoding: 'base32',


The output of above program will be something like this.


Now, One-time password token got generated and now you can send the token to the corresponding mobile number or through the email.

In the application standpoint, You should not store the token generated instead store the 30-digit secret key, in this case, we can alter the size of secret key based on your application need. Store the secret key against the user id in your application database.

//This method can be used to verify the one time password entered by the user.
var tokenValidates = speakeasy.totp.verify({
secret: secret.base32,
encoding: 'base32',
token: '179772',
window: 6

console.log(tokenValidates); //It returns true since it matches the above OTP and secret key combination.<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>


So we should make sure that secret key and otp validation returns true and if it return true then you can successfully authenticate else it will return false.

It is the very basic use case of implementing speakeasy with node and you can check more on their website. I personally found it useful so writing it as a blog.