# Analytics

First-party page, screen and event counts without cookies or identifiers, shown to platform admins on /admin/analytics.

## What it does [#what-it-does]

The site, the signed-in web app and the mobile app send a light count of each page or screen view to our own server. The server keeps totals per day: views by page and source, named events, countries, referrers, device and browser classes, and how many views came with analytics consent. Platform admins read them on `/admin/analytics`, with a chart of views per day by source, release and campaign annotations, and, when configured, Cloudflare's own numbers marked "CF".

It is the always-on destination of the analytics relay, `POST /api/events`. Mixpanel or PostHog stay optional: a provider adapter receives only batches sent with the visitor's analytics consent (see [Providers](#optional-providers)). None ships with the template.

## What is kept, and what is not [#what-is-kept-and-what-is-not]

| Kept (per event, for at most 30 days, then only as daily totals)                                                            | Never kept                                                           |
| --------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| The source: `site` (public pages), `web` (signed-in app), `mobile`                                                          | Cookies, local or session storage                                    |
| The path without its query; on signed-in screens and in the app, the route pattern (`/todos/$todoId`, `/(tabs)/todos/[id]`) | The query string (except `utm_source`, `utm_medium`, `utm_campaign`) |
| The referrer's host when it is another site                                                                                 | The referrer's path or query                                         |
| The country from the edge (`cf-ipcountry`)                                                                                  | The IP address                                                       |
| A device class and a browser family, as small codes                                                                         | The user agent                                                       |
| Whether the visitor had granted analytics consent                                                                           | Any user, session, device or visitor id                              |

A raw row cannot be linked to the next one from the same visitor, so "unique visitors" cannot be counted here; that number comes from Cloudflare and includes bots. Bots (by user agent), a request from another site's page (`Origin`) and an automated browser (`navigator.webdriver`, which sends nothing) are left out; the server answers them with the same `204` as a counted view.

**Privacy note.** Counting without cookies or identifiers usually needs no consent banner entry under the LGPD and the GDPR, but that is a legal judgement for the project: confirm it with your data protection owner (DPO/encarregado) before launch, and mention the counting in the privacy policy. The relay's rate limiter keys its counter by an HMAC of the address (`rate_limit`, deleted within a day by the auth cleanup); the address itself is never stored.

## The relay: `POST /api/events` [#the-relay-post-apievents]

Same shape as `/api/events/web-vitals`: a body of at most 4 KB, the Zod schema `analyticsRelayBatch` from `@template-cloudflare/api/analytics/contract` or `400`, `204` with `Cache-Control: no-store`.

```json
{
  "source": "site",
  "consent": false,
  "events": [
    {
      "type": "page_view",
      "path": "/pricing?utm_source=newsletter",
      "referrer": "https://news.example.org/a"
    }
  ]
}
```

- `events` holds 1 to 10 items: `page_view` (with an optional `referrer`) or `event` with a `name` from `ANALYTICS_EVENT_NAMES` (`packages/db/src/schema/analytics.enums.ts`). A name outside the catalog is refused, so an event can never carry free text. Add a name there, and its label in every web catalog (`ANALYTICS_EVENT_*`), to count a new event.
- `platform` (`ios` or `android`) is sent by the mobile app instead of a browser user agent.
- 60 requests a minute per address, counted in the database so it works on Node as on Workers; above that, `429` with `Retry-After`.

Clients:

- **Web**: `usePageViews` (`apps/web/src/platform/analytics/page-views.ts`) starts after hydration and sends one `sendBeacon` per resolved navigation ([W15](/docs/development/web-conventions)). `trackAnalyticsEvent("sign_up")` counts an event on the current page.
- **Mobile**: `useScreenViews` (`apps/mobile/src/platform/analytics/screen-views.ts`) posts each screen's route pattern from expo-router's segments. The app asks for no analytics consent yet, so its views are sent as not consented.

## Storage and isolation [#storage-and-isolation]

Platform data, not an Organization's. Every table has row-level security and no `app_tenant` policy or grant, so tenant traffic sees nothing (proved by `packages/db/src/rls-analytics.test.ts` in `test:rls-matrix`, pipelining on and off). The relay writes through `asSystem(db, "analytics-ingest", …)`, the admin reads through `asSystem(db, "analytics-admin", …)` and the cron through its tick.

| Table                       | Holds                                                                                                |
| --------------------------- | ---------------------------------------------------------------------------------------------------- |
| `analytics_event_raw`       | One row per counted event, until folded and 30 days old                                              |
| `analytics_page_daily`      | Views per UTC day, source and path; `source = 'import'` for imported days                            |
| `analytics_event_daily`     | Named events per day, source and name                                                                |
| `analytics_consent_daily`   | Views and events sent with consent, per day, source and kind                                         |
| `analytics_dimension_daily` | Views per day, source and one breakdown (country, referrer, device, browser, UTM source or campaign) |
| `analytics_cf_daily`        | Cloudflare's zone totals per day (requests, page views, uniques, threats)                            |
| `analytics_annotation`      | Releases, campaigns, press, incidents; `external_id` unique                                          |

Days are UTC days.

## The rollup, in the one-minute cron [#the-rollup-in-the-one-minute-cron]

