SMS Notifications On Pageviews with Segment and JavaScript
Tags: segment, twilio, javascript, tutorial
Published: 2022-06-01 01:01:02

---
title: SMS Notifications On Pageviews with Segment and JavaScript
published: true
description: Learn how to send SMS notifications whenever a webpage is viewed using Twilio Segment, the Twilio Serverless Toolkit, and JavaScript.
tags: segment, twilio, javascript, tutorial
cover_image: https://twilio-cms-prod.s3.amazonaws.com/images/Copy_of_D03_Blog_Image_Round_2.width-1616.png
---
This blog post was written for [Twilio](https://www.twilio.com/) and [originally published on the Twilio blog](https://www.twilio.com/blog/sms-on-pageview-using-segment-serverless).

Twilio [acquired Segment last year to help developers unify customer data across every customer touchpoint](https://www.twilio.com/blog/twilio-acquires-segment). I held off on using Segment for a while because I thought Segment was only for businesses, but I learned recently that I, an indie developer, have a use case for it. Read on to learn how to use Segment and [Twilio Serverless](https://www.twilio.com/docs/labs/serverless-toolkit) to send SMS notifications when someone visits your website.

Do you prefer learning via video more? Check out [this TikTok summarizing this tutorial in two minutes](https://www.tiktok.com/@lizziepikachu/video/7096515544441998638?is_copy_url=1&is_from_webapp=v1&lang=en)!
<a href="https://www.tiktok.com/embed/7096515544441998638" title="video"><img src="https://user-images.githubusercontent.com/8932430/171303672-407ed00a-ba65-4069-a6ca-028061afbec8.png" alt="tiktok" /></a>

### Prerequisites
To follow along with this post, you need three things:
1. A Twilio account - [sign up for a free one here and receive an extra $10 if you upgrade through this link](http://www.twilio.com/referral/iHsJ5D)
2. A Twilio phone number with SMS capabilities - [configure one here](https://www.twilio.com/console/phone-numbers/search)
3. Segment account - [sign up for a free one here](https://segment.com/)

### 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](https://segment.com/docs/connections/sources/). A source provides data to Segment to use. To make a source, [create and go to your Segment Workspace](https://app.segment.com/workspacesrview) and click <em>Sources</em> on the left.
![sources image](https://twilio-cms-prod.s3.amazonaws.com/images/UpduToSHiTM8mNBvSH2FZzB09H4k4F584Zx2VVwYcxhBm.width-1000.png)
From your <em>List of Sources</em>, click the blue <em>Add Source</em> button.
![my sources](https://twilio-cms-prod.s3.amazonaws.com/images/wFpJ-l1U2cZqcVw2U0scMqL0YBypGerLiQ7zucZ0QoKuQ.width-1000.png)
From the <em>Catalog of Sources</em>, under <em>Website</em> select <em>JavaScript</em> followed by <em>Add Source</em>.
![catalog add website](https://twilio-cms-prod.s3.amazonaws.com/images/5RZ7V5Rgqk5ayALqTpp49C9FH1ppjGyWCy55ay-JkWOwB.width-1000.png)
In <em>Source setup</em>, give your Source a name–for example, <em>Personal Website</em>. You can leave <em>Labels</em> blank, and then add the Website URL. In my case, my personal website is [lizziesiegle.xyz](https://www.lizziesiegle.xyz).
![source setup](https://twilio-cms-prod.s3.amazonaws.com/images/0_LYjZNBofxAJNo1F8ytnNJSB2q-JCGbD4JTMUNkMMajj.width-1000.png)
After clicking <em>Add Source</em>, Segment will provide you with code similar to the one below to include in your HTML file's <em>\<head\></em>element.
![Segment provided script](https://twilio-cms-prod.s3.amazonaws.com/images/DIX031FMJS78DmJxCjIlmQ24KZMm4_XnhCetxXtU7vbNM.width-1000.png)
That code adds Segment's <em>Analytics.js</em> library so we can send data from our website to Segment and any Destination. Add this to your website's <em>\<head\></em> element.

You can check that <em>Analytics.js</em> 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.
![analytics variable exists](https://twilio-cms-prod.s3.amazonaws.com/images/FjXE5as797hookN3wd1fqkhRIxDjxbL4Gcd6V6nBx9h5k.width-1000.png)
Now this tutorial will use [Twilio Functions](https://www.twilio.com/docs/runtime/functions) as a Destination: let's make that Twilio Function now.

### Make a Twilio Function to Send a SMS
The Serverless Toolkit is CLI tooling that helps you develop locally and deploy to [Twilio Runtime](https://www.twilio.com/docs/runtime). The best way to work with the Serverless Toolkit is through the [Twilio CLI](https://www.twilio.com/docs/twilio-cli/quickstart). 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:
```bash
npm install twilio-cli -g
twilio login
twilio plugins:install @twilio-labs/plugin-serverless
```
Create your new project by running:
```bash
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, it is saved as `MY_PHONE_NUMBER`.

Add a new file inside the `\functions` directory called `segment.js` containing the following code:
```javascript
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](https://www.twilio.com/docs/libraries/node), 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 (my personal phone number hidden as an environment variable and a Twilio number), and then sends an outbound text message when the Twilio Function is hit (when my website is viewed.)

From the root directory, run `twilio serverless:deploy` and copy the URL ending in `/segment`.

### Set the Twilio Function as a Segment Destination
Back in your Segment Console beneath the blue <em>Copy Snippet</em> button, click the blue <em>Add Destination</em> button.
![add destination](https://twilio-cms-prod.s3.amazonaws.com/images/ATCMGRxcP4LCY63MHlDO1eH0l_-Z8GDaYeK59PcG3ymF-.width-1000.png)
Search the Destinations Catalog for <em>webhook</em> and select <em>Webhooks</em>.
![destinations catalog](https://twilio-cms-prod.s3.amazonaws.com/images/JtU75Hub974LPYhNrO9iQVHwjLgnJbRvgDgGPfe0kLbT7.width-1000.png)
Then click the blue <em>Configure Webhooks</em> button.
![configure webhooks](https://twilio-cms-prod.s3.amazonaws.com/images/PG04aFXqSkwxWJijannLeR85EctKdrKovhL0gEtI5SIpr.width-1000.png)
Select a data source to be your website and now to setup the webhook, we give it a Destination name, followed by clicking <em>Save</em>.
![save button](https://twilio-cms-prod.s3.amazonaws.com/images/WkIeU1QSy9nLbJ64EZeEj8Cd-qCCPG6nxv1We9Bgaal6P.width-1000.png)
Then select <em>Webhooks (max 5)</em> and enable the toggle next to <em>Setup Guide</em>.
![webhooks select next to setup guide](https://twilio-cms-prod.s3.amazonaws.com/images/SxtuNZYfDDMfJFbnf5Svh6iJtOpel7_-0XZZKBjwxIiUb.width-1000.png)
Put in your Function URL ending in `/segment` and set a header to be something like you see below.

![header set](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r2sc561dufudk4ij5ays.png)
 

Click the blue <em>Save</em> button and tada! You will get a text message saying "site has been viewed!" whenever someone visits your website.
![site has been viewed text messages sent](https://twilio-cms-prod.s3.amazonaws.com/images/bthTGsJXa5m5JAkNxq_dAFo2QrhTJwpnSMotyj0SW_zbH.width-1000.png)
Alternatively in your Segment console you can go to the Debugger section of your Source and see when someone visits the site as well.
![Segment debugger](https://twilio-cms-prod.s3.amazonaws.com/images/ecmjJUXOCjOWqNtUDtVEvts1tAX0fOSdGnf5arbF9Q6KZ.width-1000.png)
### What's Next for Twilio Serverless and Segment?
Segment is a handy tool that helps give developers insight into how both users and customers are using your website or application. Let me know online what you're building with Twilio Segment and Serverless!
- Twitter: [@lizziepika](twitter.com/lizziepika)
- GitHub: [elizabethsiegle](github.com/elizabethsiegle)
- Email: lsiegle@twilio.com
- Livestreams: [twitch.tv/lizziepikachu](twitch.tv/lizziepikachu)