> Documentation index: https://docs.zernio.com/llms.txt. Every page is also Markdown: add .md to its URL.

# Send Segment and RudderStack events

Forward the track events you already send to Segment or RudderStack into Zernio, which sends them to Meta, Google, TikTok and your other ad platforms, deduplicated.

After this page, the conversions your Segment or RudderStack source already tracks reach Zernio, which forwards them to every ad platform you switched on. You paste one function and change little site code.

## When to use it

Use this recipe when your site or backend already sends `track` calls to Segment or RudderStack, such as `Order Completed`, and you want them in Meta, Google Ads and TikTok without building each conversions API.

Zernio has no native Segment or RudderStack destination. The function on this page calls the public `POST /v1/events` endpoint, the same one the [Send events](/products/conversions-api/send) page documents.

If the [Zernio tag](/products/server-side-tracking) already sends a purchase from your site, do not send that event again from Segment or RudderStack. Map only the events the tag does not cover.

## Before you start

- An [API key](https://zernio.com/dashboard/api-keys) on a team with the Ads add-on.
- The `profileId` of the profile whose ad accounts get the events.
- At least one ad account switched on for that profile, under **Ads**, then **Conversions**. Without one, events are stored but sent nowhere. See [Choose where it sends](/products/server-side-tracking/ad-accounts).
- In Segment: a workspace where you can create Functions. In RudderStack: permission to create transformations and destinations.

## Step 1: Check the event mapping

The function sends only the events in its `EVENT_NAMES` map. The defaults come from the Segment ecommerce and B2B SaaS specs, which RudderStack follows. `Subscription Started` and `Lead Created` are common names outside them:

| Your event | Zernio `eventName` |
|---|---|
| `Order Completed` | `Purchase` |
| `Checkout Started` | `InitiateCheckout` |
| `Payment Info Entered` | `AddPaymentInfo` |
| `Product Added` | `AddToCart` |
| `Product Viewed` | `ViewContent` |
| `Products Searched` | `Search` |
| `Signed Up` | `CompleteRegistration` |
| `Trial Started` | `StartTrial` |
| `Subscription Started` | `Subscribe` |
| `Lead Created` | `Lead` |

Edit the map to match your tracking plan. The full list of standard names is on [Send events](/products/conversions-api/send#event-names).

Each event becomes one Zernio event:

| Segment or RudderStack field | Zernio field |
|---|---|
| `messageId` | `eventId`, and the `Idempotency-Key` header |
| `timestamp` | `eventTime`, in unix seconds |
| `properties.revenue`, else `total`, `value`, or `price` times `quantity` | `value` |
| `properties.currency` | `currency`, `USD` when missing |
| `properties.products` (or the product itself on product events) | `items` |
| `properties.email`, else `context.traits.email` | `user.email` |
| `properties.phone`, else `context.traits.phone` | `user.phone` |
| `context.traits.firstName`, `lastName`, `address` | `user.firstName`, `lastName`, `city`, `state`, `zip`, `country` |
| `userId` | `user.externalId` |
| `context.ip`, `context.userAgent` | `user.ipAddress`, `user.userAgent` |
| `properties.order_id` on `Order Completed` | `user.orderId` |
| `context.page.url` with its query | `sourceUrl`, and `user.clickIds` from `gclid`, `fbclid`, `ttclid` and the other click ids in it |
| The consent manager's choices | `consent` on the event |

Send email and phone as plain text. Zernio normalizes and hashes them before they leave, and stores only the hashes. A value you hashed yourself is not matched.

Segment does not copy `identify` traits onto `track` calls by default. Put `email` and `phone` in the properties of your conversion events, or the platforms match on IP, user agent and click ids only.

## Step 2: Send from Segment

Create a Destination Function in Segment:

1. Go to **Connections**, then **Catalog**, open the **Functions** tab and click **New Function**.
2. Choose **Destination** and click **Next: Build Function**.
3. Replace the code with the function below.
4. Click **Add Setting** three times: `apiKey` (turn on **Secret**), `profileId` and `testCode`. Check that each **Name** matches, since the code reads `settings.apiKey`, `settings.profileId` and `settings.testCode`.
5. Click **Configure**, name it `Zernio Conversions` and click **Create Function**.
6. Connect the function to your source as a destination, fill in the settings and turn it on.

```js
// Zernio Conversions: Segment Destination Function.
// Settings: apiKey (secret), profileId, testCode (optional).

// Your Segment event names on the left, Zernio's on the right. Edit to match your tracking plan.
const EVENT_NAMES = {
  'Order Completed': 'Purchase',
  'Checkout Started': 'InitiateCheckout',
  'Payment Info Entered': 'AddPaymentInfo',
  'Product Added': 'AddToCart',
  'Product Viewed': 'ViewContent',
  'Products Searched': 'Search',
  'Signed Up': 'CompleteRegistration',
  'Trial Started': 'StartTrial',
  'Subscription Started': 'Subscribe',
  'Lead Created': 'Lead'
};

// Your Segment Consent Management categories for ads and for analytics.
const AD_CATEGORY = 'Advertising';
const ANALYTICS_CATEGORY = 'Analytics';
// Used when an event has a value but no currency.
const DEFAULT_CURRENCY = 'USD';

// URL parameter on the left, Zernio's user.clickIds field on the right.
const CLICK_PARAMS = {
  gclid: 'gclid', gbraid: 'gbraid', wbraid: 'wbraid', ttclid: 'ttclid', li_fat_id: 'li_fat_id',
  epik: 'epik', twclid: 'twclid', msclkid: 'msclkid', rdt_cid: 'rdt_cid', ScCid: 'sccid', dclid: 'dclid'
};

function readQuery(url) {
  const query = {};
  const search = String(url || '').split('#')[0].split('?')[1] || '';
  for (const pair of search.split('&')) {
    const [key, value = ''] = pair.split('=');
    try {
      if (key) query[decodeURIComponent(key)] = decodeURIComponent(value.replace(/\+/g, ' '));
    } catch (e) {}
  }
  return query;
}

function pageUrl(page) {
  if (!page || !page.url) return undefined;
  return page.url.includes('?') || !page.search ? page.url : page.url + page.search;
}

function consentOf(context) {
  const prefs = context.consent && context.consent.categoryPreferences;
  if (!prefs) return undefined;
  const signal = (category) => (prefs[category] === true ? 'GRANTED' : prefs[category] === false ? 'DENIED' : undefined);
  const consent = {};
  const ads = signal(AD_CATEGORY);
  if (ads) Object.assign(consent, { adStorage: ads, adUserData: ads, adPersonalization: ads });
  const analytics = signal(ANALYTICS_CATEGORY);
  if (analytics) consent.analyticsStorage = analytics;
  return Object.keys(consent).length ? consent : undefined;
}

function toZernioEvent(event, eventName, consent) {
  const p = event.properties || {};
  const context = event.context || {};
  const traits = Object.assign({}, context.traits, event.traits);
  const address = traits.address || {};
  const sourceUrl = pageUrl(context.page);
  const query = readQuery(sourceUrl);
  const ms = Date.parse(event.timestamp || '');
  const eventTime = Math.floor((Number.isFinite(ms) ? ms : Date.now()) / 1000);

  const user = {};
  const put = (target, key, value) => {
    if (value !== undefined && value !== null && value !== '') target[key] = String(value);
  };
  put(user, 'email', p.email || traits.email);
  put(user, 'phone', p.phone || traits.phone);
  put(user, 'firstName', traits.firstName || traits.first_name);
  put(user, 'lastName', traits.lastName || traits.last_name);
  put(user, 'externalId', event.userId);
  put(user, 'ipAddress', context.ip);
  put(user, 'userAgent', context.userAgent);
  put(user, 'city', address.city);
  put(user, 'state', address.state);
  put(user, 'zip', address.postalCode || address.postal_code);
  if (/^[A-Za-z]{2}$/.test(address.country || '')) user.country = address.country.toLowerCase();
  if (eventName === 'Purchase') put(user, 'orderId', p.order_id);

  const clickIds = {};
  for (const [param, field] of Object.entries(CLICK_PARAMS)) put(clickIds, field, p[field] || query[param]);
  if (query.fbclid) clickIds.fbc = `fb.1.${eventTime * 1000}.${query.fbclid}`;
  put(clickIds, 'fbc', p.fbc);
  put(clickIds, 'fbp', p.fbp);
  if (Object.keys(clickIds).length) user.clickIds = clickIds;

  const zernioEvent = { eventName, eventTime, eventId: event.messageId, user };
  const value = Number(p.revenue ?? p.total ?? p.value ?? (p.price === undefined ? undefined : p.price * (p.quantity || 1)));
  if (Number.isFinite(value)) {
    zernioEvent.value = value;
    zernioEvent.currency = /^[A-Za-z]{3}$/.test(p.currency || '') ? p.currency.toUpperCase() : DEFAULT_CURRENCY;
  }
  const products = Array.isArray(p.products) ? p.products : p.product_id || p.sku ? [p] : [];
  if (products.length) {
    zernioEvent.items = products.map((product) => {
      const item = {};
      put(item, 'id', product.product_id || product.sku);
      put(item, 'name', product.name);
      put(item, 'category', product.category);
      if (Number.isFinite(Number(product.price))) item.price = Number(product.price);
      if (Number.isFinite(Number(product.quantity))) item.quantity = Number(product.quantity);
      return item;
    });
  }
  if (sourceUrl) zernioEvent.sourceUrl = sourceUrl;
  if (sourceUrl || context.userAgent) zernioEvent.actionSource = 'web';
  if (consent) zernioEvent.consent = consent;
  return zernioEvent;
}

async function onTrack(event, settings) {
  const eventName = EVENT_NAMES[event.event];
  if (!eventName) return; // Not a conversion: nothing to send.

  const body = {
    profileId: settings.profileId,
    events: [toZernioEvent(event, eventName, consentOf(event.context || {}))],
    mode: 'async'
  };
  if (settings.testCode) body.testCode = settings.testCode;

  let response;
  try {
    response = await fetch('https://zernio.com/api/v1/events', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${settings.apiKey}`,
        'Content-Type': 'application/json',
        'Idempotency-Key': event.messageId
      },
      body: JSON.stringify(body)
    });
  } catch (error) {
    throw new RetryError(error.message);
  }
  if (response.status === 409 || response.status === 429 || response.status >= 500) {
    throw new RetryError(`Zernio answered ${response.status}`);
  }
  if (!response.ok) {
    throw new ValidationError(`Zernio answered ${response.status}: ${await response.text()}`);
  }
}

