# Send conversions with track()

Send one conversion from your server with track() in the Node.js and Python SDKs: every option, the event id, test codes, retries and errors.

`track()` sends one conversion to every ad platform the profile forwards to, through `POST /v1/events`. It retries brief failures and gives you back the event id to share with your browser pixel.

## Before you start

- `@zernio/node` 0.2.1912 or later (`npm install @zernio/node`), or `zernio-sdk` 1.4.2176 or later (`pip install zernio-sdk`).
- An API key in `ZERNIO_API_KEY` on an account with the Ads add-on.
- A profile with at least one [forwarding rule](/products/server-side-tracking/ad-accounts). Without one, the event is stored but reaches no platform.

## Send a conversion

Call it once the server confirms the conversion, such as a paid order or a saved lead.

<Tabs items={['Node.js', 'Python']}>
<Tab value="Node.js">
```typescript
import Zernio from '@zernio/node';

const zernio = new Zernio();

const { eventId, response } = await zernio.track('Purchase', {
  profileId: '66a1f0c2a4b9d3e8f1a2b3c4',
  eventId: 'order_1042',
  orderId: '1042',
  value: 129.99,
  currency: 'USD',
  user: { email: 'ana@example.com', ip: '203.0.113.7', userAgent: 'Mozilla/5.0' }
});
```
</Tab>
<Tab value="Python">
```python
from zernio import Zernio

zernio = Zernio()

event_id = zernio.track(
    "Purchase",
    profile_id="66a1f0c2a4b9d3e8f1a2b3c4",
    event_id="order_1042",
    order_id="1042",
    value=129.99,
    currency="USD",
    user={"email": "ana@example.com", "ip": "203.0.113.7", "user_agent": "Mozilla/5.0"},
)
```
</Tab>
</Tabs>

What comes back:

- **Node.js** resolves with `{ eventId, response }`. `response` is the API's answer: `eventsReceived`, `stored`, `testCode`, one entry per destination in `destinations`, and `warnings`.
- **Python** returns the event id as a string. It logs each destination that refused the event or could not be reached, and each warning, on the `late.track` logger at `WARNING`. `atrack()` is the async version, with the same arguments.

A destination that fails does not fail the call. In Node.js, read `error`, `eventsFailed`, `eventsDropped` and `eventsSkipped` on each entry of `response.destinations`.

## Share the event id with your pixel

Give the browser copy of the same conversion the same event id, so each platform counts it once. Pass your own id built from the record, or read the generated one from the result.

```javascript
zernio('track', 'Purchase', { eventId: 'order_1042', value: 129.99, currency: 'USD' });
```

See [Count each conversion once](/products/server-side-tracking/deduplication).

## Send from Django or FastAPI

Send the purchase once the order is saved. A helper fills `user` from the request: IP, browser, the [`_zid` visitor cookie](/products/server-side-tracking/backend-events) and the ad platforms' click cookies.

It also unwraps Google's click ids from `_gcl_aw`, `_gcl_gb` and `_gcl_ag`. When the browser also sends the purchase, post its event id with the order, else use the order id.

