# 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 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                                          |
| `analytics_time_zone`       | Which time zone cut the days from which instant ([Days and the time zone](#days-and-the-time-zone))  |

## Days and the time zone [#days-and-the-time-zone]

A day is a calendar day in one IANA time zone per deployment: `ANALYTICS_TIME_ZONE` (a Worker var, not a secret), `UTC` when unset. For a Brazilian audience set `America/Sao_Paulo`, so an evening visit counts on its own day and not the next. The zone must be an IANA name both the runtime and PostgreSQL know (`pg_timezone_names`); an offset such as `-03:00` is refused at startup, because PostgreSQL reads a bare offset with the opposite sign. Daylight saving time follows the zone's rules: in `Europe/Berlin` the last Sunday of March has 23 hours and the last Sunday of October 25.

Everything uses the same zone:

- **Rollup.** A raw row lands on its arrival's date in the zone in effect at its arrival (`analytics_time_zone`, below).
- **Retention.** The sweep deletes raw rows of days more than 30 days before today, cut at a midnight of the zone, so a day's raw rows go together.
- **Admin page.** The period ends today in the zone, the chart says which zone its days are in, and an annotation's day is its date in the zone in effect at its instant; a new annotation starts at its first day's midnight there.
- **Cloudflare sync.** Its window covers the zone's days as well as Cloudflare's. Cloudflare's daily groups (`httpRequests1dGroups`) are keyed by a calendar `date`, which the template treats as Cloudflare's UTC date, and the [GraphQL Analytics API docs](https://developers.cloudflare.com/analytics/graphql-api/features/filtering/) offer no time zone argument; distinct IPs come per day or per hour, and hourly ones cannot be summed into a day. So a Cloudflare row keeps Cloudflare's date and the "CF" card sums the dates of the period. With another zone the card says it counts UTC days, and it is off by the zone's offset at each end of the period.

### Changing the zone [#changing-the-zone]

The first rollup writes the configured zone into `analytics_time_zone`, starting at `-infinity`. When the setting differs from the latest zone there, the rollup adds a row that starts at the new zone's **next midnight**, so the change is safe to make at any time:

- **Days already counted are never cut again.** The daily tables hold totals only, and raw rows older than 30 days are gone, so a day folded in the old zone keeps the old zone's hours. Days before the switch day stay old-zone days on the chart, days from it on are new-zone days, and an admin sees a note when the period includes the switch day, or while a change is waiting for its midnight.
- **Nothing is counted twice or lost.** Each raw row is folded once, under the zone in effect at its arrival; the totals of any period stay exact.
- **One boundary day is uneven.** Moving west (UTC to `America/Sao_Paulo`), the switch day runs from the old zone's midnight to the new zone's next one, 27 hours. Moving east (UTC to `Asia/Tokyo`), the day before the switch day ends early, at the new zone's midnight, 15 hours.
- **Set back before the midnight**, the waiting change is dropped and nothing happened. A third zone replaces a waiting one.

To cut past days in the new zone as well, there is no supported path: their raw rows are gone after 30 days, and refolding the last 30 days would need the old totals subtracted first. Pick the zone before launch.

## 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 of days more than 30 days back (in the analytics time zone) 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=`) ending today in the analytics time zone, compared with the period before; the chart names the zone, and a note appears around a [change of zone](#changing-the-zone).
- 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
