# SiteBeacon API — LLM Integration Guide

You are an autonomous agent that has been given a **base URL** and an **API key** for the service documented below. This document is self-contained: it tells you everything needed to call the API. Follow it literally.

- **Base URL:** `https://sitebeacon.eu`
- **API key:** provided to you separately; it starts with `sk_`.
- **All paths below are relative to the base URL** (e.g. `https://sitebeacon.eu/api/v1/health`).

> Generated from the app's single source of truth. If an endpoint
> behaves differently from what you read here, trust the live response
> and report the mismatch — the docs are meant to be authoritative.

## Essentials

### Base URL

All endpoints live under `https://sitebeacon.eu/api/v1`. `https://sitebeacon.eu` is the origin you were given (scheme + host, e.g. `https://example.com`). Do not add a trailing slash.

### Authentication

Endpoints marked "Bearer token" require a personal API key sent as a Bearer token:
`Authorization: Bearer sk_your_key_here`. Keys always start with `sk_`. A missing or invalid key returns `401 { "error": "Invalid or missing API key" }`. Create keys in the app under Settings → API Keys. `POST /api/v1/collect` takes a site secret (`ssk_…`) instead, and the browser ingest `POST /api/event` is open.

### Two kinds of keys

Reading statistics (`/api/v1/sites…`) uses your personal API key (`sk_…`, Settings → API Keys). Sending events from a server (`POST /api/v1/collect`) uses the SITE secret (`ssk_…`) shown when the site is created (Site → Settings → Install → Server; it can be rotated there). A site secret can only write events for its one site — it can read nothing — so it is safe to deploy on a web server.

### Privacy model

No cookies, no client storage. A visitor is identified by a hash of (daily-rotating salt, site, IP, User-Agent); the salt is deleted after its UTC day and the IP is never stored. Visits (sessions) end after 30 minutes of inactivity. Send the end-user's real IP and User-Agent with server events so visitors and sessions are counted correctly.

### Periods and filters

Stats endpoints take `period` = `today` | `24h` | `7d` | `30d` (default) | `90d` | `12mo`, evaluated in the site's time zone, and optional filters `page`, `source`, `country` (ISO-3166 alpha-2), `browser`, `os`, `device` (`desktop`|`mobile`|`tablet`), `campaign` (utm_campaign) and `event` (keeps whole visits that fired that event — a goal filter). Use the value `(none)` to select rows where a dimension is unknown.

### Content type

Responses are JSON unless noted (file download returns raw bytes). Request bodies are JSON (`Content-Type: application/json`) except file upload, which is `multipart/form-data`.

### Rate limiting

Requests are rate limited per API key. When you exceed a limit you get `429` (or `403` if the limit is configured to block) with an `error` message and, when applicable, a `Retry-After` header (seconds). Back off and retry.

### Errors

Errors are JSON with an `error` string and a matching HTTP status (`400` bad input, `401` unauthenticated, `403` forbidden, `404` not found, `413` payload too large, `429` rate limited, `500` server error).

## Quick start

```bash
# 1. Verify your key works
curl https://sitebeacon.eu/api/v1/health -H "Authorization: Bearer sk_your_key_here"
# A 200 with {"status":"healthy",...} means you are authenticated.
```

## Endpoints

### GET /api/v1/health

**Health check** — Confirms the API is up and your key is valid. Handy as a first call to verify credentials and connectivity.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key.

**Request**

```bash
curl https://sitebeacon.eu/api/v1/health \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "status": "healthy",
  "timestamp": "2026-07-19T12:00:00.000Z",
  "uptime": 1234.56,
  "version": "1.0.0",
  "apiKey": "My key",
  "userId": "usr_...",
  "message": "API is running successfully"
}
```

---

### GET /api/v1/stats

**Account & API usage stats** — Returns the calling user together with API-usage counters (requests today / this week / this month, error rate, API-key count).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key (scoped to the key owner).

**Request**

```bash
curl https://sitebeacon.eu/api/v1/stats \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "user": { "id": "usr_...", "email": "you@example.com", "name": "You", "role": "user", "createdAt": "..." },
  "apiStats": {
    "totalApiKeys": 2,
    "requestsToday": 14,
    "requestsThisWeek": 98,
    "requestsThisMonth": 412,
    "errorRate": "1.20%",
    "errorCount": 5
  },
  "meta": { "timestamp": "...", "apiKey": "My key" }
}
```

