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.

  1. Twilio Segment and Twilio Engage with access to Profile API.
  2. An account with Uniform. If you don’t have access, request an account.
  3. An app that's already wired up with Uniform SDK (Canvas and Context capabilities). Check out Uniform's starters and tutorials.


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

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.

  1. In Uniform, open your project. Navigate to Optimization > Personalization > Quirks.

  2. Click the Create a Quirk button and use the following values:

    NameBig Spenders
    Public ID[This is generated from the value in the Name field]
    Description[blank] (Field is optional)
    Data typeList
    List valuetrue|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.



    The publicid of the quirk is important as it will have to correspond to the name of the trait coming from Segment Profile API.

  3. Now select Signals from the on-page menu and click Create a Signal.

  4. Enter a name for your signal. Choose something that conveys its purpose.

  5. Choose Quirk from the signal criteria builder, and select Big Spender from the list under Quirk Name.

  6. Select true from the list under Match.


    Click Save and close.

  7. Repeat this step for any additional quirks that you created and click the Publish button to make this configuration available in compositions.


After the required configuration for personalization (in this case, signals) is in place, activate personalization on any component using Uniform Canvas.

  1. Navigate to Experience > Compositions and select a composition.

  2. Within your composition, select a component.

  3. Click Personalize This in the Context tab on the component. This will only be available on components in slots that allow personalization.

  4. 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.
  5. Save the composition.

This step permits your front-end to send visitor data to Segment.

  1. Make sure you have a JavaScript source enabled in your Segment workspace:

  2. Copy your write key for this source, you will be using it later. Learn more on finding the write key.

  3. Run npm install segment/snippet within your app.

  4. If you are using TypeScript, run npm i types/segment-analytics --save-dev to get the types for Segment Analytics.

  5. Add Segment snippet into your /pages/_app.tsx using next/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() }} /> ... </> ); }
  6. 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 }); };'routeChangeComplete', handleRouteChange); return () => {'routeChangeComplete', handleRouteChange); }; }, [router]);
  7. Set the NEXT_PUBLIC_ANALYTICS_WRITE_KEY environment variable in your .env file that has the write key from the step earlier:


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.

  1. Install the Axios library for data fetching (this is needed because standard fetch has trouble parsing the response from Profile API).

    npm install axios
  2. Create 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 = `${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(; }) .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.

  3. 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:


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.

  1. 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;
  2. 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.

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.