• Recipes
  • Engineering
  • Send SMS on page view with Segment, Twilio Serverless, and Javascript

Send SMS on page view with Segment, Twilio Serverless, and Javascript

Engineering Startup Beginner

Made by Lizzie Siegle

Want to see Segment in action? In this recipe, we’ll explore the fundamental use of Segment: collecting customer data. You’ll learn how to attach your website as a source and a Twilio Serverless function as a destination to connect page views on your website directly to your phone via SMS.
What do you need?
  • A Twilio Account
  • A Segment Workspace
Increase conversion with personalized lifecycle campaigns
Collect data once with Segment and send it any tool you use. No more tedious integrations. No more engineering resources wasted.
Start with Segment

NOTE: This recipe was originally written on the Twilio Blog.

Do you prefer learning via video? Check out this TikTok summarizing this tutorial in under one minute!

To follow along with this post, you need three things:

Add a Segment Source

First off, we need to add a website as a source in the Segment app. In Segment, you create a source (or more than one!) for each website or application you want to track. A source provides data to Segment to use. To make a source, create and go to your Segment Workspace and click Sources on the left.

lizzie-img1

From your List of Sources, click the blue Add Source button.

lizzie2

From the Catalog of Sources, under Website select JavaScript followed by Add Source.

lizzie3

In Source setup, give your Source a name–for example, Personal Website. You can leave Labels blank, and then add the Website URL.

lizzie4

After clicking Add Source, Segment will provide you with code similar to the one below to include in your HTML file's <head> element.

lizzie5

This code adds Segment's Analytics.js library so you can send data from your website to Segment, and from there to any Destination. Add this to your website's <head> element. 

You can check that Analytics.js is working with your website by inspecting your website and checking that the analytics variable exists–this can be done both locally and also on a deployed site.

lizzie6

Now this tutorial will use Twilio Functions as a Destination.

Make Twilio Send a SMS

The Serverless Toolkit is CLI tooling that helps you develop locally and deploy to Twilio Runtime. The best way to work with the Serverless Toolkit is through the Twilio CLI. If you don't have the Twilio CLI installed yet, run the following commands on the command line to install it and the Serverless Toolkit:

npm install twilio-cli -g

twilio login

twilio plugins:install @twilio-labs/plugin-serverless

Create your new project by running:

twilio serverless:init segment-site-visitor-detector –template=blank

cd segment-site-visitor-detector

Open the `.env` file, fill in your AUTH_TOKEN and add an environment variable for your personal phone number. In this blog post, the API key is called `MY_PHONE_NUMBER`.

Add a new file inside the \functions directory called `segment.js` containing the following code:

exports.handler = function(context, event, callback) {

  const client = context.getTwilioClient();

  let body = event.request.headers.viewed;  

let to = context.MY_PHONE_NUMBER;

let from = 'YOUR-TWILIO-NUMBER';

console.log(`body ${body}`);

client.messages

.create({ body, to, from })

.then((message) => {

  console.log(`SMS successfully sent, ${message.sid}`);

return callback(null, `Success! Message SID: ${message.sid}`);

  })

  .catch((error) => {

    console.error(error);

    return callback(error);

  });

};

This code returns an initialized Twilio REST Helper Library, gets the inbound request (which will contain the viewed header we will soon set in the Segment console) and sets it as a variable called body, makes the to and from variables (your personal phone number hidden as an environment variable, as well as a Twilio number used to send the message), and then sends an outbound text message when the Twilio Function is hit (when the website is viewed.) From the root directory, run `twilio serverless:deploy` and copy the URL ending in `/segment`.

Set Twilio as a Destination

Back in your Segment Console beneath the blue Copy Snippet button, click the blue Add Destination button.

lizzie7

Search the Destinations Catalog for webhook and select Webhooks.

lizzie8

Then click the blue Configure Webhooks button.

lizzie9

Select a data source to be your website and to setup the webhook, we give it a Destination name, followed by clicking Save.

lizzie10

Then select Webhooks (max 5) and enable the toggle next to Setup Guide.

lizzie11

Put in your Function URL ending in `/segment` and set a header to be something like you see below.

lizzie12

Click the blue Save button and tada! You will get a text message saying "site has been viewed!" whenever someone visits your website.

lizzie13

Alternatively in your Segment console, you can go to the Debugger section of your Source and see when someone visits the site as well.

lizzie14

Wrapping up

While getting a text message every time your web page is viewed might be overwhelming if your site is high-traffic, this example shows how Segment easily turns customer interaction events into something you can act upon. With an incredible library of pre-built integrations you'll find it extremely easy to send your data to a myriad of tools, as well as plugging in your own custom functions to enrich your customer interactions.