Serverless Phone Verification with Twilio Verify and Twilio Functions

June 15, 2020
Written by

Serverless Verify

Security is at the top of everyone’s mind and phone verification is a simple way to secure your application and help prevent bot accounts. Sending a one-time password to a user's phone to validate they have possession is a common security tool used when people sign up for a product or give you their phone number for the first time.

Confidence in your users’ phone numbers decreases fraud and increases reliability of notifications. Let’s take a look at how to verify phone numbers from a web application using Twilio's serverless functions and the Twilio Verify API.

Prerequisites to adding Twilio Verify to your application

To code along with this post, you’ll need:

Make note of your Service SID (starts with VA)

Verify Service SID

We don't want to store our API Keys directly in our front-end application because this can lead to leaked API Keys. For added security we'll need a backend server that will talk to the Verify API. We'll do this with Twilio Functions.

Install the Twilio CLI for your operating system and login to your Twilio account:

twilio login

Next, install the Serverless toolkit. This will help us clone a verification template and easily deploy our project.

# Install the Serverless plugin
twilio plugins:install @twilio-labs/plugin-serverless

# See a list of available commands:
twilio serverless

Initiate a new project using the Verify function template:

twilio serverless:init verify-sample --template=verify && cd verify-sample

Edit the included .env file and add your VERIFY_SERVICE_SID as a variable (find or create a Verify service in the console). Make sure the ACCOUNT_SID and AUTH_TOKEN are populated, the Serverless toolkit will configure those if you ran twilio login. Your .env file should look something like this:

ACCOUNT_SID=ACxxx
AUTH_TOKEN=g41xxx

VERIFY_SERVICE_SID= VAxxx

Run and test the application locally

Start the application locally:

twilio serverless:start

Navigate to http://localhost:3000/index.html and check out your new user verification application!

otp project screenshot

Select SMS and enter your phone number. You should receive a verification at the phone number you provide. Entering the right code in the modal will show verification success:

verification success view

How does Twilio Verify work?

This project has two functions: one to start and one to check verifications.

  • Our start function will send a one-time passcode (OTP) to the end user's phone or email. Twilio Verify handles generating the OTP, all we need to provide is the contact method.
  • Our check function will verify that the OTP is the same one we sent to the user. Twilio verify handles storing and validating the OTP so you don't have to.

Here's a look at how we're starting a verification:

client.verify.services(service)
    .verifications
    .create({
      to: to,
      channel: channel,
      locale: locale
    })
    .then(verification => {
      console.log(`Sent verification: '${verification.sid}'`);
      response.setStatusCode(200);
      response.setBody({
        "success": true
      });
      callback(null, response);
    });

This initiates a verification to the user with a specified channel and locale. The channel can be one of sms, call, or email*. The locale will determine the verification language. Learn more about supported languages here.

*Note: the email channel requires some additional configuration. Follow these instructions to set up your Verify service to send emails.

Here's a look at how we're checking a verification:

client.verify.services(service)
    .verificationChecks
    .create({
      to: to,
      code: code
    })
    .then(check => {
      if (check.status === "approved") {
        response.setStatusCode(200);
        response.setBody({
          "success": true,
          "message": "Verification success."
        });
        callback(null, response);
    });

This calls the VerificationCheck endpoint and validates that the status is approved. If the verification code is incorrect, the response status will be pending.

Deploy your Twilio serverless functions

The front end interface of this template illustrates the capabilities of the the Verify API, but the two functions can serve a longer term, even production-ready use. Deploy your functions with the following command:

twilio serverless:deploy

You'll see 3 URLs, with a prefix like verify-sample-1234-dev.twil.io (the numbers will be different). Navigate to the index file (URL shown under Assets) and test out your verifications again.

deployed serverless functions

Any time you make changes to your code locally you can run twilio serverless:deploy again to update the hosted function. Use the deployed functions from your existing application to send and check verifications.

Next Steps

With just two API calls and one web page, you’ve now validated that a user has a real phone number or email and access to that contact channel, which will help prevent a lot of fraudulent accounts and ensure that your users can receive other text or voice notifications from your app if they opt in to those later.

You can check out the full code on Github or deploy your own version in less than 2 minutes with Twilio's Code Exchange. Looking for a mobile version? Check out phone verification in React Native.

If you have any questions about user verification or account security, please leave a comment or contact me on Twitter.