Twilio Segment
The ability to run personalization at the “edge” (or at the CDN level) is key to fast performance at scale. It also delivers exceptional Core Web Vitals, which translate to great SEO and a delightful user experience. Edge-side personalization further means that you don’t need to run and maintain any servers that typically do server-side rendering.
Uniform Context comes with edge personalization which you can execute on any CDN with a JavaScript runtime and is natively integrated into any modern React or Vue.js-based front-end framework. Leverage your visitor data with Twilio Segment Profile API, to get fast response times (under 200ms), and real-time data.
Prerequisites#
- Twilio Segment and Twilio Engage with access to Profile API.
- An app that's already wired up with Uniform SDK (Canvas and Context capabilities). Check out Uniform's starters and tutorials.
Prerequisites
You must have access to a Uniform team with the ability to create new projects. If you are an active customer or a partner, please get in touch with your Uniform team administrator colleague and ask for an invite.
If you are not sure or your company does not have a Uniform team, you can request a sandbox here.
tip
This guide uses the Next.js framework, but you can use any framework that's supported by Uniform (such as Nuxt, Gatsby, any React- or Vue.js-based framework).
Step 1: Uniform project setup#
Step 1.1: Add quirks for a desired Segment trait#
Uniform Context is the personalization engine that's working with signals and intents. A signal could reflect any criteria: cookie, query string, geo-location, as well as use data from a visitor profile. The visitor profile data is defined as quirks in Uniform, so that’s the first step. Create a quirk called Big Spenders
. This quirk will map to the traits coming from the Segment Profile API.
In Uniform, open your project. Navigate to Optimization > Personalization > Quirks.
Click the Create a Quirk button and use the following values:
Field Value Name Big Spenders
Public ID [This is generated from the value in the Name field] Description [blank] (Field is optional) Data type List List value true|false You can specify the desired option values. If you aren't sure which values will be used for this quirk, leave it as
Text Field
.Save the quirk.
warning
The
publicid
of the quirk is important as it will have to correspond to the name of the trait coming from Segment Profile API.Now select Signals from the on-page menu and click Create a Signal.
Enter a name for your signal. Choose something that conveys its purpose.
Choose Quirk from the signal criteria builder, and select Big Spender from the list under Quirk Name.
Select true from the list under Match.
Click Save and close.
Repeat this step for any additional quirks that you created and click the Publish button to make this configuration available in compositions.
Step 1.2: Add personalization on a component in Canvas#
After the required configuration for personalization (in this case, signals) is in place, activate personalization on any component using Uniform Canvas.
Navigate to Experience > Compositions and select a composition.
Within your composition, select a component.
Click Personalize This in the Context tab on the component. This will only be available on components in slots that allow personalization.
Click Add Criteria and specify the personalization criteria (the
Big Spender
signal in this case). You can now author the content with in-line editing.Select the big spender variant as personalization criteria.Save the composition.
Step 2: Connect your Next.js app with Segment#
Step 2.1: Collect data with Segment#
This step permits your front-end to send visitor data to Segment.
Make sure you have a JavaScript source enabled in your Segment workspace:
Copy your write key for this source, you will be using it later. Learn more on finding the write key.
Run
npm install @segment/snippet
within your app.If you are using TypeScript, run
npm install @types/segment-analytics --save-dev
to get the types for Segment Analytics.Add Segment snippet into your
/pages/_app.tsx
usingnext/script
:import Script from 'next/script'; import * as snippet from '@segment/snippet'; ... function renderSnippet() { const opts = { apiKey: process.env.NEXT_PUBLIC_ANALYTICS_WRITE_KEY, page: true, }; return process.env.NODE_ENV === 'development' ? snippet.max(opts) : snippet.min(opts); } function MyApp(...) => { ... return ( <> <Script id="segment-script" dangerouslySetInnerHTML={{ __html: renderSnippet() }} /> ... </> ); }If you would like to track client-side routing events as page visits in Segment, you would need to add next/router event subscribers:
import { useRouter } from 'next/router'; ... // add this to the App render function: const router = useRouter(); useEffect(() => { const handleRouteChange = (url: string) => { global?.analytics?.page({ path: url, referrer: window.location.origin, url: window.location.origin + url }); }; router.events.on('routeChangeComplete', handleRouteChange); return () => { router.events.off('routeChangeComplete', handleRouteChange); }; }, [router]);Set the
NEXT_PUBLIC_ANALYTICS_WRITE_KEY
environment variable in your.env
file that has the write key from the step earlier:NEXT_PUBLIC_ANALYTICS_WRITE_KEY=your-write-key
Step 2.2: Activate Segment Profile API with Next.js#
You need to fetch visitor traits from the Segment Profile API to hydrate the Uniform Tracker with this data. To avoid communicating directly with the Segment Profile API and exposing the API key, use Next.js API Routes.
Install the Axios library for data fetching (this is needed because standard
fetch
has trouble parsing the response from Profile API).npm install axiosCreate a
traits.ts
file under/pages/api
with the following contents:import type { NextApiRequest, NextApiResponse } from 'next'; import axios from 'axios'; export default async function handler(req: NextApiRequest, res: NextApiResponse) { const segmentSpaceId = process.env.SEGMENT_SPACE_ID!; const segmentApiKey = process.env.SEGMENT_API_KEY!; const nextCookies = req.cookies; const ajs_anonymous_id = nextCookies.ajs_anonymous_id; const url = `https://profiles.segment.com/v1/spaces/${segmentSpaceId}/collections/users/profiles/anonymous_id:${ajs_anonymous_id}/traits`; const basicAuth = Buffer.from(segmentApiKey + ':').toString('base64'); axios .get(url, { headers: { Authorization: `Basic ${basicAuth}` }, }) .then(response => { res.status(200).json(response.data); }) .catch(function (error) { res.status(error.response.status).json({ error, }); }); }This function retrieves the current segment's anonymous id from cookies and passes it to the Profile API along with basic authorization credentials.
Retrieve the Segment space ID and access token according to the official docs here and add those as Segment environment variables to your .env file:
SEGMENT_SPACE_ID= SEGMENT_API_KEY=
Step 2.3: Integrate Segment with the Uniform Tracker#
The last step is to add one-time instrumentation to your app that will fetch the traits using the new /api/traits
endpoint and set the value of traits as Uniform Quirks.
Create the following React component anywhere in your codebase:
import { useEffect } from 'react'; import { useUniformContext } from '@uniformdev/context-react'; const TrackerScoreSync = () => { const { context } = useUniformContext(); useEffect(() => { const fetchTraits = async () => { const response = await fetch('/api/traits'); const { traits } = await response.json(); await context.update({ quirks: { ...traits, }, }); }; fetchTraits(); }, [context]); return null; }; export default TrackerScoreSync;Then add this component into any application container render function, for example, to
_app.tsx
:<TrackerScoreSync />
That’s it, now the Uniform tracker will get the latest traits from Segment’s Profile API, and personalization configured during the earlier step will work automatically.
Step 3: (Optional) Activate edge personalization mode#
Uniform Context can run personalization anywhere you render: during server-side rendering and client-side rendering (hydration), but there is also a special way to run it at the CDN level. “Edge-side” personalization prevents visitors from seeing a flicker in the experience and improves the performance and scalability of static sites. This is available on any CDN that supports programmable edge runtime.
If you'd like to activate this personalization mode, please visit the CDN-specific section to learn the steps required to do this one-time activation.