Instrumentation at the edge
Twilio Segment's customer data platform collects, transforms, and activates first-party customer data. But app instrumentation has two persistent problems. First, critical events happen on the client, where data quality suffers from browser limitations, user configurations, and network issues. Second, real-time personalization — driven by segmentation logic that must run in the cloud — needs user state available in under 50ms.
The Segment Edge SDK, built on Cloudflare Workers, addresses both. It collects first-party data with the reliability of a server-side implementation while exposing real-time user profiles for personalized responses, without requiring developers to manage substantial infrastructure.
The team chose Workers as the runtime for three reasons: a platform capable of handling billions of events per day without cold starts, Workers KV as a fast storage layer, and the ease and speed of deployment. The Edge SDK is in early development, and features are subject to change.
The first-party data problem
Segment's core web SDK, analytics.js, lets developers send data to any tool without learning a new API for each integration. Developers embed a snippet in the HEAD of their page; it buffers events immediately while loading the full library asynchronously from Segment's CDN. Calls like analytics.identify('john') and analytics.track('Order Completed') send data to api.segment.io, which routes events to connected tools and builds a user profile.
The SDK also stores state in first-party cookies — e.g., an ajs_user_id cookie scoped to the site's domain — so returning visitors can be recognized.

But despite handling only first-party data, analytics.js is frequently misidentified as a third-party tracker: the library loads from cdn.segment.com and sends data to api.segment.com, both third-party domains. Browsers also impose limits on non-HTTPOnly cookies — Safari caps their TTL at seven days — making long-term state difficult to maintain.
The Edge SDK solves this by running as a Cloudflare Worker in front of a web application, injecting the analytics.js snippet into every page, proxying SDK assets and tracking calls through first-party endpoints, and persisting user identity in HTTPOnly cookies. That placement also makes the SDK a natural personalization layer: it sees the user identity on every request and can resolve it to a full profile stored in Segment.
How the Edge SDK works
Developers set up the SDK by creating a Worker that sits in front of their application and importing the Edge SDK via npm. Internally, the router checks each inbound request URL against predefined patterns and runs the matching chain of handlers to process the request, fetch the origin, or modify the response.
import { Segment } from "@segment/edge-sdk-cloudflare";
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const segment = new Segment(env.SEGMENT_WRITE_KEY);
const resp = await segment.handleEvent(request, env);
return resp;
}
};
The routing flow works like this:
export interface HandlerFunction {
(
request: Request,
response: Response | undefined,
context: RouterContext
): Promise<[Request, Response | undefined, RouterContext]>;
}
- GET requests to
/seg/assets/*are proxied to the Segment CDN (step 2a) - POST requests to
/seg/events/*are proxied to the Segment tracking API (step 2b) - All other requests go to the origin, and HTML responses are enriched with the analytics.js snippet (step 2c)
Regardless of route, a response returns to the browser (step 4). When the SDK detects a user identity in the request, it adds an HTTPOnly cookie to response headers to persist that identity.

Injecting the SDK into HTML
For origin-routed requests, the Edge SDK fetches the HTML page and inserts the analytics.js snippet into the <HEAD> tag using the HTMLRewriter API. The snippet is configured with the Segment write key and points subsequent asset loads and event sends at the first-party domain: [first-party host]/seg/assets/* and [first-party host]/seg/events/*.
import snippet from "@segment/snippet"; // Existing Segment package that generates snippet
class ElementHandler {
constructor(host: string, writeKey: string)
element(element: Element) {
// generate Segment snippet and configure it with first-party host info
const snip = snippet.min({
host: `${this.host}/seg`,
apiKey: this.writeKey,
})
element.append(`<script>${snip}</script>`, { html: true });
}
}
export const enrichWithAJS: HandlerFunction = async (
request,
response,
context
) => {
const {
settings: { writeKey },
} = context;
const host = request.headers.get("host") || "";
return [
request,
new HTMLRewriter().on("head",
new ElementHandler(host, writeKey))
.transform(response),
context,
];
};
Proxying assets and API calls
The SDK proxies both the CDN and the tracking API under the first-party domain. When the injected snippet loads the full analytics.js bundle from https://example.com/seg/assets/sdk.js, the Worker forwards that request to the Segment CDN:
https://cdn.segment.com/analytics.js/v1/<WRITEKEY>/analytics.min.js
Likewise, when analytics.js POSTs events to https://example.com/seg/events/[method], the Edge SDK forwards the request to the Segment tracking API:
https://api.segment.io/v1/[method]
Server-side cookies
The Edge SDK rewrites analytics.js's client-side cookies as HTTPOnly cookies. When it intercepts an identify call such as analytics.identify('john'), it extracts the user ID and sets a server-side cookie in the response. Every subsequent request to the Worker can then be associated with that identity via request cookies.
export const enrichResponseWithIdCookies: HandlerFunction = async (
request, response, context) => {
const host = request.headers.get("host") || "";
const body = await request.json();
const userId = body.userId;
[…]
const headers = new Headers(response.headers);
const cookie = cookie.stringify("ajs_user_id", userId, {
httponly: true,
path: "/",
maxage: 31536000,
domain: host,
});
headers.append("Set-Cookie", cookie);
const newResponse = new Response(response.body, {
...response,
headers,
});
return [request, newResponse, newContext];
};
Intercepting ajs_user_id at the Worker — and using the cookie to associate each request with a user — enables the more interesting capability: delivering personalized content.
Personalization on the Workers platform
The Edge SDK provides a registerVariation method that customizes how a request to a given route is fetched from the origin. For instance, with three landing page variants at /red, /green, and / (the default), a decision function routes visitors based on their traits:
const segment = new Segment(env.SEGMENT_WRITE_KEY);
segment.registerVariation("/", (profile) => {
if (profile.red_group) {
return "/red"
} else if (profile.green_group)
return "/green"
}
});
const resp = await segment.handleEvent(request, env);
return resp
registerVariation takes two arguments: the path displaying personalized content, and a decision function returning the origin path for the variation. The decision function receives the visitor's Segment profile object. In the example, a visitor to the root path is checked for red_group or green_group traits; the corresponding origin path is fetched and served under the original URL.
Where profiles come from
Personalization requires profile data on the Workers platform, which means a Cloudflare KV namespace must be created for the Worker and passed to the Edge SDK during initialization. The SDK stores profiles in KV, keyed by ajs_user_id with the serialized profile as the value. Two mechanisms keep the data fresh:
- Push from Segment: Segment's Engage product can sync user profile databases to external tools, including webhooks. The Edge SDK exposes a webhook endpoint at
example.com/seg/profiles-webhook; Segment calls it periodically and the handler writes profiles to KV. - Pull by the Edge SDK: When a profile isn't found in KV — because sync hasn't happened yet — the SDK fetches it from the Segment API and stores it in KV for subsequent requests.
The complete personalization flow follows this sequence:

The user requests the root path (step 1), the Worker hands the request to the Edge SDK (step 2), and the router sees a registered variation. It extracts ajs_user_id from cookies and resolves the full profile (step 3), checking KV first and falling back to the Segment API as needed. The profile is passed to the decision function to select the path (step 4), the variation is fetched from the origin (step 5), and the response is returned under the root path to the browser (step 6).
What the Edge SDK Changes for Segment Users
The Cloudflare Workers platform gives Segment customers a path to first-party data collection and personalization without standing up their own tracking infrastructure. Instead of a do-it-yourself setup, the Segment Edge SDK handles the heavy lifting.
The SDK is built to run directly on Cloudflare Workers, sitting at the network edge rather than in a browser or a centralized server. That placement is what unlocks the benefits: requests hit the edge close to the user, so data can be captured, enriched, and routed before it ever reaches a Segment-hosted endpoint.
First-Party Data Without the DIY
One of the main reasons to run tracking at the edge is to escape the limitations of third-party cookies and client-side scripts that browsers increasingly block or restrict. The edge SDK runs in a first-party context — the Worker is served from the same domain as your site — so the data it collects is inherently first-party. For Segment customers, that means they can keep using Segment's APIs and event model while gaining the reliability and compliance advantages of first-party collection.
It also simplifies things operationally. There is no separate service to deploy, no new vendor to onboard. A Worker gets configured and the SDK does the rest: capturing events, attaching user context, and forwarding payloads through Segment's standard pipeline.
Personalization at Request Time
The edge is also a natural place to make personalization decisions. Since the Worker intercepts the request before it reaches your origin, it can consult user traits or segment memberships stored in the edge and adapt the response accordingly — for example, by rewriting the HTML or adjusting which experiments a visitor is assigned to. That sort of decision logic would otherwise require a round trip to a profile service, adding latency. With the SDK, those checks happen in the same place the request is already being handled.
Status and Roadmap
The Segment Edge SDK is still in early development. The team plans to launch a private pilot soon and to open-source the SDK in the near future. For now, there is no public release or stable API; the work is about proving the integration points and the performance characteristics of running Segment's SDK logic on Cloudflare Workers.
For Segment customers who want the benefits of edge computing on their own timeline, the SDK is meant to remove the need to evaluate and assemble the pieces themselves. The expectation is that once it matures, it becomes the standard out-of-the-box option for Segment workloads on Cloudflare Workers.