// Other calls are not conversions. Empty handlers keep Segment from reporting them as unsupported.
async function onIdentify(event, settings) {}
async function onPage(event, settings) {}
async function onScreen(event, settings) {}
async function onGroup(event, settings) {}
async function onAlias(event, settings) {}
```

Segment retries a call that throws `RetryError` for up to 4 hours. Zernio answers `409`, `429` and `5xx` with an error worth retrying; any other `4xx` is a `ValidationError` that Segment does not retry.

For consent, set `AD_CATEGORY` and `ANALYTICS_CATEGORY` to your category names in Segment Consent Management. The function reads them from `context.consent.categoryPreferences`.

## Step 3: Send from RudderStack

RudderStack hosts the code in a transformation attached to a Webhook destination. The transformation calls Zernio itself and returns nothing, so the Webhook sends no request of its own.

The Webhook cannot post to Zernio directly: RudderStack keeps a `type` field in every body it sends, and `POST /v1/events` refuses fields it does not know.

1. Go to **Collect**, then **Transformations**, and click **Create Transformation**. Pick **JavaScript**.
2. Paste the code below, set `ZERNIO_API_KEY`, `PROFILE_ID` and the two consent ids, then **Publish** it.
3. Add a **Webhook** destination to your source. Set **Webhook URL** to `https://zernio.com/api/v1/events` and **URL Method** to `POST`.
4. On the destination's **Transformation** tab, click **Add a transformation** and choose this one.

