How to Implement 2FA with Twilio Verify in Node

April 24, 2023
Written by
Felistas Ngumi
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Twilio Verify v2 in Node.js Header

In today's digital world, security is paramount, and two-factor authentication (2FA) is becoming increasingly important for securing user accounts. Two-factor authentication provides an additional layer of security beyond just a username and password, making it much more difficult for hackers to gain access to user accounts. Twilio Verify is a powerful API that makes implementing 2FA in your Node.js application straightforward and secure.

One of the most significant benefits of using Twilio Verify for implementing 2FA is its ease of use. Twilio Verify provides a simple API that can be easily integrated into your Node.js application, and with just a few lines of code, you can implement 2FA for your users. This makes it an ideal solution for developers who want to add an extra layer of security to their applications without spending a lot of time on implementation.

In this article, I'll provide a step-by-step guide on how to implement 2FA with Twilio Verify in Node.js, including how to generate a Twilio API key and how to integrate Twilio Verify into your application. I'll also provide tips and best practices for ensuring the security of your users' accounts. By the end of this article, you will have a solid understanding of how to implement 2FA with Twilio Verify in your Node.js application, and how to ensure that your application is secure and reliable.

Prerequisites

Twilio Project Setup and Sandbox Activation

After creating and verifying your account on Twilio, navigate to the Twilio Console and create a new account, stating the Twilio project you would like to use, in this case select Verify and select Javascript as the preferred language to use. In the resulting dashboard, take a note of the ACCOUNT SID and AUTH TOKEN. You’ll need them later when building out the code.

Next, navigate to the Verify page by clicking Explore Products and selecting Verify from the list of products.

Verify product page on Twilio console

Click on the Create new button to create a new service. Enter node-verify as the Friendly name select SMS as the preferred verification channel as shown below.

Create new service modal on Verify product page

Once filled out, click the Continue button and enable Fraud Guard.


Ensure to enable Fraud Guard to block fraudulent messages from being sent to your account that will result in more charges to your account.

For more info, take a look at our docs on Fraud Guard: Verify Fraud Guard

You’ll then be redirected to your new services Service settings page. Copy and paste the Service SID and store it in a safe place as this will be needed in the next sectio

Service settings of new Twilio Verify service

Project Setup

Enter the following commands in your preferred terminal to set up your local development environment:

bash
mkdir demo && cd demo && touch verify-node.js
npm init -y

The above commands create a folder called /demo and our working files, verify-node.js for our project code. The last command will then initalize the Node.js project.

Next enter the following commands to install the Twilio and dotenv npm packages and to create a .env which will hold your environment variables:

npm install twilio dotenv
touch .env

In your preferred code editor, navigate to the /demo folder and add the following configurations in the .env file. Replace the XXXX placeholders with their respective keys from the previous section.

TWILIO_ACCOUNT_SID=XXXX
TWILIO_AUTH_TOKEN=XXXX
TWILIO_VERIFY_SERVICE_SID=XXXX

Next, add the following code in the verify-node.js file:

require('dotenv').config();

const client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);

const readline = require('readline').createInterface({
   input: process.stdin,
   output: process.stdout
});

function sendVerificationCode(phoneNumber) {
   return client.verify.v2.services(process.env.TWILIO_VERIFY_SERVICE_SID)
       .verifications
       .create({
           to: phoneNumber,
           channel: 'sms'
       }).then((data) => {
           return data.status;
       });
}

function checkVerification(phoneNumber, code) {
   return client.verify.v2.services(process.env.TWILIO_VERIFY_SERVICE_SID)
       .verificationChecks
       .create({
           to: phoneNumber,
           code: code
       }).then((data) => {
           return data.status;
       });
}

async function verifyUser(phoneNumber) {
   const status = await sendVerificationCode(phoneNumber);
   if (status === 'pending') {
       readline.question('Enter code: ', code => {
           checkVerification(phoneNumber, code)
               .then((data) => {
                   if (data === 'approved') {
                       readline.write('User verified');
                       readline.close();
                   } else {
                       readline.write('User not verified');
                       readline.close();
                   }
               });
       });

   }
   else {
       return 'Error sending verification code';
   }
}

verifyUser('<your_phone_number>');

The code above uses the Twilio API to send a verification code via SMS to a specific phone number and then verifies the user by prompting them to enter the code they received. The script reads Twilio API account details from environment variables using the dotenv module and uses the Twilio Verify service to create and check verifications. It prompts the user to enter the verification code using the Node js readline module, then checks the code entered by the user against the code sent by Twilio. If the codes match, the user is considered verified and the script prints "User verified" to the console; otherwise, it prints "User not verified". The phone number to be verified is passed as an argument to the function verifyUser(), which is an async function.

In a real world example, you will need to integrate this script with the frontend application instead of reading input from the terminal.

Testing out the demo

Before testing out the code, replace the <your_phone_number> placeholder with your number in E.164 format and save the file.

Now navigate back to your terminal and enter the following command to run the Node application:

node verify-node.js

Once entered, you’ll receive a verification code on your phone like so:

Verfication code on messages app of iPhone

 

Enter the code on your terminal and hit enter. You’ll then receive a confirmation on the terminal saying User verified:

Terminal displaying that user has been verified after entering verification code

Wrapping up

In this tutorial, you have learned how to use Twilio Verify to implement 2FA in Node.js with minimal lines of code. By following the step-by-step instructions, you can quickly and easily set up phone number verification for your application, enhancing its security and preventing unauthorized access.

It's important to note that this tutorial only covered the backend implementation of 2FA with Twilio Verify. In a real-world scenario, you would typically implement a Graphical User Interface (GUI) for users to input the code received from Twilio Verify. This GUI would allow users to easily enter the verification code and complete the authentication process. Implementing a GUI for 2FA can greatly enhance the user experience, making the verification process more intuitive and user-friendly.

Overall, Twilio Verify is an incredibly useful tool for implementing 2FA in your applications. By following the steps outlined in this tutorial and implementing a user-friendly GUI, you can provide your users with a secure and easy-to-use authentication process.

Felistas is a Software Engineer who enjoys writing technical articles from time to time and loves solving problems through code.