# HTTP ingest API

`POST /api/v1/ingest` accepts one JSON batch of product events, identify calls, or error reports. The browser client in `@visibling/sdk/browser` uses it directly in public-key mode, and a first-party proxy uses it with a server key. The same service backs the same-account Service Binding.

```text
POST https://visibling.com/api/v1/ingest
content-type: application/json
x-visibling-key: vis_srv_your_key
```

## Authentication

Send the key in either header:

- `x-visibling-key: <key>` — preferred.
- `Authorization: Bearer <key>` — accepted when `x-visibling-key` is absent.

Three key kinds exist:

| Key | Prefix | Can ingest | Notes |
| --- | --- | --- | --- |
| Server | `vis_srv_` | yes | Trusted enrichment: may set `distinctId`, `email`, `userName`, `plan`, `externalOrgId`, and `errorSource`. Never ship it to a browser. |
| Public | `vis_pub_` | yes | Browser credential. Cannot set `plan` or `externalOrgId`; `errorSource` is forced to `browser`; the project's allowed origins are enforced. |
| Source map | `vis_map_` | no | Upload-only; ingest answers `403`. |

## Request body

The only accepted envelope is an object with an `items` array of 0–100 items. An empty array is valid: the batch answers `202` with every counter at zero.

```json
{
  "items": [
    {
      "type": "track",
      "name": "checkout_started",
      "distinctId": "user_123",
      "props": { "plan": "starter", "items": 3 }
    }
  ]
}
```

The request body is capped at 64 KB (64 × 1024 bytes) before parsing. Items after the first 100 are dropped and counted in `droppedInvalid`.

### Item fields

| Field | Type | Required | Caps and behavior |
| --- | --- | --- | --- |
| `eventId` | string | no | 1–64 chars. A unique id is generated when absent. |
| `type` | `pageview` \| `track` \| `identify` \| `error` \| `agent` | yes | Event kind. `agent` is accepted only with a server ingest key. |
| `name` | string | yes | 1–128 chars after trimming. Stored trimmed. |
| `ts` | string | no | ≤40 chars. RFC3339 client time; missing, unparseable, or more than 24 hours in the future falls back to server receipt time. |
| `distinctId` | string | no | 1–256 chars. Trusted user id. |
| `anonId` | string | no | 1–256 chars. Browser-owned anonymous id. |
| `sessionId` | string | no | ≤128 chars. |
| `release` | string | no | ≤128 chars. |
| `environment` | string | no | ≤64 chars. Defaults to `production` for error issues. Use exactly `internal` (lowercase) to mark internal/test traffic: product analytics excludes it by default. |
| `path` | string | no | ≤1024 chars in the payload; stored as a query-free path capped at 512 chars. |
| `url` | string | no | ≤2048 chars. Used as the path when `path` is absent. Query strings and fragments are stripped. |
| `referrerHost` | string | no | ≤256 chars. Reduced to a bare host. |
| `country` | string | no | ≤8 chars. The Cloudflare edge country wins when present. |
| `deviceType` | `desktop` \| `mobile` \| `tablet` \| `bot` \| `unknown` | no | Derived from the user agent when absent. |
| `cfRay` | string | no | ≤128 chars. The edge `cf-ray` wins when present. |
| `traceId` | string | no | ≤128 chars. |
| `props` | object | no | Custom properties. Serialized to at most 4 KB; an oversized object becomes `{"_truncated":true}`. |
| `email` | string | no | Valid email, ≤320 chars. |
| `userName` | string | no | ≤256 chars. |
| `externalOrgId` | string | no | ≤256 chars. Server enrichment only. |
| `plan` | string | no | ≤64 chars. Server enrichment only. |
| `traits` | object | no | Identify traits, ≤8 KB. Merged into the same 4 KB props column as `props`; an over-budget merge truncates the stored props. |
| `errorSource` | `browser` \| `worker` \| `cf_issues` | no | Error items. Public keys are always recorded as `browser`. |
| `errorLevel` | `fatal` \| `error` \| `warning` | no | Error items. Defaults to `error`. |
| `errorType` | string | no | ≤128 chars. Defaults to the event name. |
| `errorMessage` | string | no | ≤2048 chars. Defaults to the event name. |
| `stack` | string | no | ≤16 KB. |
| `breadcrumbs` | array | no | Up to 20 entries of `{ ts, category, message, data }`; category ≤64 chars, message ≤512 chars. The whole serialized trail is capped at 16 KB; a larger trail is omitted rather than truncated. |