```js
// Zernio Conversions: RudderStack transformation for a Webhook destination.
// It sends each conversion to Zernio itself and returns nothing, so the Webhook sends nothing.

// On Growth and Enterprise plans, use getCredential('ZERNIO_API_KEY') instead of pasting the key.
const ZERNIO_API_KEY = 'paste your Zernio API key';
const PROFILE_ID = '66a1f0c2a4b9d3e8f1a2b3c4';
const TEST_CODE = ''; // Set to a Meta test code while testing, then empty it.

// Your RudderStack event names on the left, Zernio's on the right. Edit to match your tracking plan.
const EVENT_NAMES = {
  'Order Completed': 'Purchase',
  'Checkout Started': 'InitiateCheckout',
  'Payment Info Entered': 'AddPaymentInfo',
  'Product Added': 'AddToCart',
  'Product Viewed': 'ViewContent',
  'Products Searched': 'Search',
  'Signed Up': 'CompleteRegistration',
  'Trial Started': 'StartTrial',
  'Subscription Started': 'Subscribe',
  'Lead Created': 'Lead'
};

// Your consent manager's category ids for ads and for analytics.
const AD_CONSENT_ID = 'C0004';
const ANALYTICS_CONSENT_ID = 'C0002';
// Used when an event has a value but no currency.
const DEFAULT_CURRENCY = 'USD';

// URL parameter on the left, Zernio's user.clickIds field on the right.
const CLICK_PARAMS = {
  gclid: 'gclid', gbraid: 'gbraid', wbraid: 'wbraid', ttclid: 'ttclid', li_fat_id: 'li_fat_id',
  epik: 'epik', twclid: 'twclid', msclkid: 'msclkid', rdt_cid: 'rdt_cid', ScCid: 'sccid', dclid: 'dclid'
};

function readQuery(url) {
  const query = {};
  const search = String(url || '').split('#')[0].split('?')[1] || '';
  for (const pair of search.split('&')) {
    const [key, value = ''] = pair.split('=');
    try {
      if (key) query[decodeURIComponent(key)] = decodeURIComponent(value.replace(/\+/g, ' '));
    } catch (e) {}
  }
  return query;
}

function pageUrl(page) {
  if (!page || !page.url) return undefined;
  return page.url.includes('?') || !page.search ? page.url : page.url + page.search;
}

function consentOf(context) {
  const cm = context.consentManagement;
  if (!cm) return undefined;
  const allowed = Array.isArray(cm.allowedConsentIds) ? cm.allowedConsentIds : Object.keys(cm.allowedConsentIds || {});
  const denied = cm.deniedConsentIds || [];
  const signal = (id) => (allowed.includes(id) ? 'GRANTED' : denied.includes(id) ? 'DENIED' : undefined);
  const consent = {};
  const ads = signal(AD_CONSENT_ID);
  if (ads) Object.assign(consent, { adStorage: ads, adUserData: ads, adPersonalization: ads });
  const analytics = signal(ANALYTICS_CONSENT_ID);
  if (analytics) consent.analyticsStorage = analytics;
  return Object.keys(consent).length ? consent : undefined;
}

function toZernioEvent(event, eventName, consent) {
  const p = event.properties || {};
  const context = event.context || {};
  const traits = Object.assign({}, context.traits, event.traits);
  const address = traits.address || {};
  const sourceUrl = pageUrl(context.page);
  const query = readQuery(sourceUrl);
  const ms = Date.parse(event.timestamp || '');
  const eventTime = Math.floor((Number.isFinite(ms) ? ms : Date.now()) / 1000);

  const user = {};
  const put = (target, key, value) => {
    if (value !== undefined && value !== null && value !== '') target[key] = String(value);
  };
  put(user, 'email', p.email || traits.email);
  put(user, 'phone', p.phone || traits.phone);
  put(user, 'firstName', traits.firstName || traits.first_name);
  put(user, 'lastName', traits.lastName || traits.last_name);
  put(user, 'externalId', event.userId);
  put(user, 'ipAddress', context.ip);
  put(user, 'userAgent', context.userAgent);
  put(user, 'city', address.city);
  put(user, 'state', address.state);
  put(user, 'zip', address.postalCode || address.postal_code);
  if (/^[A-Za-z]{2}$/.test(address.country || '')) user.country = address.country.toLowerCase();
  if (eventName === 'Purchase') put(user, 'orderId', p.order_id);

  const clickIds = {};
  for (const [param, field] of Object.entries(CLICK_PARAMS)) put(clickIds, field, p[field] || query[param]);
  if (query.fbclid) clickIds.fbc = `fb.1.${eventTime * 1000}.${query.fbclid}`;
  put(clickIds, 'fbc', p.fbc);
  put(clickIds, 'fbp', p.fbp);
  if (Object.keys(clickIds).length) user.clickIds = clickIds;

  const zernioEvent = { eventName, eventTime, eventId: event.messageId, user };
  const value = Number(p.revenue ?? p.total ?? p.value ?? (p.price === undefined ? undefined : p.price * (p.quantity || 1)));
  if (Number.isFinite(value)) {
    zernioEvent.value = value;
    zernioEvent.currency = /^[A-Za-z]{3}$/.test(p.currency || '') ? p.currency.toUpperCase() : DEFAULT_CURRENCY;
  }
  const products = Array.isArray(p.products) ? p.products : p.product_id || p.sku ? [p] : [];
  if (products.length) {
    zernioEvent.items = products.map((product) => {
      const item = {};
      put(item, 'id', product.product_id || product.sku);
      put(item, 'name', product.name);
      put(item, 'category', product.category);
      if (Number.isFinite(Number(product.price))) item.price = Number(product.price);
      if (Number.isFinite(Number(product.quantity))) item.quantity = Number(product.quantity);
      return item;
    });
  }
  if (sourceUrl) zernioEvent.sourceUrl = sourceUrl;
  if (sourceUrl || context.userAgent) zernioEvent.actionSource = 'web';
  if (consent) zernioEvent.consent = consent;
  return zernioEvent;
}

export async function transformEvent(event, metadata) {
  if (event.type !== 'track') return; // Identify, page and other calls are not conversions.
  const eventName = EVENT_NAMES[event.event];
  if (!eventName) return;

  const context = event.context || {};
  const body = {
    profileId: PROFILE_ID,
    events: [toZernioEvent(event, eventName, consentOf(context))],
    mode: 'async'
  };
  if (TEST_CODE) body.testCode = TEST_CODE;

  const response = await fetchV2('https://zernio.com/api/v1/events', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${ZERNIO_API_KEY}`,
      'Content-Type': 'application/json',
      'Idempotency-Key': event.messageId
    },
    body: JSON.stringify(body),
    timeout: 10000
  });
  if (response.status >= 300) {
    throw new Error(`Zernio answered ${response.status}: ${JSON.stringify(response.body)}`);
  }
  return; // Sent: the Webhook has nothing left to send.
}
```

On Growth and Enterprise plans, save the key as a secret under **Settings**, **Workspace**, **Credentials** and read it with `getCredential('ZERNIO_API_KEY')`. Otherwise the key sits in the code, so limit who edits transformations.

For consent, set `AD_CONSENT_ID` and `ANALYTICS_CONSENT_ID` to your consent manager's category ids, such as OneTrust's. The function reads them from `context.consentManagement`.

## Step 4: Test with a test code

1. Copy the test code from Meta Events Manager, **Test events**.
2. Put it in the Segment `testCode` setting, or in `TEST_CODE` in the transformation.
3. Fire a mapped event, such as a test order. The Segment editor's **Run** button works too. Change the sample's `messageId` before each run: a repeat reaches no platform.
4. Check the event in Meta's **Test events** tab.

Zernio forwards test events but never stores them, so they do not appear in Zernio. Each platform's test mode is on [Platforms](/products/conversions-api/platforms#test-mode-and-consent).

Then empty the test code and fire one real event. Open **Ads**, then **Conversions**, then the **Events** tab: the event shows with every send to every destination. With the API:

```bash
curl "https://zernio.com/api/v1/events?profileId=66a1f0c2a4b9d3e8f1a2b3c4&source=api&limit=5" \
  -H "Authorization: Bearer $ZERNIO_API_KEY"
