How to Authenticate Mobile Number with Twilio using Express/NodeJS?

How to Authenticate Mobile Number with Twilio using Express/NodeJS?

Most of the enterprise grade applications provide multiple ways to create an account on their service. This includes Login with Google, Login with SMS, etc. These authentication methods provides win-win situation for both customers and system admins. But How?

For a customer, Login with Google / SMS helps to quickly sign up to service within few seconds (max of 10 seconds). For the system admins, it gives a confidence that their users are authentic as they do not need to do many stuffs to ensure their authenticity (Sending confirmation link via email and asking the user to confirm with an hour, etc. ).

In this article, let’s explore How to authenticate a user with mobile number using Twilio?

5 Simple Steps

  1. Create a Twilio account

  2. Configuration & Setup

  3. Send the SMS code

  4. Validate the SMS code

  5. Validate with status

Create a Twilio account

Head to Twilio and signup for an account. After your signup, navigate to Twilio Console and get your Account SID, Auth Token.

Create a Verify Service by Verify > Services > Create new

Navigate to General section and get your Service SID

Configuration & Setup

In the env file of your NodeJS project, add the following environment variables.

TWILIO\_ACCOUNT\_SID=<Your Twilio Account SID>  
TWILIO\_AUTH\_TOKEN=<Your Twilio Auth Token>  
TWILIO\_VERIFY\_SERVICE\_ID=<Your Service ID>

Replace Account SID, Auth Token and Service ID with the ones you took from Twilio console.

Let’s put on development shoes

Send the SMS code

Add Twilio package

Add twiliopackage to your project by running either of the following commands

npm install twilio

or

yarn add twilio

Create an endpoint in your project to send a verification code (Eg. /signup/sendsms/:phone )

Note: From the client side, while calling this endpoint, replace :phone with the actual phone number

Copy the below code and paste in your file

// Your other imports

const accountSid = process.env.TWILIO_ACCOUNT_SID;  
const authToken = process.env.TWILIO_AUTH_TOKEN;  
const serviceSid = process.env.TWILIO_VERIFY_SERVICE_ID;

const client = require('twilio')(accountSid, authToken); // Import Twilio

// Your other endpoints

router.post("/signup/sendsms/:phone", function (req, res, next) {  
    `client.verify.v2.services(serviceSid)  
    .verifications  
    .create({to: req?.params?.phone, channel: 'sms'})  
    .then(verification => console.log(verification.status));`

});

This would have triggered an SMS to the phone number you passed in the url.

Validate the SMS code

Instead of we storing and verifying the OTP code, Twilio handles this in an extra-ordinary way. Create another endpoint, to validate the OTP received by the user.

router.post("/signup/sendsms/:phone/:code/verify", function (req, res, next) { `client.verify.v2.services(serviceSid)  
    .verificationChecks  
    .create({to: req?.params?.phone, code: req?.params?.code})  
    .then(verification_check => {   
        console.log(verification_check.status))  
    }  
});`

Pass the phone number and the OTP code to this endpoint and get it validated against Twilio. The above code will return the following response.

Validate with status

{  
    "sid": "VEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",  
    "service_sid": "VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",  
    "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",  
    "to": "+11111111111",  
    "channel": "sms",  
    "**status**": "**approved**",  
    "valid": true,  
    "amount": null,  
    "payee": null,  
    "date_created": "2022-07-22T20:00:00Z",  
    "date_updated": "2015-07-22T20:00:00Z"  
}

The status will be “approved” if the phone number and the OTP, provided by user are correct and will remain in “pending” state if it does not match.

Hope you find this blog crisp and useful.

Subscribe to our newsletter to receive more such insightful articles that get delivered straight to your inbox.

Happy Coding