<Tabs items={['Django', 'FastAPI']}>
<Tab value="Django">
```python
import re

from django.db import transaction
from django.shortcuts import redirect
from zernio import Zernio

from .models import Order

zernio = Zernio()

CLICK_COOKIES = {"_fbp": "fbp", "_fbc": "fbc", "_ttp": "ttp", "li_fat_id": "li_fat_id", "_epik": "epik", "_rdt_uuid": "rdt_uuid"}
GOOGLE_COOKIES = {"_gcl_aw": "gclid", "_gcl_gb": "wbraid"}


def gbraid_from(cookie):
    match = re.match(r"2\.[^.]*\.k([\w-]+)(?:\$|%24|$)", cookie or "")
    return match.group(1) if match else None


def track_user(request, **user):
    cookies = request.COOKIES
    forwarded = request.META.get("HTTP_X_FORWARDED_FOR", "")
    user["ip"] = forwarded.split(",")[0].strip() or request.META.get("REMOTE_ADDR")
    user["user_agent"] = request.META.get("HTTP_USER_AGENT")
    user["visitor_id"] = cookies.get("_zid")
    user.update({key: cookies[name] for name, key in CLICK_COOKIES.items() if name in cookies})
    user.update({key: cookies[name].split(".")[-1] for name, key in GOOGLE_COOKIES.items() if name in cookies})
    user["gbraid"] = gbraid_from(cookies.get("_gcl_ag"))
    return user


def checkout(request):
    with transaction.atomic():
        order = Order.objects.create(email=request.POST["email"], total=129.99)
        user = track_user(request, email=order.email)
        event_id = request.POST.get("event_id") or str(order.pk)
        transaction.on_commit(
            lambda: zernio.track(
                "Purchase",
                profile_id="66a1f0c2a4b9d3e8f1a2b3c4",
                event_id=event_id,
                order_id=str(order.pk),
                value=float(order.total),
                currency="USD",
                user=user,
            ),
            robust=True,
        )
    return redirect("thanks")
```
</Tab>
<Tab value="FastAPI">
```python
import re

from fastapi import BackgroundTasks, FastAPI, Request
from zernio import Zernio

from .orders import save_order

app = FastAPI()
zernio = Zernio()

CLICK_COOKIES = {"_fbp": "fbp", "_fbc": "fbc", "_ttp": "ttp", "li_fat_id": "li_fat_id", "_epik": "epik", "_rdt_uuid": "rdt_uuid"}
GOOGLE_COOKIES = {"_gcl_aw": "gclid", "_gcl_gb": "wbraid"}


def gbraid_from(cookie):
    match = re.match(r"2\.[^.]*\.k([\w-]+)(?:\$|%24|$)", cookie or "")
    return match.group(1) if match else None


def track_user(request: Request, **user):
    cookies = request.cookies
    forwarded = request.headers.get("x-forwarded-for", "")
    user["ip"] = forwarded.split(",")[0].strip() or (request.client.host if request.client else None)
    user["user_agent"] = request.headers.get("user-agent")
    user["visitor_id"] = cookies.get("_zid")
    user.update({key: cookies[name] for name, key in CLICK_COOKIES.items() if name in cookies})
    user.update({key: cookies[name].split(".")[-1] for name, key in GOOGLE_COOKIES.items() if name in cookies})
    user["gbraid"] = gbraid_from(cookies.get("_gcl_ag"))
    return user


@app.post("/orders")
async def create_order(request: Request, background: BackgroundTasks):
    form = await request.json()
    order = await save_order(form)
    background.add_task(
        zernio.atrack,
        "Purchase",
        profile_id="66a1f0c2a4b9d3e8f1a2b3c4",
        event_id=form.get("event_id") or str(order.id),
        order_id=str(order.id),
        value=float(order.total),
        currency="USD",
        user=track_user(request, email=order.email),
    )
    return {"id": order.id}
```
</Tab>
</Tabs>

- **Django.** `transaction.on_commit` sends nothing for an order that rolls back, and `robust=True` (Django 4.2 or later) logs a failed send instead of failing the request. The send still runs inside the request, so retries delay the response; send from a task queue to avoid that.
- **FastAPI.** The background task sends after the response, so the visitor never waits on retries.
- **`X-Forwarded-For`.** A visitor can set it, so read it only behind a proxy you trust that replaces the header rather than appending to it.

## Options