```

The `eventId` is the Segment or RudderStack `messageId`. [Get one event](/conversions/get-event) shows each send as `sent`, `retrying` or `failed`, with the platform's error.

## Limits

- One event per request, as each `track` call arrives. A `429` carries `Retry-After`; Segment retries it, RudderStack reports the event as failed.
- One event is limited to 32 KB of JSON and 8,192 characters in any text field; `eventName` and `eventId` to 256 characters.
- Only mapped `track` calls are sent. `identify`, `page`, `screen`, `group` and `alias` calls are skipped.
- Click ids come from the event's page URL. A purchase on a checkout page rarely has them, so pass `fbc`, `fbp`, `gclid` or `ttclid` in its properties when your site keeps them.
- RudderStack does not retry a failed transformation call. The event shows as failed in RudderStack, and is lost unless you replay it.
- RudderStack transformations run for at most 4 seconds, not counting the time `fetchV2` waits.

## How it behaves

- **Dedup.** `eventId` is the `messageId`, so a retried call never counts twice: Zernio replaces the stored event and each destination skips an id it already took.
- **Dedup with your browser pixel.** Segment's Facebook Pixel destination sends the `messageId` as the pixel's `eventID`, so Meta keeps one copy. A pixel fired with another id, such as the order id, needs that id as `eventId`. See [Count each conversion once](/products/server-side-tracking/deduplication).
- **Async.** The function sends `mode: "async"`, so Zernio answers `202` at once and retries each ad platform on its own. With a test code, Zernio sends at once and answers `200`.
- **Consent.** Zernio applies consent by country, from `user.country` or a matched site visit. The function sets `user.country` from a two-letter `traits.address.country`. For a visitor in the EEA, the UK or Switzerland, a missing signal counts as denied. See [Consent](/products/conversions-api/send#consent).
- **Server events.** Segment fills `context.ip` only for events from the browser. For events your backend sends, set the visitor's IP in `context.ip` yourself.

## If it fails

| Error | Cause | Fix |
|---|---|---|
| `400` naming a field | A value has the wrong type, such as a currency that is not three letters | Read `param` in the error and fix the mapping |
| `401` | The API key is missing or wrong | Check `apiKey` or `ZERNIO_API_KEY` |
| `403 ads_addon_required` | The team has no Ads add-on | Add the Ads add-on |
| `404` | The `profileId` is not in your team | Copy the profile id again |
| `warnings` with `no_destination` | No ad account is switched on for the profile | Switch one on under **Ads**, then **Conversions** |
| Events in Zernio, none on a platform | No ad consent for an EEA, UK or Swiss visitor | Map your consent categories |

## Related

- [Send events](/products/conversions-api/send)
- [Send events reference](/conversions/send-events)
- [Count each conversion once](/products/server-side-tracking/deduplication)
- [Choose where it sends](/products/server-side-tracking/ad-accounts)
- [Conversions integrations](/products/conversions-api/integrations)