Detect Button Clicks on Your Site using Segment and SMS

June 22, 2022
Written by
Reviewed by

header img segment button clicks

Segment can help you as a developer receive data on how your users use your website or app, so you can do something like sending a text message whenever someone visits your site. This post will show you how to detect button clicks on your website and send corresponding SMS notifications.

sms example

Do you prefer learning via video more? Check out this TikTok summarizing this tutorial in under three minutes! 

Prerequisites

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 a 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.

Segment Connections
 

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

my sources

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

catalog of sources

In Source setup, give your Source a name–for example, Personal Website. You can leave Labels blank, and then add the Website URL. In my case, my personal website is https://www.lizziesiegle.xyz.

source setup

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

install segment snippet on your website

That code adds Segment's Analytics.js library so we can send data from our website to Segment and 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.

:

check that segment is installed in the browser dev tools console
 

Add Button Onclick event

Segment has an API call called track to let developers record any actions their users perform, along with any properties that might describe the action. Properties are extra data points you can connect to events you track. Segment recommends sending properties whenever possible to provide a more complete picture of what your users are doing.

A track API call for a registration button could look like

analytics.track("User Registered", {
  plan: "Pro Annual",
  accountType: "Facebook"
});

That code generates the following payload:

{
  "type": "track",
  "event": "User Registered",
  "properties": {
    "plan": "Pro Annual",
    "accountType" : "Facebook"
  }
}

Now let's make a button onClick event to call track. In your HTML file with the analytics script, your code might look something like this:

<button class="btn-toggle" onclick="analytics.track('dark mode button clicked');">dark mode🌙</button>

In the example code above, "dark mode button clicked" is the event. Now if you run your site locally or deploy it, when the button you added an onclick event to is clicked, the action will show up in the Debugger section of your Source:

segment debugger
 

Now this tutorial will use Twilio Functions as a Destination: let's make that Twilio Function now.

Make a Twilio Function to Send a SMS on Button Click

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 visited = event.request.headers.viewed; //visited
  let buttonClicked = event.event; //button clicked
  let to = context.MY_PHONE_NUMBER; //your phone #
  let from = 'YOUR-TWILIO-NUMBER; //twilio number
  let body;
  if (typeof buttonClicked  !== 'undefined') { //button is clicked
    body = `${buttonClicked}`; //set body to be button clicked
  }
  else {
    body = visited; //set body to be site visited
  }  
  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, creates two variables (visited for if Segment says the website was visited, and buttonClicked for if Segment says a button was clicked), checks if the buttonClicked variable is not undefined (and if so, sets a body variable to be buttonClicked, otherwise, body is site visited), 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 containing whatever action a user performed on your site.

From the root directory, run twilio serverless:deploy. Now let's set up the Destination in your Segment console.

Set the Twilio Function as a Segment Destination

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

Segment destination webhook

Search the Destinations Catalog for webhook and select Webhooks.

segment destinations

Then click the blue Configure Webhooks button.

configure webhooks

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

setup

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

connection settings webhook

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

webhook settings with headers

This will alert the Function when the Destination site has been viewed. There's code to detect button clicks in your Destination site's HTML. Now click the blue Save button and tada! When someone visits your website and/or clicks a button, you will be notified via SMS.

sms example buttons clicked

What's Next for Twilio Serverless and Segment?

Segment is a great tool to have in your developer toolkit to provide insight into how users and customers are using your website or application. Let me know online what you're building with Serverless and Segment!