The event name is the first argument: `Purchase`, `Lead`, another [standard name](/products/conversions-api/send#event-names) or any string. The rest are options.

| Node.js | Python | What it is |
|---|---|---|
| `profileId` | `profile_id` | The profile whose forwarding rules receive the event. Required. Python falls back to the `ZERNIO_PROFILE_ID` environment variable |
| `eventId` | `event_id` | The dedup key shared with your pixel. Defaults to the order id, else a random UUID. Two events for one order, such as `InitiateCheckout` then `Purchase`, need distinct event ids |
| `orderId` | `order_id` | Your order id, sent as `platformData.order_id` (Meta's `order_id`) |
| `eventTime` | `event_time` | When it happened, as unix seconds or a date. Defaults to now. Node.js takes a `Date`, Python a datetime with a timezone. Both SDKs refuse a time in milliseconds |
| `value`, `currency` | `value`, `currency` | The amount in currency units, not cents, and its ISO 4217 code |
| `user` | `user` | Who converted, in plain text. See [User fields](#user-fields) |
| `sourceUrl` | `source_url` | The page where it happened, with its UTM tags and click ids |
| `actionSource` | `action_source` | `web`, `app`, `offline`, `crm`, `phone_call`, `system_generated` or `business_messaging` |
| `items` | `items` | The order lines: `id`, `name`, `price`, `quantity`, `category` |
| `consent` | `consent` | Google Consent Mode signals: `adStorage`, `adUserData`, `adPersonalization`, `analyticsStorage`, each `GRANTED` or `DENIED`. See [Consent](/products/conversions-api/send#consent) |
| `properties` | `platform_data` | Platform fields Zernio does not map, sent as `platformData` |
| `testCode` | `test_code` | Sends to each platform's test mode. A platform without one records the event live. The event is not stored |
| `campaign` | Not available | The ad campaign behind it, as `id` or `name` |
| `destinations` | Not available | `accountId` and `destinationId` pairs to send to instead of the profile's forwarding rules |
| `mode` | Not available | `async` answers at once with 202 and sends in the background, so `response.destinations` is empty |
| `signal` | Not available | An `AbortSignal` that cancels the call, retries included. It replaces the client timeout |
| `maxAttempts` | Not available | Attempts on rate limits, server errors and network failures. Defaults to 3 |

## User fields

Send every value in plain text. Zernio normalizes and hashes each one per platform, and stores email, phone and `externalId` only as SHA-256 hashes.

A value you hash yourself cannot match, so both SDKs refuse an `email` or `phone` that looks like a SHA-256 hash.

| Node.js | Python | What it is |
|---|---|---|
| `email`, `phone` | `email`, `phone` | The main match keys. Phone ideally in E.164, such as `+14155551234` |
| `firstName`, `lastName` | `first_name`, `last_name` | The customer's names |
| `externalId` | `external_id` | Your own customer id |
| `ip`, `userAgent` | `ip`, `user_agent` | The visitor's IP address and browser. `ip` is sent as `ipAddress` |
| `country` | `country` | ISO 3166-1 alpha-2, such as `us`. It also decides whether the EEA, UK and Swiss consent rules apply |
| `city`, `state`, `zip` | `city`, `state`, `zip` | The address |
| `dob`, `gender` | `dob`, `gender` | Birth date as `YYYYMMDD`, gender as `f` or `m` |
| `leadId` | `lead_id` | The Meta lead id, for an event about a Meta lead |
| `visitorId` | `visitor_id` | The Zernio tag's visitor id, from the `_zid` cookie, to join the event to the visit |

Click ids go on `user` under their own names in both SDKs, such as `fbc`, `fbp`, `gclid`, `ttclid` or `msclkid`, and are sent as `user.clickIds`. The full list is on [Click ids](/products/conversions-api/send#click-ids).

In Node.js, any other key on `user`, and anything in `user.clickIds`, is sent as a click id. Python refuses a key it does not know, `uid2Token` included.

## Test before going live

Pass a test code from the platform, such as one from Meta's Test Events tool. Platforms with a test mode receive the event there, and Zernio does not store it.

Google Ads, LinkedIn, Microsoft Ads, X, OpenAI and Taboola have none and record it on the live account. The Trade Desk, Amazon Ads and Outbrain do not get it.

<Tabs items={['Node.js', 'Python']}>
<Tab value="Node.js">
```typescript
await zernio.track('Purchase', { profileId: '66a1f0c2a4b9d3e8f1a2b3c4', eventId: 'order_1042', value: 129.99, currency: 'USD', testCode: 'TEST12345' });
```
</Tab>
<Tab value="Python">
```python
zernio.track("Purchase", profile_id="66a1f0c2a4b9d3e8f1a2b3c4", event_id="order_1042", value=129.99, currency="USD", test_code="TEST12345")
```
</Tab>
</Tabs>

What each platform does with a test event is on [Platforms](/products/conversions-api/platforms#test-mode-and-consent).

## Catch errors

<Tabs items={['Node.js', 'Python']}>
<Tab value="Node.js">
```typescript
import Zernio, { TrackError } from '@zernio/node';

const zernio = new Zernio();

try {
  await zernio.track('Purchase', { profileId: '66a1f0c2a4b9d3e8f1a2b3c4', value: 129.99, currency: 'EURO' });
} catch (error) {
  if (error instanceof TrackError) console.log(error.field, error.code, error.message);
}
```
</Tab>
<Tab value="Python">
```python
from zernio import Zernio, ZernioTrackError, ZernioValidationError

zernio = Zernio()

try:
    zernio.track("Purchase", profile_id="66a1f0c2a4b9d3e8f1a2b3c4", value=129.99, currency="EURO")
except ZernioValidationError as e:
    print(e.field, e)
except ZernioTrackError as e:
    print(e.field, e.code, e.status_code, e.event_id)
```
</Tab>
</Tabs>

| Node.js `TrackError` | Python `ZernioTrackError` | What it is |
|---|---|---|
| `field` | `field` | The `track()` option to fix, such as `currency` or `user.email`, when the API names one |
| `code` | `code` | The API's error code |
| `statusCode` | `status_code` | The HTTP status. Node.js sets `0` and Python `None` when the API could not be reached |
| `attempts` | `attempts` | Requests made. Node.js sets `0` when the input was refused before sending |
| `body` | `details` | The error body as the API sent it |
| Not available | `event_id`, `retry_after` | The event id, and the `Retry-After` the API asked for |

Where the SDKs differ:

- **Refused before sending.** Node.js throws `TrackError` with status `400` and code `invalid_track_input`. Python raises `ZernioValidationError`, with `field`.
- **Wrong key or no Ads add-on.** Node.js throws `TrackError`. Python raises `ZernioAuthenticationError` or `ZernioForbiddenError`.
- **API unreachable after every retry.** Node.js throws `TrackError` with `statusCode` `0` and the network error in `cause`. Python raises `ZernioTrackError` with `status_code` `None`.

## How it behaves

- **Retries.** Up to 3 attempts in total (`maxAttempts` in Node.js) on `429`, `409`, `5xx` and network failures, with backoff. A `Retry-After` is honoured up to 60 seconds in Node.js and 30 in Python; a longer one fails at once. Python also retries a timeout; Node.js does not retry a timeout or an abort.
- **No double sends.** Every attempt of one call carries the same `Idempotency-Key`, so a retry never sends the event twice. Each new call gets a new key.
- **Resending an event id.** Calling `track()` again with the same event id replaces the stored event, and the platforms drop the copy.
- **Refused before sending.** Both SDKs refuse a missing profile, an `email` or `phone` that looks hashed, and an event time in milliseconds. Node.js also refuses an empty event name. Python also refuses a datetime without a timezone and an unknown `user` key.
- **No forwarding rule.** The event is stored and the response carries a `no_destination` warning.

## If it fails

| Error | Cause | Fix |
|---|---|---|
| `invalid_track_input` or `ZernioValidationError` | An input the SDK refuses, named in `field` | Fix that option and call again |
| `403` `ads_addon_required` | The account has no Ads add-on | Add the Ads add-on |
| `400` with `field` | The API refused a value, such as `currency: 'EURO'` | Fix `field` and call again |
| `no_destination` warning | No forwarding rule took the event | Add a [forwarding rule](/products/server-side-tracking/ad-accounts) |
| `error` or `eventsFailed` on a destination | The platform refused the event | Read each failure's `message` |

## Related

- [Send events](/products/conversions-api/send)
- [Send events reference](/conversions/send-events)
- [Node.js SDK](/sdks/node)
- [Python SDK](/sdks/python)
- [Set up conversions with AI assistants](/products/conversions-api/ai-assistant)