---

### GET /api/v1/users

**List users** — Lists users. A regular key returns only its own user record; an admin key returns all users with pagination.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key (admin keys see all users; others see themselves).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `limit` | query | integer | no | Page size, 1–100 (default 10). Admin only; ignored for non-admins. |
| `offset` | query | integer | no | Rows to skip (default 0). Admin only. |

**Request**

```bash
curl "https://sitebeacon.eu/api/v1/users?limit=20&offset=0" \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "users": [
    { "id": "usr_...", "email": "you@example.com", "name": "You", "role": "user", "emailVerified": null, "createdAt": "..." }
  ],
  "meta": { "limit": 20, "offset": 0, "total": 1, "apiKey": "My key" }
}
```

---

### POST /api/v1/users

**Create user (scaffold)** — Admin-only endpoint scaffold for creating a user. Ships as a stub in this starter — it validates input and echoes it back rather than persisting. Fill in real creation logic before relying on it.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Admin API keys only (others get 403).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `email` | body | string | yes | New user email. |
| `name` | body | string | yes | New user display name. |
| `role` | body | string | no | 'user' (default) or 'admin'. |

**Request**

```bash
curl -X POST https://sitebeacon.eu/api/v1/users \
  -H "Authorization: Bearer sk_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"email":"new@example.com","name":"New User","role":"user"}'
```

**Response**

```
{
  "message": "User creation endpoint - implementation needed",
  "requestedData": { "email": "new@example.com", "name": "New User", "role": "user" },
  "apiKey": "My key"
}
```

> This is a template stub — no user is actually created yet.

---

### POST /api/v1/files

**Upload a file** — Uploads a file and stores its raw bytes. Use this instead of a form/Server Action for any real upload (Server Actions cap the body at ~1MB; this endpoint does not). Send `multipart/form-data` with a single `file` field.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key (the file is owned by the key owner).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `file` | form | file | yes | The file to upload (multipart field name must be "file"). |

**Request**

```bash
curl -X POST https://sitebeacon.eu/api/v1/files \
  -H "Authorization: Bearer sk_your_key_here" \
  -F "file=@./photo.png"
```

**Response**

```
{
  "id": "fil_...",
  "filename": "photo.png",
  "url": "/api/v1/files/fil_..."
}
```

> Default max size is 100MB (configurable via MAX_FILE_SIZE). Oversized uploads return 413.
>
> The returned `url` is the Bearer-gated download endpoint below.

---

### GET /api/v1/files/:id

**Download / preview a file** — Streams the raw file bytes with the stored Content-Type. Because it is Bearer-gated you cannot put it directly in an `<img src>`; fetch it with the token and build an object URL client-side.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | File id returned by the upload endpoint. |

**Request**

```bash
curl https://sitebeacon.eu/api/v1/files/fil_your_file_id \
  -H "Authorization: Bearer sk_your_key_here" \
  --output downloaded-file
```

**Response**

```
Raw binary body with the stored `Content-Type` and `Content-Disposition: inline; filename="..."`. Returns `404 { "error": "File not found" }` if unknown.
```

---

### DELETE /api/v1/files/:id

**Delete a file** — Deletes a file owned by the calling key.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key (only the owner may delete).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | File id to delete. |

**Request**

```bash
curl -X DELETE https://sitebeacon.eu/api/v1/files/fil_your_file_id \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{ "deleted": true }   // { "deleted": false } with status 404 if not found / not owned
```

---

### POST /api/v1/collect

**Send events from a server** — Records pageviews and custom events server-side — for server-rendered sites, backends, apps or anywhere JavaScript does not run. Send ONE event object or an ARRAY of up to 100. An event named `pageview` (the default when `name` is omitted) counts as a pageview; any other name is a custom event/goal. Pass the end-user's IP and User-Agent so visitors and visits are counted (they are hashed with a daily salt, never stored).

