# Server-side event tracking from your backend

> Track server-side analytics events by calling vibiz.user(userId).track() with @vibiz/app to record accurate conversions without cookies or client drops.

**You track server-side analytics events by calling `await vibiz.user(session.userId).track('EventName', { properties })` directly in your backend runtime with the `@vibiz/app` library.** This approach sends key lifecycle events—such as subscription upgrades, invoice settlements, or background worker jobs—straight from your server to your project analytics. Every event links to your visitor records without third-party tracking scripts, cookies, or stored IP addresses.

This guide covers how server-side tracking works, how to structure your payloads, and how to verify your event data from the CLI and API.

## Why track analytics events from your backend?

Client-side event tracking in the browser is helpful for interface interactions, but it is vulnerable to network drops, aggressive browser extensions, and early tab closures. If a customer closes their laptop lid right after authorizing a checkout, the browser may never fire your client-side conversion script.

Server-side event tracking solves this by recording events where your business logic runs:

- **Accuracy for critical business steps.** Upgrades, cancellations, account activations, and recurring billing happen on your servers. Tracking them on the backend guarantees that your analytics reflect actual database state.
- **Out-of-band updates.** Webhooks, automated renewal jobs, and asynchronous queue workers operate without any visitor browser active. Server-side tracking gives these background tasks a direct line into your analytics stream.
- **Privacy by default.** Client tracking often relies on third-party cookies or scripts that get blocked. thelastapi analytics uses no cookies and never stores visitor IP addresses. Countries are resolved via a local lookup table ([IP geolocation by DB-IP](https://db-ip.com)), keeping visitor tracking compliant and lightweight.

Pairing backend events with client data lets you see the entire journey, from the referrer documented in [Where your visitors come from: sources, countries and devices](https://thelastapi.dev/blog/visitor-sources-countries-devices) to the final database record.

## How to send server events with `@vibiz/app`

When building a Node.js or Next.js backend, install `@vibiz/app` and call the `track` method on the user scope.

```bash
npm install @vibiz/app
```

In your application code, pass the user identifier and your custom event payload:

```ts
import { vibiz } from '@vibiz/app';

interface UpgradePayload {
  userId: string;
  plan: string;
  seats: number;
}

export async function handlePlanUpgrade({ userId, plan, seats }: UpgradePayload) {
  // Update your database first
  // ...

  // Track the event on the server
  await vibiz.user(userId).track('Upgraded', {
    properties: {
      plan,
      seats,
    },
  });
}
```

One critical detail: **development keys do not record events**. If you call `vibiz.user().track()` in a local development environment using a local development key, the call will exit cleanly without writing data to your analytics totals. To test live tracking, deploy the code to a preview or production environment that uses your project's active credentials.

If you deploy your service to an external infrastructure provider rather than thelastapi hosting, you can still send server-side events using your project's API key. See [Run your app on another host with one key](https://thelastapi.dev/blog/run-app-on-another-host-one-key) for details on authenticating requests across outside environments.

## Event payload limits and rules

To keep analytics processing fast and predictable, server-side events must adhere to fixed data limits. Payloads that exceed these limits return an error.

| Constraint | Limit | What happens if exceeded |
| --- | --- | --- |
| Payload format | `text/plain` JSON | `400 invalid_request` |
| Maximum payload size | 8 KB | `400 invalid_request` |
| Maximum custom properties | 30 scalar properties | `400 invalid_request` |
| Property values | String, number, boolean (scalars only) | `400 invalid_request` |
| Domain origin | Registered project domain | `403 forbidden` |
| Bot traffic | Filtered automatically | Dropped silently |

Ensure your properties remain flat. Nested arrays or complex JSON objects should be simplified into top-level strings or numbers before sending:

```ts
// Valid payload
await vibiz.user('usr_123').track('Invoice Paid', {
  properties: {
    plan: 'enterprise',
    amount_usd: 1200,
    annual: true,
  },
});
```

Events are billed at **$0**. Recording analytics events and capturing session metadata adds no cost to your project.

## Connecting server events to client sessions

A server-side event is most useful when it ties back to the visitor who browsed your landing pages. thelastapi handles this connection through identity mapping.

### 1. Identify the user in the browser

On your frontend, include the analytics snippet. Once the user signs in or completes registration, call `identify`:

```html
<script defer src="https://thelastapi.dev/v1/script.js" data-key="vz_pk_..."></script>
<script>
  // After sign-in completes
  vibiz('identify', 'usr_123');
</script>
```

Calling `identify` takes the visitor's existing anonymous browser session (stored locally using a random id in `localStorage`) and links it to `usr_123`. If that person later logs in from another device, calling `identify` with the same ID links that new device to the same person.

When a user signs out, clear the mapping:

```html
<script>
  vibiz('identify', null);
</script>
```

### 2. Emit matching server events

Because the browser tied the visitor session to `usr_123`, any call to `vibiz.user('usr_123').track(...)` from your backend joins that visitor's timeline. You can see when they first visited via search or social, which landing page they viewed, and the exact backend transaction that followed. If you have session replay enabled, you can pair backend events with visual replays of their earlier browser behavior as outlined in [Session replay for a small site: masked, cheap and useful](https://thelastapi.dev/blog/session-replay-small-site).

## Handling domain restrictions and errors

The analytics engine accepts events only from the project's own domains. This includes your default `<slug>.vibiz.app` address and any custom domains added to your project.

If you send events from an unrecognized domain or outside your registered origins, the API rejects the request:

```bash
# Example error response when the origin does not match
{
  "code": "forbidden",
  "status": 403,
  "message": "The origin is not one of the project's domains"
}
```

To connect an outside domain, register it with the CLI:

```bash
vibiz domains add example.com --elsewhere
```

Here are the standard status codes returned by the analytics endpoint:

- **`401 unauthorized`**: The API key or `data-key` is missing or invalid. Check that your environment variables are loaded properly.
- **`403 forbidden`**: The request origin does not match any domain registered on the project. Add the domain with `vibiz domains add`.
- **`400 invalid_request`**: The event payload exceeds 8 KB, contains more than 30 properties, or contains non-scalar values like nested objects.
- **`429 rate_limited`**: Too many events were submitted simultaneously. Inspect the `Retry-After` header and apply exponential backoff.

## Reading your event data from the CLI and API

Once your server routes begin recording events, you can query totals and event breakdowns directly from your terminal or programmatically via the API.

To inspect recent metrics from the CLI:

```bash
vibiz analytics --period 7d
```

This displays total visitors, pageviews, referrers, geographic locations, device types, and custom event counts over the last seven days.

To read the raw data via HTTP:

```bash
curl "https://thelastapi.dev/v1/projects/prj_123/analytics?period=7d" \
  -H "Authorization: Bearer $VIBIZ_API_KEY"
```

The endpoint returns structured JSON summarizing your tracking metrics:

```json
{
  "totals": {
    "pageviews": 1420,
    "visitors": 812
  },
  "timeseries": [ ... ],
  "top_pages": [
    { "path": "/", "pageviews": 900 },
    { "path": "/pricing", "pageviews": 240 }
  ],
  "sources": [
    { "source": "Google", "visitors": 210 },
    { "source": "Direct", "visitors": 150 }
  ],
  "countries": [ ... ],
  "devices": [ ... ],
  "events": [
    { "name": "Upgraded", "count": 24 },
    { "name": "Invoice Paid", "count": 22 }
  ]
}
```

System monitors watch these traffic flows automatically. In [Mission Control and health checks](https://thelastapi.dev/docs/mission-control), background checks evaluate your project's traffic once an hour. If daily pageviews drop more than 60% below your 7-day average (once traffic reaches 20 a day), Mission Control alerts you with an amber status warning so you can investigate broken routes or failed deploys immediately.

Read the [Analytics and replay](https://thelastapi.dev/docs/analytics) documentation for complete snippet options, consent configurations, and export parameters.

## Frequently asked questions

### Do server-side analytics events record when running locally in development?

No. Development keys do not record analytics events or write data to project metrics. To test and verify your event tracking, deploy the code to a preview or production environment using active project credentials.

### How much does it cost to track server-side analytics events?

Analytics events are recorded at $0. There is no usage fee for tracking custom backend events or recording visitor pageviews.

### What are the payload limits for a custom server event?

An event payload must be valid JSON formatted as `text/plain` up to 8 KB in size. It can contain up to 30 custom properties, and all property values must be scalars (strings, numbers, or booleans). Nested arrays and objects are rejected.

### Why did my backend event return a 403 forbidden status?

A 403 status occurs when the event origin does not match one of your project's registered domains. You can authorize your domain by running `vibiz domains add <domain>`.

---

Published 2026-11-15 · https://thelastapi.dev/blog/server-side-event-tracking