Each item is validated independently. A malformed item is counted in `droppedInvalid` while its valid neighbours are still accepted, so one bad event never drops a batch.

### Event shapes

- `pageview`: requires `type` and `name` (the browser client sends `$pageview`). `path` identifies the page.
- `track`: requires `type` and `name`; `props` carries custom dimensions.
- `identify`: requires `type` and `name` (the browser client sends `$identify`) plus `distinctId` or `anonId` to upsert an end user. `traits`, `email`, `userName`, `plan`, and `externalOrgId` enrich the user directory.
- `error`: requires `type` and `name`; `errorType`, `errorMessage`, `stack`, `breadcrumbs`, `errorSource`, and `errorLevel` describe the failure.
- `agent`: AI agent and MCP request telemetry. `name` is `$agent_request` or `$mcp_call` (`AGENT_EVENT_NAMES`). Accepted only with a server ingest key: `agent` items sent with a `vis_pub_` key are dropped and counted in `droppedInvalid`, so a browser cannot fabricate agent analytics. `deviceType` is always stored as `bot`, and PII properties (`ip`, `userAgent`, `authorization`, `cookie`, `x-forwarded-for`, `cf-connecting-ip`, …) are stripped before storage. Distinct ids use the daily `agent:<utcDate>:<family>:<nickname>` convention, so an agent's requests stitch within one UTC day but rotate daily.

Client-supplied timestamp, path, referrer, country, and device type are advisory. The service normalizes them, and trusted edge values override browser values.

## Response

A successful batch answers `202 Accepted`:

```json
{
  "ok": true,
  "accepted": 1,
  "droppedInvalid": 0,
  "droppedQuota": 0
}
```

- `accepted` — items written to the event store.
- `droppedInvalid` — items that failed validation or exceeded the 100-item batch cap.
- `droppedQuota` — valid items dropped because the organization reached a monthly plan cap.

## Status codes

| Status | Meaning |
| --- | --- |
| `202` | Batch accepted. Individual items may still have been dropped; inspect the counters. |
| `400` | Body is not valid JSON, or is not a JSON object with an `items` array. |
| `401` | Missing, invalid, or revoked ingest key. |
| `403` | A source map key tried to ingest events; a public key is not allowed from this origin; or the endpoint requires a server key. |
| `413` | Body exceeds 64 KB. |
| `429` | Project rate limit exceeded. Retry after the `Retry-After: 60` header. |
| `500` | Internal delivery failure. The batch may be retried; delivery is at-least-once. |
| `503` | The deployment is missing required ingest bindings. |

## Quotas are soft

When an organization reaches its monthly product-event or error-event cap, Visibling keeps accepting requests: the batch still answers `202` and the events that no longer fit are counted in `droppedQuota`. Events are admitted in order, so a batch that crosses a cap keeps everything under it. Clients never see a 4xx or 5xx because a quota was reached. `SELF_HOSTED=true` deployments have no caps and never drop for quota.

Invalid items and items beyond the batch cap are likewise reported through counters rather than a request-level error.

## CORS

Browser callers are first-class on this endpoint:

- `OPTIONS /api/v1/ingest` answers `204` without requiring a key.
- Responses echo the request `Origin` and set `Vary: Origin`.
- Allowed methods: `POST, OPTIONS`. Allowed headers: `content-type, x-visibling-key, authorization`.
- Preflight cache: 86400 seconds.

CORS is not authorization: a browser on any origin still needs a valid key. When a project configures allowed origins, a public key is accepted only from an exact origin match.

## Rate limits

Ingest is rate-limited per project. A rejected call answers `429` with `Retry-After: 60`. Failed requests, revoked keys, and quota drops do not consume the project's monthly counters.

## Example

```sh
curl -i -X POST https://visibling.com/api/v1/ingest \
  -H 'content-type: application/json' \
  -H 'x-visibling-key: vis_srv_your_key' \
  -d '{
    "items": [
      {
        "type": "track",
        "name": "report_exported",
        "distinctId": "user_123",
        "props": { "format": "csv", "rows": 4200 }
      }
    ]
  }'
```

```text
HTTP/2 202
content-type: application/json
cache-control: no-store

{"ok":true,"accepted":1,"droppedInvalid":0,"droppedQuota":0}
```