- **Auth:** `Authorization: Bearer ssk_...` (the SITE secret, not a user key) required
- **Access:** The site whose secret (`ssk_…`) is used. Write-only.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `name` | body | string | no | 'pageview' (default) or a custom event name, ≤120 chars. |
| `url` | body | string | yes | Absolute http(s) URL of the page, or a path starting with `/` (the site domain is assumed). UTM params in it are recorded. |
| `ip` | body | string | no | The visitor's IP (hashed, never stored). Strongly recommended. |
| `userAgent` | body | string | no | The visitor's User-Agent (browser/OS/device + visitor hash). |
| `referrer` | body | string | no | Referer header of the original request (query string is dropped). |
| `country` | body | string | no | ISO-3166 alpha-2 country code if you know it (e.g. from CF-IPCountry). |
| `visitor` | body | string | no | Your own stable, already-anonymised visitor key — used INSTEAD of ip+userAgent for identity. |
| `props` | body | object | no | Flat map of custom properties (string/number/boolean, ≤30 keys, values ≤256 chars). |
| `timestamp` | body | string|number | no | ISO-8601 or epoch-ms; defaults to now. May be up to 7 days in the past, never in the future. |

**Request**

```bash
curl -X POST https://sitebeacon.eu/api/v1/collect \
  -H "Authorization: Bearer ssk_your_site_secret" \
  -H "Content-Type: application/json" \
  -d '[{"name":"pageview","url":"https://example.com/pricing","ip":"203.0.113.7","userAgent":"Mozilla/5.0 ...","referrer":"https://www.google.com/"},
       {"name":"Purchase","url":"/checkout","ip":"203.0.113.7","userAgent":"Mozilla/5.0 ...","props":{"plan":"pro"}}]'
```

**Response**

```
{
  "accepted": 2,
  "results": [
    { "index": 0, "stored": true },
    { "index": 1, "stored": true }
  ]
}
```

> Returns 202 when at least one event was accepted, 400 when all failed (each result carries its own `error`), 401 for a bad/missing site secret, 413 for >100 events, 429 when rate limited.
>
> Bot User-Agents are silently skipped (`stored: false, reason: "bot"`) unless you pass `visitor`.
>
> Ready-made clients: GET /scripts/sitebeacon.mjs (Node), /scripts/sitebeacon.py (Python), /scripts/sitebeacon.php (PHP).

---

### POST /api/event

**Browser ingest (used by /a.js)** — The endpoint the `/a.js` snippet beacons to. Public and CORS-open; bodies are `text/plain` JSON so no preflight is needed. You normally never call it directly — embed `<script defer data-site="st_…" src="{BASE_URL}/a.js"></script>` and call `sitebeacon('EventName', { props: {…} })` for custom events. Hits whose page hostname is not the site's domain (or a subdomain) are ignored.

- **Auth:** none
- **Access:** Anyone who knows the public site id (`st_…`).

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `s` | body | string | yes | Public site id (`st_…`). |
| `k` | body | string | yes | 'pageview' \| 'event' \| 'engage'. |
| `u` | body | string | yes | Page URL (pageview/event). |
| `n` | body | string | no | Event name (k=event). |
| `r` | body | string | no | document.referrer. |
| `tz` | body | string | no | IANA time zone — used to derive the country when no CDN country header exists. |
| `pv` | body | string | no | Random per-pageview id; lets later `engage` pings add visible time to it. |
| `e` | body | integer | no | Engaged (visible) milliseconds on the page (k=engage). |
| `p` | body | object | no | Custom event properties (k=event). |

**Request**

```bash
curl -X POST https://sitebeacon.eu/api/event \
  -H "Content-Type: text/plain" \
  -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/128 Safari/537.36" \
  -d '{"s":"st_your_site_id","k":"pageview","u":"https://example.com/","r":"https://duckduckgo.com/","tz":"Europe/Amsterdam"}'
```

**Response**

```
`202 Accepted` with an empty body (also for ignored hits). `400`/`404`/`413`/`429` carry `{ "error": "..." }`.
```

---

### GET /api/v1/sites