`pendingAnalytics` (`packages/api/src/features/analytics/analytics.jobs.ts`) runs in the existing tick ([scheduled jobs](/docs/features/scheduled-jobs)); nothing is buffered in memory between requests.

1. **Release annotation.** The first tick of a new Worker version writes an annotation with `external_id = worker-version:<id>` from the `CF_VERSION_METADATA` binding; the unique index makes every later tick, isolate or older version a no-op. A version older than a day is left alone, so an annotation an admin deleted stays deleted. PR previews have no binding and write none.
2. **Rollup.** Under the `analytics-rollup` lease (`job_cursor`, the webhook trigger cursor's pattern) it folds the window (watermark, upto] into the daily tables and moves the watermark in the same transaction, so a failed tick folds nothing and a repeated one adds nothing. `upto` stays 5 seconds behind `now()` for inserts still committing; a window covers at most one hour of arrivals and starts at the next waiting row, so a quiet night costs one window. Up to six windows run per tick.
3. **Retention.** Once an hour (minute 23), raw rows older than 30 days and already folded are deleted in bounded batches. The daily totals stay.
4. **Cloudflare sync** (optional, below).

## Cloudflare's numbers ("CF") [#cloudflares-numbers-cf]

Set `CLOUDFLARE_ANALYTICS_TOKEN` (a Worker secret: an API token with **Zone → Analytics → Read** on the zone) and `CLOUDFLARE_ANALYTICS_ZONE_ID` (a var). Every 30 minutes, under its own lease, the cron reads `httpRequests1dGroups` from the GraphQL Analytics API (30 days back the first time, then the last 3) into `analytics_cf_daily`. A failure is logged as `analytics.cf_sync_failed` with its kind and HTTP status only, never the token, and retried 30 minutes later. The admin page shows the sum of daily uniques in a dimmed card marked "CF": distinct IPs per day, bots included, not comparable to our counts.

## Imported days [#imported-days]

Days counted by another tool can be written to `analytics_page_daily` with `source = 'import'` (by SQL or a script of the project's own); the chart draws them hatched and the KPI totals include them. The relay never writes that source.

## The admin page [#the-admin-page]

`/admin/analytics` (`apps/web/src/features/analytics`), in the Admin navigation group:

- Periods of 7, 14, 30 and 90 days (`?days=`), compared with the period before.
- KPI cards: views (with a daily sparkline), events, countries, share with consent (dimmed), active sources, unique visitors "CF" (dimmed).
- Views per day stacked by source (Bklit `ComposedChart`), imported days hatched, releases as markers and campaigns (an annotation with an end day) as bands; the annotation list with add and delete.
- Top pages, countries, referrers and events on the shared data table.

### Who may see it [#who-may-see-it]

Platform admins, proven against the database on every call (`adminProcedure`). The screen's permission is named in `ANALYTICS_PERMISSION` (`analytics:read`, and `analytics:annotate` for the writes) in `analytics.procedures.ts`: once platform roles exist, the procedures' base becomes `platformProcedure(ANALYTICS_PERMISSION.read)` and nothing else changes, because the service already takes `systemDb` and crosses tenants itself.

| Procedure                          | Who             | Failures                                  |
| ---------------------------------- | --------------- | ----------------------------------------- |
| `admin.analytics.overview`         | Platform admins | `BAD_REQUEST` (a period not offered)      |
| `admin.analytics.createAnnotation` | Platform admins | `BAD_REQUEST` (end before start, bad URL) |
| `admin.analytics.deleteAnnotation` | Platform admins | `NOT_FOUND`                               |

## Optional providers [#optional-providers]

`CONSENTED_PROVIDERS` in `analytics.providers.ts` is the seam: an adapter implements `AnalyticsProvider` (`forward(batch, signal)`) and is listed there behind its own configuration (the analytics plan names `ANALYTICS_PROVIDERS`). The relay calls it only for a batch with `consent: true`, after the count, in `waitUntil`, with a 5-second timeout; a failure is logged by provider name and never reaches the visitor. The template lists none.

## Why Postgres and not Workers Analytics Engine [#why-postgres-and-not-workers-analytics-engine]

The counts join annotations and consent in one database, work the same on Cloudflare and on a Node/VPS deploy, and the expected volume (thousands of people) is small. Analytics Engine would be cheaper at scale but exists only on Cloudflare.

## Key files [#key-files]

- [`packages/api/src/features/analytics/analytics.http.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/analytics/analytics.http.ts) and [`analytics.normalize.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/analytics/analytics.normalize.ts): the relay and what it keeps
- [`analytics.rollup.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/analytics/analytics.rollup.ts), [`analytics.cloudflare.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/analytics/analytics.cloudflare.ts), [`analytics.release.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/analytics/analytics.release.ts): the cron's work
- [`analytics.service.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/analytics/analytics.service.ts) and [`analytics.procedures.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/features/analytics/analytics.procedures.ts): the admin queries
- [`packages/db/src/schema/analytics.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/db/src/schema/analytics.ts): the tables
- [`apps/web/src/platform/analytics/page-views.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/apps/web/src/platform/analytics/page-views.ts) and [`apps/mobile/src/platform/analytics/screen-views.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/apps/mobile/src/platform/analytics/screen-views.ts): the clients