**List your sites** — Every site owned by the key owner (in the key's tenant when multi-tenant mode is on).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key (own sites only).

**Request**

```bash
curl https://sitebeacon.eu/api/v1/sites \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "sites": [
    {
      "id": "st_2O8iQhfAz3yg",
      "name": "Demo store",
      "domain": "example.com",
      "timezone": "Europe/Amsterdam",
      "public": false,
      "firstEventAt": "2026-07-02T22:07:22.000Z",
      "createdAt": "2026-07-02T09:39:44.000Z"
    }
  ]
}
```

---

### GET /api/v1/sites/:id/stats

**Summary + time series** — Headline metrics for the period (and the previous period of equal length, for comparison) plus a visitors/visits/pageviews series bucketed by hour (today, 24h), day (7d–90d) or month (12mo) in the site's time zone.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key that owns the site.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Site id (`st_…`). |
| `period` | query | string | no | today \| 24h \| 7d \| 30d (default) \| 90d \| 12mo. |
| `page, source, country, browser, os, device, campaign, event` | query | string | no | Optional filters (see Essentials → Periods and filters). |

**Request**

```bash
curl "https://sitebeacon.eu/api/v1/sites/st_your_site_id/stats?period=7d&country=NL" \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "site": { "id": "st_…", "name": "Demo store", "domain": "example.com", "timezone": "Europe/Amsterdam" },
  "period": "7d",
  "from": "2026-09-23T22:00:00.000Z",
  "to": "2026-09-30T10:00:00.000Z",
  "granularity": "day",
  "filters": { "country": "NL" },
  "summary":  { "visitors": 1301, "visits": 1452, "pageviews": 3081, "events": 320, "viewsPerVisit": 2.12, "bounceRate": 40.4, "avgDurationSec": 141 },
  "previous": { "visitors": 1176, "visits": 1290, "pageviews": 2732, "events": 299, "viewsPerVisit": 2.12, "bounceRate": 38.1, "avgDurationSec": 138 },
  "timeseries": [ { "bucket": "2026-09-24", "visitors": 218, "visits": 240, "pageviews": 515 } ]
}
```

> `bounceRate` is a percentage (0–100) of visits with a single pageview and no events; `avgDurationSec` is the average visible (engaged) time per visit.
>
> Visitors are unique per UTC day by design (the hash salt rotates daily), so multi-day totals count a returning person once per day.

---

### GET /api/v1/sites/:id/breakdown

**Top values of a dimension** — Ranks the values of one dimension by unique visitors for the period, honouring the same filters as /stats.

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key that owns the site.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Site id (`st_…`). |
| `dimension` | query | string | yes | page \| entry \| exit \| source \| referrer \| campaign \| medium \| country \| browser \| os \| device \| event. |
| `period` | query | string | no | As for /stats (default 30d). |
| `limit` | query | integer | no | Rows to return, 1–500 (default 10). |
| `page, source, country, browser, os, device, campaign, event` | query | string | no | Optional filters. |

**Request**

```bash
curl "https://sitebeacon.eu/api/v1/sites/st_your_site_id/breakdown?dimension=source&period=30d&limit=5" \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "dimension": "source",
  "period": "30d",
  "filters": {},
  "rows": [
    { "value": "Google", "visitors": 1972, "pageviews": 4679, "count": 5161 },
    { "value": "Direct / None", "visitors": 1715, "pageviews": 4135, "count": 4556 }
  ]
}
```

> `count` = matching rows (for `event`: times the event fired; for `entry`/`exit`: visits that started/ended there). `value` is null when unknown.

---

### GET /api/v1/sites/:id/realtime

**Realtime visitors** — Unique visitors and pageviews in the last 5 minutes, the top 5 active pages, and pageviews per minute for the last 30 minutes (index 0 = 29 minutes ago).

- **Auth:** `Authorization: Bearer sk_...` required
- **Access:** Any valid API key that owns the site.

**Parameters**

| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Site id (`st_…`). |

**Request**

```bash
curl https://sitebeacon.eu/api/v1/sites/st_your_site_id/realtime \
  -H "Authorization: Bearer sk_your_key_here"
```

**Response**

```
{
  "visitors": 3,
  "pageviews": 4,
  "pages": [ { "path": "/pricing", "visitors": 2 } ],
  "perMinute": [ { "minute": 29, "pageviews": 0 }, "…", { "minute": 0, "pageviews": 2 } ]
}
```

---

## Notes for automated callers

- Always send the `Authorization: Bearer sk_...` header; there is no cookie/session auth here.
- On `429`/`403` with a `Retry-After` header, wait that many seconds before retrying.
- Treat any non-2xx JSON `error` field as the human-readable failure reason.
- File downloads (`GET /api/v1/files/:id`) return raw bytes, not JSON.
