# Pug Docs > Documentation for Pug: open-source product analytics. SDKs, HTTP API, and self-hosting. Index: https://docs.pug.sh/llms.txt # Integrate Pug > Event analytics and user profiles you can wire into any app - install an SDK, POST straight to the API, or self-host the whole stack. Source: https://docs.pug.sh/ | Markdown: https://docs.pug.sh/index.md Pug is open-source product analytics. Capture events, identify the people behind them, and query the result back out - from a browser, a mobile app, your backend, or any language that can POST JSON. Run it on Pug Cloud or [self-host the entire stack](/self-hosting). The server and dashboard are AGPL-3.0 licensed and the SDKs are MIT. Custom event names work with no setup. Beyond those, Pug ships **[127 typed events](/reference/well-known-events)** across 19 families (commerce, auth, billing, media, support), each with a validated property schema, so `purchase` and `signup` mean the same thing in your data as they do in everyone else's. Capture is [cookieless by default](/sdks/web#tracking-consent): events flow from the first hit, and nothing is stored on the device until the reader consents. [Quickstart](/get-started) [Install with AI](/get-started/ai-setup) [Install the Web SDK](/sdks/web) ## Initialize, then track The whole integration, on every platform. Pick yours, then carry on in its [SDK reference](/sdks). ### Web ```ts import { init, track } from '@pug-sh/browser' init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY' }) track('page_view') ``` Next: the [Web SDK reference](/sdks/web). ### Android ```kotlin import sh.pug.android.Options import sh.pug.android.Pug // In Application.onCreate() Pug.init(this, "YOUR_PROJECT_ID", Options("pub_YOUR_PUBLIC_KEY")) Pug.track("button_clicked", mapOf("label" to "Sign up")) ``` Next: the [Android SDK reference](/sdks/android). ### iOS ```swift import Pug // In your App's init(), or application(_:didFinishLaunchingWithOptions:) do { try Pug.initialize(projectId: "YOUR_PROJECT_ID", options: Pug.Options(apiKey: "pub_YOUR_PUBLIC_KEY")) } catch { assertionFailure("Pug was not started: \(error)") } Pug.track("button_clicked", properties: ["label": "Sign up"]) ``` Next: the [iOS SDK reference](/sdks/ios). ### Flutter ```dart import 'package:pug_flutter/pug_flutter.dart'; await Pug.init( 'YOUR_PROJECT_ID', const PugOptions(apiKey: 'pub_YOUR_PUBLIC_KEY'), ); Pug.track('page_view'); ``` Next: the [Flutter SDK reference](/sdks/flutter). ### Node ```ts import { Pug } from '@pug-sh/node' // Server-side - authenticate with your private key. const pug = new Pug({ apiKey: process.env.PUG_PRIVATE_KEY! }) // A server has no ambient user - name the distinctId. pug.track('user-123', 'page_view') ``` Next: the [Node SDK reference](/sdks/node). ### Go ```go import pug "github.com/pug-sh/sdk-go" // Server-side - authenticate with your private key. client, err := pug.New(pug.Options{APIKey: os.Getenv("PUG_PRIVATE_KEY")}) if err != nil { log.Fatal(err) } // A server has no ambient user - name the distinctID. client.Track("user-123", "page_view") ``` Next: the [Go SDK reference](/sdks/go). ### Ruby ```ruby require "pug" # Server-side - authenticate with your private key. pug = Pug::Client.new(api_key: ENV.fetch("PUG_PRIVATE_KEY")) # A server has no ambient user - name the distinct_id. pug.track("user-123", "page_view") ``` Next: the [Ruby SDK reference](/sdks/ruby). ### HTTP API ```bash # No SDK? POST events to the Connect RPC ingest endpoint. # See /sdks/http for the full request shape. curl -X POST https://api.pugs.dev/sdk.events.v1.EventsService/BatchCreate \ -H "x-api-key: pub_YOUR_PUBLIC_KEY" \ -H "Connect-Protocol-Version: 1" \ -H "Content-Type: application/json" \ -d '{"events":[{"eventId":"01966b9e-1234-7abc-abcd-0123456789ab","kind":"page_view","distinctId":"anon-1","sessionId":"f47ac10b-58cc-4372-a567-0e02b2c3d479","occurTime":"2026-06-05T10:00:00Z"}]}' ``` Next: [integrating over HTTP](/sdks/http). ## Ways to integrate - **Web app** - Install the Web SDK (`@pug-sh/browser`) - auto-track page views and clicks, identify users on sign-in. [Quickstart](/get-started) - **Mobile app** - Typed event tracking, screen and lifecycle auto-tracking, and identity for native Android and iOS apps, and for Flutter. [Android SDK](/sdks/android) | [iOS SDK](/sdks/ios) | [Flutter SDK](/sdks/flutter) - **Backend or any language** - Send events and read analytics from Node with `@pug-sh/node`, Go with `github.com/pug-sh/sdk-go` or Ruby with `pug-sh` - or POST straight to the Connect RPC API from anywhere else. [Node SDK](/sdks/node) | [Go SDK](/sdks/go) | [Ruby SDK](/sdks/ruby) - **Query your data** - Read insights and profiles programmatically with your private key, via the Node, Go or Ruby SDK or the Connect API. [API reference](/api) - **Self-host** - Run the full stack - Postgres, ClickHouse, NATS, Dragonfly and the Go workers - on your own infrastructure. [Self-hosting guide](/self-hosting) ## How it works Events flow from your app through an async pipeline into analytics storage. The same data powers Live, Insights, and Profiles. 1. **SDK** (track() & identify()) 2. **API** (Connect RPC ingest) 3. **NATS** (async queue) 4. **Workers** (geo & enrichment) 5. **ClickHouse** (analytics store) 6. **Dashboard** (insights & profiles) Ingestion is near-real-time: events appear in **Live** within seconds and in **Insights** within the same minute. See [Core concepts](/get-started/concepts) for the full model. ## Jump straight in ### Track ```ts import { track } from '@pug-sh/browser' track('button_clicked', { label: 'Sign up' }) track('purchase', { productId: 'sku_123', amount: 29.99, currency: 'USD' }, { immediate: true }) ``` ### Identify ```ts import { identify, reset } from '@pug-sh/browser' // On sign-in - merges prior anonymous activity into the profile. await identify('user-123', { email: 'user@example.com', plan: 'pro' }) // On sign-out. reset() ``` ## Start here - **Get started** - [Quickstart](/get-started) | [Core concepts](/get-started/concepts) | [Install the Web SDK](/sdks/web#install) | [Authentication](/get-started/authentication) - **Build** - [Track events](/sdks/web#track-events) | [Identity and sessions](/sdks/web#identify-and-sessions) | [Consent and privacy](/sdks/web#consent-and-privacy) | [Android](/sdks/android) | [iOS](/sdks/ios) | [Flutter](/sdks/flutter) | [Node](/sdks/node) | [Go](/sdks/go) | [Ruby](/sdks/ruby) | [HTTP](/sdks/http) - **Reference** - [API reference](/api) | [Well-known events](/reference/well-known-events) | [Auto-properties](/reference/auto-properties) | [Self-hosting](/self-hosting) | [GitHub](https://github.com/pug-sh) # API reference > Call every Pug endpoint with plain JSON over HTTP POST. Base URLs, request format, auth modes and the Connect error model. Source: https://docs.pug.sh/api/ | Markdown: https://docs.pug.sh/api/index.md **You can call every endpoint but one with plain JSON over HTTP POST**: two headers (`Content-Type: application/json` and `Connect-Protocol-Version: 1`) plus a JSON-encoded body. No client library or codegen is required; see [HTTP transport](/sdks/http) for a curl-ready recipe. The exception, `ProfilesService/List`, streams its results and needs [Connect's streaming framing](/api/profiles#list). Under the hood the API is built on **Connect RPC** - a single set of handlers that speaks the Connect, gRPC, and gRPC-Web protocols over the same HTTP endpoints, on both HTTP/1.1 and HTTP/2. Generated clients are available for any language with Buf support, but every other method needs only the plain-JSON path above. ## Base URL | Environment | Base URL | |-------------|----------| | Production | `https://api.pugs.dev` | | Self-hosted / local | `http://localhost:3000` | The server port for self-hosted deployments defaults to `3000` (configurable via `PUG_SERVER_PORT`). ## Request format Every Connect RPC endpoint is reachable at: ``` POST /{package}.{Service}/{Method} ``` For example: ``` POST /sdk.events.v1.EventsService/BatchCreate POST /sdk.profiles.v1.ProfilesSDKService/Identify POST /shared.insights.v1.InsightsService/Query ``` For Connect JSON (no generated client needed), send these headers on every request except the streaming [`List`](/api/profiles#list): ```http Content-Type: application/json Connect-Protocol-Version: 1 ``` Add the appropriate auth header (see below) and POST a JSON-encoded request body. ## Authentication Auth is enforced at the HTTP middleware layer, before any handler runs. The mode depends on the proto package. For obtaining and rotating keys, see [Authentication](/get-started/authentication). ### SDK key (`sdk.*` services) Send your API key in the `x-api-key` header: ```http x-api-key: pub_... # or prv_... ``` Two key types are accepted: | Key prefix | Access | |------------|--------| | `pub_...` | Write / ingest only. Safe to embed in browser code via the Web SDK. | | `prv_...` | Full read-write. Server-side and trusted environments only. | No `Authorization` header or `x-project-id` is required for SDK auth - the project is resolved directly from the key. Beacon requests (which cannot set headers) may pass a public key as the `api_key` query parameter. Private keys are rejected on the query parameter path. ### JWT (`dashboard.*` services) ```http Authorization: Bearer ``` Optionally add `x-project-id: ` to scope the request to a specific project (the server verifies org membership). JWT auth is issued by `public.auth.v1.AuthService`. ### Dual: private key or JWT (`shared.*` services) Shared services are accessible from both server-side integrations and the dashboard. The server checks `x-api-key` first; if absent, it falls back to `Authorization: Bearer`. Only **private keys** (`prv_...`) are accepted via this path - public keys are rejected. ```http x-api-key: prv_... # server-side path # -- or -- Authorization: Bearer # dashboard path ``` ### Public (no auth) Two services require no credential: - `public.auth.v1.AuthService`: sign-in, magic link, OIDC and SSO. - `public.dashboards.v1.SharedDashboardsService`: reads a publicly-shared dashboard. Authorization comes from the unguessable **share token** carried in the request, so treat that token as a bearer credential: anyone holding it can read the dashboard. ### Auth matrix | Proto package | Auth mode | Header | |---------------|-----------|--------| | `sdk.*` | SDK key | `x-api-key: pub_... \| prv_...` | | `dashboard.*` | JWT | `Authorization: Bearer ` | | `shared.*` | Dual (private key or JWT) | `x-api-key: prv_...` or `Authorization: Bearer ` | | `public.*` | None | - (share token in the request body, where applicable) | ## Error model All errors follow the Connect error envelope. For Connect JSON the response body is: ```json { "code": "invalid_argument", "message": "validation error: events[0].kind: value is required" } ``` Standard codes returned by the API (HTTP status is the Connect-protocol mapping): | Code | HTTP status | Meaning | |------|------|---------| | `unauthenticated` | 401 | Missing, malformed, or expired credential | | `permission_denied` | 403 | Valid credential, insufficient access for this operation | | `invalid_argument` | 400 | Request failed protovalidate: fix the named field and retry | | `not_found` | 404 | Resource does not exist or is not visible to the caller | | `already_exists` | 409 | Attempted to create a resource that already exists | | `failed_precondition` | 400 | Operation rejected due to current system state | | `resource_exhausted` | 429 | Request body over 8 MiB, measured after decompression | | `internal` | 500 | Server-side error: retry with exponential backoff | | `unavailable` | 503 | A dependency, such as the credential check, is down: retry with exponential backoff | Connect errors also carry `google.rpc.ErrorInfo` details (reason + domain) and a `google.rpc.RequestInfo` with the correlation id, useful for support requests. ## Services at a glance | Service | Proto name | Auth | Docs | |---------|-----------|------|------| | Events (ingest) | `sdk.events.v1.EventsService` | SDK key | [Events](/api/events) | | Profiles (SDK) | `sdk.profiles.v1.ProfilesSDKService` | SDK key | [Profiles](/api/profiles) | | Profiles (read/manage) | `shared.profiles.v1.ProfilesService` | Dual | [Profiles](/api/profiles) | | Insights | `shared.insights.v1.InsightsService` | Dual | [Insights](/api/insights) | | Activity | `shared.activity.v1.ActivityService` | Dual | - | | Projects (list) | `shared.projects.v1.ProjectsService` | Dual | - | | Dashboards (read/edit) | `shared.dashboards.v1.DashboardsService` | Dual | - | | Orgs | `dashboard.orgs.v1.OrgsService` | JWT | - | | Projects | `dashboard.projects.v1.ProjectsService` | JWT | - | | Dashboards | `dashboard.dashboards.v1.DashboardsService` | JWT | - | | Customers | `dashboard.customers.v1.CustomersService` | JWT | - | | Auth | `public.auth.v1.AuthService` | None | - | | Shared dashboards | `public.dashboards.v1.SharedDashboardsService` | None (share token) | - | Services showing **-** in the Docs column are not covered in this reference. `sdk.devices.v1.DevicesService` handles push-notification device registration and is likewise out of scope. Most `shared.*` reads, plus creating and editing dashboards, are also served as Model Context Protocol tools at `POST /mcp`, for agents rather than generated clients: see [MCP server](/mcp). For the complete method index see [RPC services](/reference/rpc-services). ## Next steps - [Events](/api/events): ingest events with `sdk.events.v1.EventsService/BatchCreate` - [Profiles](/api/profiles): identify users and read/manage profiles - [Insights](/api/insights): run analytics queries programmatically - [MCP server](/mcp): the same read APIs, plus dashboard editing, as tools for an AI agent - [HTTP transport](/sdks/http): curl-ready plain-JSON recipes - [RPC services](/reference/rpc-services): full package and method map # Events API > Ingest event batches with sdk.events.v1.EventsService/BatchCreate - full request schema, property wrapping and validation rules. Source: https://docs.pug.sh/api/events/ | Markdown: https://docs.pug.sh/api/events/index.md Ingest events from SDKs and server-side integrations with `sdk.events.v1.EventsService/BatchCreate`. **Auth:** an `x-api-key` header holding a public key (`pub_...`) or a private key (`prv_...`). The key identifies the project, so no `Authorization` or `x-project-id` header is needed. See [Authentication](/get-started/authentication). ## `BatchCreate` ``` POST /sdk.events.v1.EventsService/BatchCreate ``` Validates and queues up to 1000 events per request; there is no single-event endpoint. Timestamps (`occurTime`, and `timestampValue` in a `PropertyValue`) are RFC 3339 strings with `Z` or an offset, such as `"2026-06-05T10:00:00Z"`. ## `Event` fields | Proto field | JSON name | Type | Required | Notes | |---|---|---|---|---| | `event_id` | `eventId` | string | Yes | A UUID, any version (v7 recommended) | | `auto_properties` | `autoProperties` | `map` | No | Context set by the SDK or server. Keys must start with `$`, and some are [server-only](#validation-summary) | | `custom_properties` | `customProperties` | `map` | No | Your event properties. Keys must not start with `$` | | `distinct_id` | `distinctId` | string | Unless `cookieless` | Anonymous or identified user ID. Must not start with `cookieless-` | | `kind` | `kind` | string | Yes | Event name, matching `^[a-zA-Z0-9_.-]+$` | | `occur_time` | `occurTime` | `google.protobuf.Timestamp` -> RFC 3339 | Yes | When the event occurred | | `session_id` | `sessionId` | string | Unless `cookieless` | A UUID grouping events in a visit | | `cookieless` | `cookieless` | bool | No | Ask the server to derive identity. See [Cookieless events](#cookieless-events) | The JSON names are canonical, and the proto field names (snake_case) work too, here and in `PropertyValue`. Unknown fields are ignored, not rejected: a misspelled name such as `customProps` loses its data silently. ## Cookieless events Set `"cookieless": true` when the client stores no identifier: the Web SDK's default [consent state](/sdks/web#tracking-consent), and what to send for a visitor who hasn't consented. Omit `distinctId` and `sessionId`: the request fails if either is set, even a `sessionId` of `""` (an empty `distinctId` passes). A batch may mix cookieless and identified events. ```json { "eventId": "01966b9e-1234-7abc-abcd-0123456789ab", "kind": "page_view", "cookieless": true, "occurTime": "2026-06-05T10:00:00Z", "customProperties": {}, "autoProperties": {} } ``` The server derives a daily-rotating `distinctId`, prefixed `cookieless-`, from the request's IP address and `User-Agent`, and stitches a `sessionId` that closes after 30 minutes of inactivity. Send these events from the visitor's own device: from your backend, every visitor gets the same identity. Insights leave cookieless visitors out of user counts by default; see [Insights](/api/insights#cookieless-visitors-are-excluded-from-user-counts). ## `PropertyValue`: typed property wrapper Every value in `customProperties` and `autoProperties` is an object holding exactly one typed field, the Connect JSON form of a protobuf `oneof`. Profile traits are [plain JSON instead](/api/profiles#traits-type-plain-json-not-propertyvalue). | Variant | JSON shape | Notes | |---|---|---| | String | `{ "stringValue": "hello" }` | At most 1024 characters (Unicode code points); a longer value is rejected, not truncated | | Integer | `{ "intValue": "42" }` | int64, as a JSON string or a whole number | | Double | `{ "doubleValue": 3.14 }` | Must be finite | | Boolean | `{ "boolValue": true }` | | | Timestamp | `{ "timestampValue": "2026-06-05T10:00:00Z" }` | RFC 3339; stored at millisecond precision | ## Validation summary A request that breaks any rule fails whole with `invalid_argument`, and nothing in it is stored: - **Batch**: at most 1000 events, no two with the same `eventId`. - **Identity**: `distinctId` and `sessionId` are required unless `cookieless` is `true`, then [omitted](#cookieless-events). No `distinctId` may start with `cookieless-`, nor may an `externalId` on [Identify](/api/profiles). - **Fields and values**: every rule in the [`Event` fields](#event-fields) and [`PropertyValue`](#propertyvalue-typed-property-wrapper) tables. Ingest then rewrites some auto-properties: - **`$ip`** is stripped from every event and never stored. - **Server-only keys** (`$bot`, `$bot_reason`, `$bot_score`, `$verified_bot`, `$channel`, `$referrerDomain`): any value you send is dropped, and the server sets its own where it can. - **Geo** (`$country`, `$city`, ...): on a public-key request, each key the CDN headers supply replaces the event's. A private-key request derives none and keeps what the event sends, verbatim, so send `$country` as ISO 3166-1 alpha-2; an event that sends none stores none. Node's and Ruby's `location` option ([Node](/sdks/node#visitor-location), [Ruby](/sdks/ruby#visitor-location)) and Go's [`pug.WithLocation`](/sdks/go#visitor-location) set them, and [Auto-properties](/reference/auto-properties#geo-enrichment-cloudflare) lists the keys. - **User agent** (`$browser`, `$os`, `$device`, `$mobile`, ...): on a public-key request, parsed from the `User-Agent` header where the event has none. A private-key request derives none, so send your own. ## Request / response shape ### `BatchCreateRequest` ```json { "events": [ { "eventId": "", "distinctId": "anon-abc123", "kind": "page_view", "sessionId": "", "occurTime": "2026-06-05T10:00:00Z", "customProperties": { "plan": { "stringValue": "pro" }, "seats": { "intValue": "5" }, "mrr": { "doubleValue": 299.0 }, "trial": { "boolValue": false } }, "autoProperties": {} } ] } ``` ### `BatchCreateResponse` ```json { "accepted": 1, "dropped": 0 } ``` `accepted` (`uint32`) counts the events queued for storage, and `dropped` those refused while deriving [cookieless](#cookieless-events) identity; together they equal the number sent. `droppedByReason` appears when `dropped` isn't zero. A drop is not an error, so a 200 doesn't mean every event landed: ```json { "accepted": 8, "dropped": 2, "droppedByReason": { "salt_unavailable": 2 } } ``` | Reason | Cause | Retry the same payload? | |---|---|---| | `day_out_of_range` | `occurTime` is neither today nor yesterday (UTC), usually from client clock skew | No - it drops again | | `salt_unavailable` | The day's salt couldn't be read or created, a server-side fault | Yes | | `salt_corrupt` | The day's stored salt can't be decoded | No - it drops until an operator replaces the salt or it expires | A cookieless request with no `User-Agent` header or no resolvable client address (usually a proxy stripping headers) fails whole with `invalid_argument` instead. ## Errors The codes `BatchCreate` returns, a subset of the [error model](/api#error-model): | Connect code | HTTP status | Cause | |---|---|---| | `unauthenticated` | 401 | Missing or invalid `x-api-key` | | `invalid_argument` | 400 | The request was malformed or broke a [rule](#validation-summary), and nothing in it was stored; the `message` names the rule | | `aborted` | 409 | An identical batch is still being stored: retry it | | `resource_exhausted` | 429 | Request body over 8 MiB, measured after decompression | | `internal` | 500 | Server error: retry with exponential backoff | | `unavailable` | 503 | The key couldn't be checked: retry with exponential backoff | Resend the same events on a retry, with the same `eventId` and `occurTime`, so any stored before the error are deduplicated rather than counted twice. Error responses follow the Connect envelope: ```json { "code": "invalid_argument", "message": "validation error: events[0].kind: does not match regex pattern `^[a-zA-Z0-9_.-]+$`" } ``` ## Further reading - [HTTP transport](/sdks/http#examples): full curl, Python, and Go examples for `BatchCreate` - [Auto-properties](/reference/auto-properties): the `$`-prefixed property catalog set by the server - [Authentication](/get-started/authentication): public vs. private keys, key rotation # Insights API > Run trends, funnel, retention, segmentation, user-flow, top-K and map queries programmatically with a private key. Source: https://docs.pug.sh/api/insights/ | Markdown: https://docs.pug.sh/api/insights/index.md Run analytics queries against the engine behind the dashboard's charts, overview KPIs and saved tiles. Browsers on other origins are blocked, so call it from a server. **Service:** `shared.insights.v1.InsightsService` **Auth:** a private key (`prv_...`) in `x-api-key`, or a dashboard JWT in `Authorization: Bearer`. See [Authentication](/get-started/authentication). Tables use proto names. Requests may use them or lowerCamelCase; responses always use lowerCamelCase (`eventKind`, `isOthers`), with int64 values as strings. ## Methods ### `Query` ``` POST /shared.insights.v1.InsightsService/Query ``` Runs one insight and returns a typed result whose shape depends on `spec.insight_type` (see [Insight types](#insight-types)). #### Request: `QueryRequest` | Field | Type | Required | Description | |-------|------|----------|-------------| | `spec` | `InsightQuerySpec` | Yes | The query specification (insight type, events, breakdowns, filters). | | `time_range` | `TimeRange` | Yes | `from` (inclusive) and `to` (exclusive) as RFC 3339 timestamps; `from` must be before `to`. | | `granularity` | `Granularity` | Yes | Time bucket size. See [Granularities](#granularities). | Buckets align to the project's reporting timezone; a `timezone` field on the request is ignored. #### Response: `QueryResponse` The response carries exactly one of the following fields, selected by `spec.insight_type`: | Field | Type | Populated when | |-------|------|----------------| | `trends` | `TrendsResult` | `INSIGHT_TYPE_TRENDS` | | `segmentation` | `SegmentationResult` | `INSIGHT_TYPE_SEGMENTATION` | | `funnel` | `FunnelResult` | `INSIGHT_TYPE_FUNNEL` | | `retention` | `RetentionResult` | `INSIGHT_TYPE_RETENTION` | | `user_flow` | `UserFlowResult` | `INSIGHT_TYPE_USER_FLOW` | | `top_k` | `TopKResult` | `INSIGHT_TYPE_TOP_K`, `INSIGHT_TYPE_MAP` | ### `SegmentUsers` ``` POST /shared.insights.v1.InsightsService/SegmentUsers ``` Returns, a page at a time in ascending order, the raw `distinctId`s of users who performed any of the given events in a time range, so one person can appear under both an anonymous ID and an external ID. Cookieless and bot-tagged traffic is always left out. | Field | Type | Description | |-------|------|-------------| | `time_range` | `TimeRange` | Required. | | `events` | `EventQuery[]` | Required, at least one. | | `filter_groups` | `FilterGroup[]` | Optional top-level filters. | | `filter_groups_operator` | `LogicalOperator` | How groups are combined (default `AND`). | | `page_size` | `int32` | 0-1000; 0 means 100. | | `page_token` | `string` | The previous response's `nextPageToken`. | Response: `{ "distinctIds": [...], "nextPageToken": "..." }`. The token is set only when a page is full, so the last page can be empty. ### `GetFilterSchema` ``` POST /shared.insights.v1.InsightsService/GetFilterSchema ``` Lists the project's event kinds and property keys (`events`, `auto_property_keys`, `custom_property_keys`, `profile_property_keys`), each with a count and last-seen time, and each key with its observed `value_type`. Results are cached for up to 5 minutes. | Field | Type | Required | Description | |-------|------|----------|-------------| | `event_kind` | `string` | No | Limit the auto and custom keys to one event kind. | | `allowed_types` | `PropertyValueType[]` | No | Keep only keys of these types. | ### `GetPropertyValues` ``` POST /shared.insights.v1.InsightsService/GetPropertyValues ``` Returns up to 100 distinct values of one property: an event property's from the last 30 days, or a profile trait's. Results are cached for 10 minutes, or an hour when there are fewer than 100. | Field | Type | Required | Description | |-------|------|----------|-------------| | `property_key` | `string` | Yes | The property, such as `$country` or `plan`. An auto-property key must start with `$`. | | `source` | `PropertySource` | Yes | `PROPERTY_SOURCE_AUTO`, `PROPERTY_SOURCE_CUSTOM` or `PROPERTY_SOURCE_PROFILE`. `PROPERTY_SOURCE_UNSPECIFIED` fails with `internal`. | | `event_kind` | `string` | No | Only values seen on this event kind. Omit to scan all events. | Response: `{ "values": string[] }`. ```json { "propertyKey": "$country", "source": "PROPERTY_SOURCE_AUTO" } ``` ## Insight types `InsightQuerySpec.insight_type` selects the computation and the response field. | Enum value | Description | |------------|-------------| | `INSIGHT_TYPE_TRENDS` | Time-series event counts or aggregations. One `TrendSeries` per `(event, breakdown)` combination. | | `INSIGHT_TYPE_SEGMENTATION` | Single scalar over the full time range, no time axis. With several events, one value covers events matching any of them, using the first event's aggregation. | | `INSIGHT_TYPE_FUNNEL` | Multi-step conversion funnel. Steps are the `events` array in order. Each series carries per-step counts, plus per-step timing when `include_step_timing` is true. | | `INSIGHT_TYPE_RETENTION` | Cohort retention matrix. `events[0]` is the starting event; `events[1]` (optional) is the return event. Cohorts are bucketed by the query granularity. | | `INSIGHT_TYPE_USER_FLOW` | Sankey graph of transitions between events or property values. Requires a [`user_flow`](#userflowquery) sub-spec; no `events` field. | | `INSIGHT_TYPE_TOP_K` | Ranking: the top K values of a dimension by a metric, plus a trailing `$others` bucket. Requires a `top_k` sub-spec; no `events` field, no time axis. See [`TopKQuery`](#topkquery). | | `INSIGHT_TYPE_MAP` | Choropleth: one metric per country, the dimension fixed to `$country`. Requires a `map` sub-spec; no `events` field, no time axis. Results arrive in `top_k`. See [`MapQuery`](#mapquery). | ### Insight type constraints Breaking any of these fails with `invalid_argument`: - **`INSIGHT_TYPE_FUNNEL`**: 1-20 events. Takes `breakdowns`, `conversion_window` and `include_step_timing`. - **`INSIGHT_TYPE_RETENTION`**: 1 or 2 events (`events[0]` = start, `events[1]` = return). - **`INSIGHT_TYPE_SEGMENTATION`**: no `breakdowns`. - **`INSIGHT_TYPE_USER_FLOW`**: requires `user_flow`; `events`, `session`, `breakdowns` and `breakdown_limit` must be empty. - **`INSIGHT_TYPE_TOP_K`**: requires `top_k`; `events`, `session`, `breakdowns` and `breakdown_limit` must be empty. Scope events through `top_k.scope`. - **`INSIGHT_TYPE_MAP`**: requires `map`; `events`, `session`, `breakdowns` and `breakdown_limit` must be empty. Scope events through `map.scope`. - **Numeric aggregations** (`AGGREGATION_TYPE_SUM`, `AVG`, `MIN`, `MAX`): trends and segmentation only. ## Granularities `QueryRequest.granularity` controls the time-bucket width and imposes a maximum query range. | Enum value | Bucket width | Maximum time range | |------------|-------------|-------------------| | `GRANULARITY_MINUTE` | 1 minute | 6 hours | | `GRANULARITY_HOUR` | 1 hour | 14 days | | `GRANULARITY_DAY` | 1 day | 365 days | | `GRANULARITY_WEEK` | 1 week | ~4 years (1461 days) | | `GRANULARITY_MONTH` | 1 month | ~10 years (3652 days) | ## `InsightQuerySpec` fields | Field | Type | Description | |-------|------|-------------| | `insight_type` | `InsightType` | Required. Selects the computation and response shape. | | `events` | `EventQuery[]` | Event series for trends, segmentation, funnel and retention. Each selects one event kind, with optional filters and an aggregation. | | `breakdowns` | `Breakdown[]` | Group results by up to 5 distinct properties (`{ property: string }`). Funnel and retention take each user's value from their earliest matching event. | | `breakdown_limit` | `int32` | Breakdown values to keep, 0-100; 0 means 10. The rest merge into one series whose breakdown values are all `$others` (series carry no `is_others` flag). Requires at least one breakdown. | | `filter_groups` | `FilterGroup[]` | Top-level property filters. Multiple groups are combined by `filter_groups_operator`. | | `filter_groups_operator` | `LogicalOperator` | How filter groups are combined. Defaults to `LOGICAL_OPERATOR_AND`. | | `conversion_window` | `Duration` | Funnel only. Maximum time from the first step to the last, per user: whole seconds, at least `1s`. Absent means the whole time range. | | `include_step_timing` | `bool` | Funnel only. When true, each non-entry step includes `StepTiming` (avg, median, p95, 8-bucket histogram). | | `session` | `SessionQuery` | Trends and segmentation only. Measures sessions instead of events; `events` must be empty. See [Session metrics](#session-metrics). | | `user_flow` | `UserFlowQuery` | User flow only. See [`UserFlowQuery`](#userflowquery). | | `top_k` | `TopKQuery` | Top-K only. Configures the ranking (dimension, metric, limit). See [`TopKQuery`](#topkquery). | | `map` | `MapQuery` | Map only. Configures the per-country metric (scope, metric, metric property). See [`MapQuery`](#mapquery). | | `include_cookieless` | `bool` | Count [cookieless visitors](/api/events#cookieless-events) in user-based results. Defaults to `false` - see below. | | `include_bots` | `bool` | Count traffic tagged as a bot at ingest. Defaults to `false` - see [Bot traffic is excluded](#bot-traffic-is-excluded). | ### Cookieless visitors are excluded from user counts By default, cookieless visitors are left out of: - **`UNIQUE_USERS` and `PER_USER_AVG`**, numerator and denominator alike, wherever those metrics appear: trends, segmentation, [top K](#topkquery), [map](#mapquery). - **Person-based insights**: funnel, retention, user flow, and `DIMENSION_USER` top K, whichever metric is selected. Event totals, numeric aggregations and all session metrics always count every visitor. With `include_cookieless: true` cookieless visitors count above too, as a new user each day, since their IDs rotate daily. ### Bot traffic is excluded Ingest tags a web-SDK event `$bot` when its user agent is a known crawler, its network is a datacenter's, or it reports headless Chrome's default 800x600 screen. Tagged events are left out of **every** insight and metric by default, event totals included. Session metrics and user flow judge a session whole, so one tagged event drops its session. Events sent with a private key are never tagged. Set `include_bots: true` to count them. ### `EventQuery` | Field | Type | Description | |-------|------|-------------| | `event` | `EventFilter` | Event kind (empty means any) and optional per-event property filters, all of which must match. | | `aggregation` | `AggregationType` | Defaults to `AGGREGATION_TYPE_TOTAL`. Funnel and retention ignore the counting types and reject the numeric ones. | | `aggregation_property` | `string` | Required for `SUM`, `AVG`, `MIN`, `MAX`. Property name to aggregate (e.g. `revenue`). | ### Aggregation types | Enum value | Description | |------------|-------------| | `AGGREGATION_TYPE_TOTAL` | Total event occurrences. | | `AGGREGATION_TYPE_UNIQUE_USERS` | Count of distinct users. | | `AGGREGATION_TYPE_PER_USER_AVG` | Average events per user. | | `AGGREGATION_TYPE_SUM` | Sum of a numeric property. Requires `aggregation_property`. | | `AGGREGATION_TYPE_AVG` | Mean of a numeric property. Requires `aggregation_property`. | | `AGGREGATION_TYPE_MIN` | Minimum of a numeric property. Requires `aggregation_property`. | | `AGGREGATION_TYPE_MAX` | Maximum of a numeric property. Requires `aggregation_property`. | ### `TopKQuery` Ranks the values of one dimension by a metric. It has **no time axis**: `granularity` only selects which [time-range cap](#granularities) applies, so send the coarsest one whose cap admits your window. | Field | Type | Description | |-------|------|-------------| | `dimension` | `Dimension` | Required. What is being ranked - see below. | | `property` | `string` | The property to rank values of. Required when `dimension` is `DIMENSION_PROPERTY`, and rejected otherwise. Same `$`-prefix encoding as `Breakdown.property`. | | `scope` | `EventFilter` | Optional event scope (kind and/or per-event filters). Empty means all events participate. This replaces `events`, which top K may not set. | | `metric` | `AggregationType` | Metric to rank by. Defaults to `AGGREGATION_TYPE_TOTAL`. | | `metric_property` | `string` | Property to aggregate. Required for `SUM`, `AVG`, `MIN`, `MAX`; ignored otherwise. | | `limit` | `int32` | Rows to return before `$others`, 0-100; 0 means 10. | | `omit_others` | `bool` | Drop the trailing synthetic `$others` bucket and return only the top `limit` rows. Defaults to `false`. | | `Dimension` | Ranks | |---|---| | `DIMENSION_PROPERTY` | Values of an event property, auto or custom, named by `property`. | | `DIMENSION_EVENT_KIND` | Event kinds: "top events". | | `DIMENSION_USER` | Users. `dimension_value` is the canonical profile ID, or the raw `distinctId` when none resolves. `UNIQUE_USERS` and `PER_USER_AVG` are rejected. | `TopKResult` holds `rows`, ordered metric-descending, with the `$others` bucket last when anything overflows. Each `TopKRow` carries `dimension_value`, `value`, `is_others`, and, for resolved `DIMENSION_USER` rows only, a `profile` (`id`, `external_id`, `properties`). Identify the overflow bucket by **`is_others`**, not by matching `"$others"`, which can be a real property value or event kind. The same holds for `UserFlowNode`. ### `MapQuery` Measures one metric per `$country` for a choropleth; there is no `dimension`, `property` or `limit` to set. Like top K it has **no time axis**, so `granularity` only selects which [time-range cap](#granularities) applies. | Field | Type | Description | |-------|------|-------------| | `scope` | `EventFilter` | Optional event scope (kind and/or per-event filters). Empty means all events participate. This replaces `events`, which map may not set. | | `metric` | `AggregationType` | Metric to measure per country. Defaults to `AGGREGATION_TYPE_TOTAL`. | | `metric_property` | `string` | Property to aggregate. Required for `SUM`, `AVG`, `MIN`, `MAX`; rejected for the counting metrics. | Results arrive in `QueryResponse.top_k`, ordered metric-descending, with the country code in `dimension_value` and no `$others` bucket. > **Map rows do not sum to your project total** > > Every returned key is an assigned **ISO 3166-1 alpha-2** code. Rows that aren't one are dropped: traffic the geo lookup couldn't resolve, and any other value a client wrote to `$country` (`"USA"`, `"unknown"`, unassigned codes like `"ZZ"`). Compute percentages against the row set, not against a separate total. > > Ranking happens **before** that filter, against an internal cap of 250 countries, so a project flooded with junk `$country` values can push real countries out of the result. ### `UserFlowQuery` Configures the user-flow graph: each session's events in time order, one step per event. | Field | Type | Description | |-------|------|-------------| | `node_kind` | `NodeKind` | `NODE_KIND_EVENT_KIND` (the default) names nodes by event kind; `NODE_KIND_PROPERTY` by the value of `node_property`. | | `node_property` | `string` | Required with `NODE_KIND_PROPERTY`. | | `group_by` | `GroupBy` | `GROUP_BY_SESSION`, the only value and the default. | | `scope` | `EventFilter` | Which events can become nodes. A session with none emits no transitions. | | `max_hops` | `int32` | Steps per session, 1-10; 0 means 5. | | `max_nodes` | `int32` | Nodes kept per step, 2-50, before the rest merge into that step's `$others` node; 0 means 20. | | `max_links` | `int32` | Links returned, 1-500, dropping the lowest-value ones; 0 means 250. | `UserFlowResult` holds `nodes` (`id`, `is_others`, `depth`, `label`) and `links` (`source`, `target`, `value`). A node's `id` is an opaque key, unique per depth and label; `depth` is its 0-based step, and every link joins depth d to d+1. ## Filter model Filters are `FilterGroup` objects in `spec.filter_groups`. Each group's `operator` combines its `PropertyFilter`s, and `spec.filter_groups_operator` combines the groups. ### `FilterGroup` ```json { "filters": [ { "property": "plan", "operator": "FILTER_OPERATOR_EQUALS", "value": "pro" }, { "property": "$country", "operator": "FILTER_OPERATOR_IN", "values": ["US", "CA"] } ], "operator": "LOGICAL_OPERATOR_AND" } ``` A group needs at least one filter. A `PropertyFilter` takes `property`, `operator`, `value` or `values`, and `source`: `PROPERTY_SOURCE_PROFILE` matches events by their user's profile traits, and any other source matches the event's own property, auto if `property` starts with `$`, else custom. ### Filter operators (`FilterOperator`) | Enum value | Value fields used | Description | |------------|------------------|-------------| | `FILTER_OPERATOR_EQUALS` | `value` | Exact match. | | `FILTER_OPERATOR_NOT_EQUALS` | `value` | Excludes exact match. | | `FILTER_OPERATOR_CONTAINS` | `value` | Case-sensitive substring match. | | `FILTER_OPERATOR_NOT_CONTAINS` | `value` | Excludes substring match. | | `FILTER_OPERATOR_IS_SET` | - | Property exists. | | `FILTER_OPERATOR_IS_NOT_SET` | - | Property is absent. | | `FILTER_OPERATOR_LTE` | `value` (numeric) | Less than or equal. | | `FILTER_OPERATOR_GTE` | `value` (numeric) | Greater than or equal. | | `FILTER_OPERATOR_LT` | `value` (numeric) | Strictly less than. | | `FILTER_OPERATOR_GT` | `value` (numeric) | Strictly greater than. | | `FILTER_OPERATOR_IN` | `values` | Match any of a list. | | `FILTER_OPERATOR_NOT_IN` | `values` | Exclude all of a list. | | `FILTER_OPERATOR_BETWEEN` | `values[0]`, `values[1]` (numeric, ordered) | Inclusive range. | | `FILTER_OPERATOR_NOT_BETWEEN` | `values[0]`, `values[1]` (numeric, ordered) | Outside range. | Set only the fields in that column: a missing one fails with `invalid_argument`, and so can an extra one. On event properties, an empty string counts as not set; `NOT_EQUALS`, `NOT_CONTAINS` and `NOT_IN` also match events without the property; and the numeric operators never match a non-numeric value. ### Logical operators (`LogicalOperator`) | Enum value | Description | |------------|-------------| | `LOGICAL_OPERATOR_AND` | All conditions must match (default). | | `LOGICAL_OPERATOR_OR` | At least one condition must match. | A filter's `property` matches `^\$?[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*$`. Auto-properties use their `$` key, such as `$country`; [Auto-properties](/reference/auto-properties) lists them. A dotted name is a literal event-property key, or, with `PROPERTY_SOURCE_PROFILE`, a path into a nested trait. ## Session metrics When `spec.session` is set, the query measures sessions instead of individual events, and `spec.events` must be empty. Sessions are selected by start time and measured over all their in-scope events, even past the end of the window. | Enum value | Description | Restrictions | |------------|-------------|--------------| | `SESSION_METRIC_SESSIONS` | Count of distinct sessions started in the window. | Trends or segmentation. | | `SESSION_METRIC_AVG_DURATION` | Average session duration in seconds (last event - first event). | Trends or segmentation. | | `SESSION_METRIC_BOUNCE_RATE` | Percentage of sessions with exactly one event (after optional scope filter). | Trends or segmentation. | | `SESSION_METRIC_AVG_EVENTS_PER_SESSION` | Average number of scoped events per session; with a `page_view` scope, pages per session. | Trends or segmentation. | | `SESSION_METRIC_ENTRY` | Count sessions by their first matching event's breakdown value (entry page). | Trends + exactly one breakdown. | | `SESSION_METRIC_EXIT` | Count sessions by their last matching event's breakdown value (exit page). | Trends + exactly one breakdown. | `SessionQuery.scope` (optional `EventFilter`) restricts which events participate in the metric. An empty scope considers all events in the session. ## Worked example: TRENDS query A daily time series of unique users who fired `page_view`, broken down by `$country`, over the last 30 days. ```http POST /shared.insights.v1.InsightsService/Query Content-Type: application/json Connect-Protocol-Version: 1 x-api-key: prv_... ``` ```json { "spec": { "insightType": "INSIGHT_TYPE_TRENDS", "events": [ { "event": { "kind": "page_view" }, "aggregation": "AGGREGATION_TYPE_UNIQUE_USERS" } ], "breakdowns": [ { "property": "$country" } ], "breakdownLimit": 10 }, "timeRange": { "from": "2026-05-06T00:00:00Z", "to": "2026-06-05T00:00:00Z" }, "granularity": "GRANULARITY_DAY" } ``` Response sketch: ```json { "trends": { "series": [ { "eventKind": "page_view", "breakdown": { "$country": "US" }, "points": [ { "time": "2026-05-06T00:00:00Z", "value": 412 }, { "time": "2026-05-07T00:00:00Z", "value": 389 } ] }, { "eventKind": "page_view", "breakdown": { "$country": "GB" }, "points": [ { "time": "2026-05-06T00:00:00Z", "value": 104 }, { "time": "2026-05-07T00:00:00Z", "value": 97 } ] } ] } } ``` Each `series` entry is one `(event_kind, breakdown)` pair. `points` run in ascending time order, and a bucket with no data may be missing rather than zero. ## Worked example: FUNNEL query ```http POST /shared.insights.v1.InsightsService/Query Content-Type: application/json Connect-Protocol-Version: 1 x-api-key: prv_... ``` ```json { "spec": { "insightType": "INSIGHT_TYPE_FUNNEL", "events": [ { "event": { "kind": "signup_started" } }, { "event": { "kind": "signup_completed" } }, { "event": { "kind": "purchase" } } ], "conversionWindow": "604800s" }, "timeRange": { "from": "2026-05-01T00:00:00Z", "to": "2026-06-01T00:00:00Z" }, "granularity": "GRANULARITY_DAY" } ``` Response sketch: ```json { "funnel": { "series": [ { "steps": [ { "eventKind": "signup_started", "total": 1000 }, { "eventKind": "signup_completed", "total": 650 }, { "eventKind": "purchase", "total": 120 } ] } ] } } ``` With `includeStepTiming: true`, each non-entry step gains a `timing` object: ```json { "eventKind": "signup_completed", "total": 650, "timing": { "avg": "180s", "median": "95s", "p95": "1200s", "distribution": [ { "label": "0-30s", "upperBound": "30s", "count": "78" }, { "label": "30s-2m", "upperBound": "120s", "count": "210" } ] } } ``` A full `distribution` always has the same 8 buckets in a fixed order, and the last, `24h+`, has no `upperBound`. A step nobody converted to has every timing field at zero. ## Performance notes Query time grows with the time range at fine granularities, with breakdown cardinality (cap it with `breakdown_limit`), and with funnel steps. Most queries are cached for 60 seconds, so repeating one with the same parameters may not include events ingested since. ## Related - [API reference](/api): base URL, auth, error codes - [Auto-properties](/reference/auto-properties): filterable `$`-prefixed properties - [RPC services](/reference/rpc-services): full method index # Profiles API > Identify users, read and list profiles, and run data-subject deletion across the SDK and shared profile services. Source: https://docs.pug.sh/api/profiles/ | Markdown: https://docs.pug.sh/api/profiles/index.md Pug keeps a profile for every user your project tracks, identified or anonymous, holding the traits you set and linked to the user's events. | Service | Auth | What it does | |---------|------|--------------| | `sdk.profiles.v1.ProfilesSDKService` | `x-api-key`: public or private key | Write: `Identify`, `BatchIdentify` | | `shared.profiles.v1.ProfilesService` | Private key (`prv_...`) or dashboard JWT | Read and erase: `Get`, `GetByExternalId`, `List`, `Delete`, `DeleteDataSubject`, `GetDeletionRequest` | See [Authentication](/get-started/authentication) and the [auth matrix](/api#auth-matrix) for key types and headers. ## `ProfilesSDKService`: write path ``` POST /sdk.profiles.v1.ProfilesSDKService/Identify ``` Creates or updates the profile for `externalId`. Traits are **shallow-merged** into an existing profile's: the keys you send overwrite stored values, and other keys are left as they are. **Auth** for both methods: an `x-api-key` header holding a public key (`pub_...`) or a private key (`prv_...`). The key identifies the project, so no `Authorization` or `x-project-id` header is needed. ### `IdentifyRequest` fields | Proto field | JSON name | Type | Required | Notes | |---|---|---|---|---| | `external_id` | `externalId` | string | Yes | Stable, unique user identifier: your database user ID, not an email, which can change. Must be non-empty and must not start with `cookieless-` ([reserved](/api/events#cookieless-events)) | | `traits` | `traits` | `google.protobuf.Struct` | No | [Plain JSON](#traits-type-plain-json-not-propertyvalue), shallow-merged into stored traits; on a conflict these win | | `anonymous_id` | `anonymousId` | string | No | The `distinctId` the user's anonymous events carried, to [merge](#anonymous-to-identified-merge) them. Empty or starting with `anon-`; at most 255 characters | | `device_id` | `deviceId` | string | No | A push device registered through `sdk.devices.v1`, to link to this profile; at most 36 characters, and an unregistered ID is ignored. The Flutter SDK sends one and the Android and iOS SDKs don't; omit it for web | ### `traits` type: plain JSON, not `PropertyValue` `traits` is a `google.protobuf.Struct`, a plain JSON object: pass bare values, not the `{ "stringValue": "..." }` wrappers that [event properties](/api/events#propertyvalue-typed-property-wrapper) use. A wrapped value is stored as a nested object. ```json { "traits": { "email": "user@example.com", "plan": "pro", "seats": 5, "trial": false } } ``` A top-level `$ip` trait is dropped. A trait key or string holding a NUL character (`\u0000`) can't be stored: the identify is accepted but never applied. ### `anonymous_id` constraint Any value other than `""` or an `anon-`-prefixed ID fails with `invalid_argument`, so anonymous events can be merged only if their `distinctId` starts with `anon-`. The Web SDK's anonymous IDs do. ### Anonymous to identified merge An identify merges a user's prior anonymous activity only when it carries their `anonymousId`, so send it on the first identify after an anonymous session. The merge moves that ID's events, properties and devices to the identified profile and soft-deletes the anonymous one. Identifying the same `anonymousId` under another external ID later moves all of its history to that user, so start a new anonymous ID after sign-out. There is no `alias()` method. ### `IdentifyResponse` The response is `{}`. The identify is applied asynchronously, so a read straight after it may not see it yet, and two identifies for one user sent close together can apply in either order. ### Wire example ```bash curl -X POST https://api.pugs.dev/sdk.profiles.v1.ProfilesSDKService/Identify \ -H "Content-Type: application/json" \ -H "Connect-Protocol-Version: 1" \ -H "x-api-key: pub_..." \ -d '{ "externalId": "user-123", "anonymousId": "anon-abc456", "traits": { "email": "user@example.com", "plan": "pro", "company": "Acme Inc" } }' ``` ### `BatchIdentify` ``` POST /sdk.profiles.v1.ProfilesSDKService/BatchIdentify ``` Added in server v0.0.48. Takes up to 1000 identifies, each validated as `Identify` validates it, so one invalid item fails the whole request before any is queued. ```json { "identifies": [ { "externalId": "user-123", "anonymousId": "anon-abc456", "traits": { "plan": "pro" } }, { "externalId": "user-456", "traits": { "plan": "free" } } ] } ``` The response is `{ "accepted": 2 }`, the number of items queued, not yet applied. Within one request, items for one `externalId` that only set traits are merged in order, later values winning per key, unless the merged identify would pass 900 KiB. An item carrying `anonymousId` or `deviceId` isn't merged into earlier ones, so it can [apply before them](#identifyresponse). The request isn't atomic: it can fail after queueing some items, and a retry queues those again, overwriting anything newer. ## `ProfilesService`: read and manage **Auth:** a private key (`prv_...`) in `x-api-key`, or a dashboard JWT in `Authorization: Bearer`. A public key gets `unauthenticated`. ```http x-api-key: prv_... # -- or -- Authorization: Bearer ``` ### Methods | Method | Endpoint | |--------|----------| | `Get` | `POST /shared.profiles.v1.ProfilesService/Get` | | `GetByExternalId` | `POST /shared.profiles.v1.ProfilesService/GetByExternalId` | | `List` | `POST /shared.profiles.v1.ProfilesService/List` | | `Delete` | `POST /shared.profiles.v1.ProfilesService/Delete` | | `DeleteDataSubject` | `POST /shared.profiles.v1.ProfilesService/DeleteDataSubject` | | `GetDeletionRequest` | `POST /shared.profiles.v1.ProfilesService/GetDeletionRequest` | ### `Get` Fetch a profile by its Pug ID. **Request** | Field | Type | Required | Notes | |---|---|---|---| | `id` | string | Yes | A profile ID, as `List` and `GetByExternalId` return it. An anonymous person's is its `distinctId`, though a cookieless one is never found; an anonymous ID merged by `Identify` returns the profile it joined | | `include_bots` | bool | No | JSON `includeBots`. Include traffic [tagged as a bot](/api/insights#bot-traffic-is-excluded) at ingest: count it in `activity`, and find an anonymous person whose traffic is all bot-tagged. Defaults to `false` | ```json { "id": "dbolnlavh7ldv7r89na0" } ``` **Response**: a [`Profile`](#profile-message). ```json { "profile": { "id": "dbolnlavh7ldv7r89na0", "externalId": "user-123", "properties": { "email": "user@example.com", "plan": "pro" }, "projectId": "dbolnlavh7ldv7r89nag", "createTime": "2026-01-15T10:00:00Z", "updateTime": "2026-06-01T14:30:00Z", "activity": { "firstSeen": "2026-01-15T10:00:00Z", "lastSeen": "2026-06-01T14:30:00Z", "totalEvents": "342", "pageviews": "198", "sessions": "27", "browser": "Google Chrome", "os": "macOS", "country": "US" } } } ``` ### `GetByExternalId` Fetch a profile by the `externalId` you passed to `Identify`. **Request** | Field | Type | Required | Notes | |---|---|---|---| | `external_id` | string | Yes | The `externalId` set on `Identify` | | `include_bots` | bool | No | JSON `includeBots`. As on [`Get`](#get) | ```json { "externalId": "user-123" } ``` **Response**: same shape as `Get`. ### `List` Streams every matching profile in one call, up to 100 per frame, newest first. `List` is server-streaming, so plain JSON gets HTTP 415: send `Content-Type: application/connect+json` and frame the request and each response message in a 5-byte envelope (a flags byte, then the message length as a big-endian uint32), or use a generated Connect client. The final frame, flagged `0x02`, carries any error, auth failures included, under HTTP 200. **Request** | Field | JSON name | Type | Notes | |---|---|---|---| | `page_token` | `pageToken` | string | A frame's `nextPageToken`, to resume after that frame. Empty (or omitted) to start | | `filter_groups` | `filterGroups` | `FilterGroup[]` | Each group has `filters` (at least one `PropertyFilter`) and an `operator` (`LOGICAL_OPERATOR_AND` or `LOGICAL_OPERATOR_OR`) to combine them | | `filter_groups_operator` | `filterGroupsOperator` | `LogicalOperator` | Combines the groups. Defaults to `LOGICAL_OPERATOR_AND` | | `include_bots` | `includeBots` | bool | As on [`Get`](#get); identified profiles are listed either way. Keep it the same for a whole `pageToken` run - flipping it mid-run skips rows | | `sort` | `sort` | `ProfileListSort` | `PROFILE_LIST_SORT_CREATE_TIME` (the default), `PROFILE_LIST_SORT_FIRST_SEEN` or `PROFILE_LIST_SORT_LAST_SEEN`, newest first. A `pageToken` works only with the sort it came from | A `PropertyFilter` has `property`, `operator` (one of the [filter operators](/api/insights#filter-operators-filteroperator)), `value` or `values`, and `source`. With `source` unset or `PROPERTY_SOURCE_PROFILE`, `property` is a trait key of ASCII letters, digits, `_` and `-`, such as `"plan"`, or a dot path into a nested trait; with `PROPERTY_SOURCE_AUTO` it is one of `$browser`, `$browserVersion`, `$os`, `$osVersion`, `$device`, `$country`, `$region` or `$city`, matched against the profile's `activity`. **Example - filter by plan** ```json { "filterGroups": [ { "filters": [ { "property": "plan", "operator": "FILTER_OPERATOR_EQUALS", "value": "pro" } ], "operator": "LOGICAL_OPERATOR_AND" } ] } ``` **Response** (each frame) ```json { "profiles": [ { "id": "...", "externalId": "user-123", "properties": { "plan": "pro" }, "...": "..." } ], "nextPageToken": "eyJzIjoiY3JlYXRlX3RpbWUiLCJ0IjoiMjAyNi0wNi0wMVQxNDozMDowMFoiLCJpIjoiZGJvbG5sYXZoN2xkdjdyODluYTAifQ" } ``` The last frame carries no `nextPageToken`. To resume an interrupted stream, send the last token you received as `pageToken`. A person whose sort time changes mid-run can be skipped or returned twice. ### `Delete` Erases a person: soft-deletes the profile and deactivates its push devices at once, then queues irreversible deletion of the person's events, activity, devices and profile, which a worker carries out. They leave reads when it finishes. On a dashboard JWT, erasing needs the member or admin role. **Request** | Field | Type | Required | Notes | |---|---|---|---| | `id` | string | Yes | A profile ID, an external ID, or any `distinctId` that has events, cookieless ones included. An anonymous ID merged by `Identify` erases the profile it joined | ```json { "id": "dbolnlavh7ldv7r89na0" } ``` **Response**: the erasure request, such as `{ "requestId": "dbolnlavh7ldv7r89nb0", "status": "COMPLIANCE_REQUEST_STATUS_PENDING" }`, to follow with [`GetDeletionRequest`](#getdeletionrequest). Calling `Delete` again before that request completes returns the same request, and re-queues it if it failed. ### `DeleteDataSubject` Erases the person with an external ID, as [`Delete`](#delete) does. It goes ahead when no profile has that ID, erasing the events that carry it as their `distinctId`. **Request** | Field | Type | Required | Notes | |---|---|---|---| | `external_id` | string | Yes | JSON `externalId`. The `externalId` set on `Identify`; `""` gets `not_found` | ```json { "externalId": "user-123" } ``` **Response**: as for `Delete`, including a repeated call. ### `GetDeletionRequest` Reports an erasure request's progress. **Request** | Field | Type | Required | Notes | |---|---|---|---| | `request_id` | string | Yes | JSON `requestId`, as `Delete` or `DeleteDataSubject` returned it | ```json { "requestId": "dbolnlavh7ldv7r89nb0" } ``` **Response** | Proto field | JSON name | Type | Notes | |---|---|---|---| | `request_id` | `requestId` | string | The erasure request's ID | | `external_id` | `externalId` | string | The erased external ID, when known | | `profile_id` | `profileId` | string | The erased profile's ID, or the anonymous `distinctId`, when known | | `status` | `status` | `ComplianceRequestStatus` | `COMPLIANCE_REQUEST_STATUS_PENDING`, then `_PROCESSING`, then `_COMPLETED` or `_FAILED` | | `events_identified` | `eventsIdentified` | int64, as a JSON string | Events found to erase when processing began, not a count of rows removed; `"0"` until then | | `requested_at` | `requestedAt` | RFC 3339 timestamp | When the erasure was requested | | `completed_at` | `completedAt` | RFC 3339 timestamp | Set once `COMPLETED` | | `error` | `error` | string | Why it failed, when `FAILED` | To retry a `FAILED` request, repeat the call that created it. ## `Profile` message Returned by `Get`, `GetByExternalId`, and each frame of `List`. | Proto field | JSON name | Type | Notes | |---|---|---|---| | `id` | `id` | string | Pug profile ID; an anonymous person's is its `distinctId` | | `external_id` | `externalId` | string | Set via `Identify`; empty for an anonymous person | | `properties` | `properties` | `google.protobuf.Struct` | Traits, as plain JSON (same encoding as `IdentifyRequest.traits`); empty for an anonymous person | | `project_id` | `projectId` | string | Project this profile belongs to | | `create_time` | `createTime` | RFC 3339 timestamp | First identify; an anonymous person's first event | | `update_time` | `updateTime` | RFC 3339 timestamp | Latest identify; an anonymous person's latest event | | `activity` | `activity` | `ProfileActivitySummary` | Absent when the profile has no events | ### `ProfileActivitySummary` fields | Proto field | JSON name | Type | Notes | |---|---|---|---| | `first_seen` | `firstSeen` | RFC 3339 timestamp | Earliest event | | `last_seen` | `lastSeen` | RFC 3339 timestamp | Latest event | | `total_events` | `totalEvents` | int64, as a JSON string | All events attributed to this profile | | `pageviews` | `pageviews` | int64, as a JSON string | `page_view` events | | `sessions` | `sessions` | int64, as a JSON string | Session count | | `browser` | `browser` | string | Browser name | | `browser_version` | `browserVersion` | string | Browser version | | `os` | `os` | string | Operating system name | | `os_version` | `osVersion` | string | OS version | | `device` | `device` | string | Device type or model | | `country` | `country` | string | ISO 3166-1 alpha-2 country code | | `region` | `region` | string | Region / state | | `city` | `city` | string | City name | | `bot` | `bot` | bool | `true` when every event counted here was tagged as a bot at ingest, so only ever with `include_bots` | The string fields take their value from the latest event. Activity is computed from the person's events, so it trails both ingestion and identify merges. ## Errors | Code | HTTP | Cause | |------|------|-------| | `unauthenticated` | 401 | Missing, malformed, or expired credential, or a public key on `ProfilesService` | | `permission_denied` | 403 | JWT only: the caller isn't in the project's org, or their role doesn't permit the call | | `invalid_argument` | 400 | A field broke a rule on this page, or an identify is too large to queue (about 1 MiB) | | `not_found` | 404 | No profile with the given `id` or `externalId`, or no erasure request with the given `requestId` | | `resource_exhausted` | 429 | Request body over 8 MiB, measured after decompression | | `internal` | 500 | Server error: retry with exponential backoff | | `unavailable` | 503 | The key couldn't be checked: retry with exponential backoff | `List` reports these [in its final frame](#list). ## Further reading - [HTTP transport](/sdks/http#identify-and-sessions): calling `Identify` without an SDK - [Authentication](/get-started/authentication): public vs. private keys, key rotation - [Auto-properties](/reference/auto-properties): `$`-prefixed properties set by the server on events - [Events API](/api/events): `PropertyValue`-wrapped properties used by `BatchCreate` # AI crawlers > See which AI products, search engines and SEO tools read your site, and why, with @pug-sh/crawlers in your own request handling and a private key. Source: https://docs.pug.sh/crawlers/ | Markdown: https://docs.pug.sh/crawlers/index.md See which AI products, search engines and SEO tools read your site, and why: to answer someone's question, to build a search index, or to train a model. Crawlers fetch HTML and don't run JavaScript, so a browser analytics script never sees them. This package runs in your site's own request handling instead. When a request comes from a known crawler, it sends one small report to Pug after the response. Pug checks the request's IP against the ranges the crawler's operator publishes, so a scraper borrowing GPTBot's name reads as unverified. It has no dependencies and runs on Cloudflare Workers, Vercel, Next.js, Hono, Bun, Deno, Express and plain Node. ## Install ```sh npm install @pug-sh/crawlers ``` You need a private key (`prv_...`) from your project's settings in Pug. Keep it on the server, in an environment variable: it can also read your analytics. ## Cloudflare Workers and Pages Functions ```ts import { crawlers } from '@pug-sh/crawlers' export default { async fetch(request, env, ctx) { const response = await env.ASSETS.fetch(request) crawlers({ apiKey: env.PUG_PRIVATE_KEY }).track(request, response, ctx) return response }, } ``` Passing `ctx` lets the Worker finish the report after the response is sent. ## Hono, Bun and Deno ```ts import { crawlers } from '@pug-sh/crawlers' const pug = crawlers({ apiKey: process.env.PUG_PRIVATE_KEY }) app.use(async (c, next) => { await next() pug.track(c.req.raw, c.res) }) ``` On Cloudflare, pass `c.executionCtx` as the third argument. Elsewhere, see [the client's address](#the-clients-address). ## Next.js and Vercel ```ts // proxy.ts import { crawlers } from '@pug-sh/crawlers' import { type NextFetchEvent, type NextRequest, NextResponse } from 'next/server' const pug = crawlers({ apiKey: process.env.PUG_PRIVATE_KEY! }) export function proxy(request: NextRequest, event: NextFetchEvent) { pug.track(request, undefined, event) return NextResponse.next() } ``` The proxy runs before the page, so these reports carry no status code. ## Express and node:http ```ts import { crawlers } from '@pug-sh/crawlers' app.use(crawlers({ apiKey: process.env.PUG_PRIVATE_KEY }).express()) ``` The middleware reports after the response finishes. With plain `node:http`, call it at the start of your handler: `middleware(req, res)`. ## Any other server Report a request yourself with one POST, from any language: ```sh curl https://api.pugs.dev/sdk.events.v1.EventsService/BatchCreate \ -H 'x-api-key: prv_...' \ -H 'content-type: application/json' \ -d '{"events": [{"eventId": "0193b2c4-8f1e-7a2b-9c3d-4e5f6a7b8c9d", "occurTime": "2026-11-14T09:30:00Z", "kind": "crawler_request", "client": {"userAgent": "... GPTBot/1.2 ...", "ip": "20.171.207.5"}, "autoProperties": {"$url": {"stringValue": "https://example.com/pricing"}, "$status_code": {"intValue": 200}}}]}' ``` One call takes up to 1,000 requests. Make `eventId` (a UUID) once and resend it unchanged on a retry, so Pug stores the request once. ## Options | Option | Default | What it does | | --------------- | ---------------------- | ---------------------------------------------------------------------------------- | | `apiKey` | required | A private key, `prv_...`. | | `endpoint` | `https://api.pugs.dev` | Where Pug runs. A self-hosted install sets its own. | | `categories` | all five | Which kinds of crawler to report: `answers`, `search`, `training`, `seo`, `other`. | | `skip` | none | Agents to leave out, by name, such as `['Googlebot']`. | | `includeAssets` | `false` | Also report requests for scripts, styles, images and fonts. | | `getIP` | the platform's | Returns the crawler's address for a request. | ## The categories | Category | Meaning | Examples | | ---------- | --------------------------------------------------------- | ------------------------------------------ | | `answers` | Fetched live because a person asked an AI product | ChatGPT-User, Claude-User, Perplexity-User | | `search` | Builds a search index that results and AI answers draw on | OAI-SearchBot, Googlebot, bingbot | | `training` | Collects pages to train models | GPTBot, ClaudeBot, CCBot | | `seo` | Crawls for an SEO tool | AhrefsBot, SemrushBot, MJ12bot | | `other` | AI-related, but none of the above | OAI-AdsBot, GoogleOther | The AI agents come from Pug's own table of 35, each with its company and, where the operator publishes them, its IP ranges. Search engines and SEO tools come from the [crawler-user-agents](https://github.com/monperrus/crawler-user-agents) list. Both ship inside the package, so a new crawler reaches your site with the package's next release. ## What it sends Only requests whose user agent names a known crawler, so your visitors' requests never leave your server. For each one it sends: | Field | Value | | ------------------ | ------------------------------------------------------------ | | `$url` | The full URL, without its query string or fragment | | `client.userAgent` | The User-Agent header | | `client.ip` | The client's address, for the IP check. Pug never stores it. | | `$status_code` | The response's status, when the adapter sees it | It never sends query strings, cookies, other headers, bodies, requests other than GET and HEAD, or (unless `includeAssets` is on) static files. ## Delivery One POST per crawler request, after the response, with a 2-second timeout and one retry on a network error or a server error. It never throws, so it can't break your site, and it logs a failure once per process. ## The client's address The package reads `CF-Connecting-IP` on Cloudflare, `x-real-ip` on Vercel, `req.ip` on Express (which follows its `trust proxy` setting) and the socket on plain Node. Pass `getIP` when that's wrong: - **Behind a CDN**, your server sees the CDN's address, so every request fails the IP check. Read the CDN's client-IP header in `getIP`. - **A fetch-style server that Cloudflare or Vercel doesn't front** can't trust those two headers, since anyone can send them. Return the socket's address, such as Bun's `server.requestIP(req)?.address`. Running at the edge (Workers, Vercel) sees every request, including those a CDN would answer from its cache. ## See them in Pug Each request is a `crawler_request` event, tagged as a bot, so it stays out of your other numbers. Insights and the Events list include bots on their own when you ask for `crawler_request` or one of its properties: | Property | Value | |---|---| | `$bot_reason` | The agent's name, such as `GPTBot` | | `$crawler_company` | Such as `OpenAI`; none for a search engine or SEO tool from the list | | `$crawler_category` | `answers`, `search`, `training`, `seo` or `other` | | `$crawler_verified` | `verified` (inside the operator's ranges), `failed` (outside them, likely an impostor) or `unchecked` | | `$status_code` | The response's status, when sent | | `$url`, `$pathname`, `$hostname` | The page requested | Break `crawler_request` down by `$crawler_category` for requests over time, rank `$crawler_company` or `$bot_reason` with Top K, or filter `$status_code` to 404 for the pages crawlers can't find. A crawler is never listed as a person. ## Volume Crawler requests count toward your Pug usage like any event, and a busy site can get more of them than page views. SEO tools are among the busiest crawlers, so `seo` is the first category to leave out. ## Self-hosted Pug Point `endpoint` at your Pug. Its server fetches each operator's IP ranges when it starts, then every 6 hours. Without internet access, set `PUG_CRAWLER_RANGES_ENABLED=false`, and every request reads `unchecked`. # Quickstart > Send your first event to Pug in under five minutes - install the Web SDK, track a page view, and confirm it in the dashboard. Source: https://docs.pug.sh/get-started/ | Markdown: https://docs.pug.sh/get-started/index.md Send your first event to Pug in under five minutes. By the end you'll have the Web SDK installed, a `page_view` flowing into your project, and confirmation in the dashboard. ## Prerequisites - A Pug account: [sign up at app.pug.sh](https://app.pug.sh) (or your self-hosted dashboard) - Node.js 18+ and a bundler-based web project (Vite, Next.js, etc.) Building a **mobile app**? This quickstart is web-only: start with the [Android](/sdks/android), [iOS](/sdks/ios) or [Flutter](/sdks/flutter) SDK instead. Building a **backend**? Use a server-side SDK - [Node](/sdks/node), [Go](/sdks/go) or [Ruby](/sdks/ruby) - or POST events directly from any language - see [Integrate over HTTP](/sdks/http). Working with a **coding agent**? [Install with AI](/get-started/ai-setup) has a ready-to-paste prompt for each platform that points the agent at these docs. ## 1. Create a project and grab your keys 1. Sign in to the [dashboard](https://app.pug.sh). 2. Create an **organization**, then a **project** inside it. 3. Collect the two values this quickstart needs: - **Project ID**: in the dashboard URL: `/p/`. - **Public key** (`pub_...`): under the **API Keys** section of your project **Overview**; safe to ship in client code. The Web SDK authenticates with your **public key**. (The same screen also shows a server-side **private key** - you don't need it here; see [Authentication](/get-started/authentication).) ## 2. Install the Web SDK ```bash npm install @pug-sh/browser ``` See [Installation](/sdks/web#install) for pnpm, yarn, bun, and framework-specific setup. No bundler? Drop in the [CDN loader snippet](/sdks/web#loader-snippet) instead. ## 3. Initialize and track Call `init` once at startup, then `track` anywhere. `init` registers your project ID and public key and begins auto-tracking (page views, clicks). The first argument to `track` is the **event name** - any string you choose. > **This install is cookieless until you ask for consent** > > With no `trackingConsent` set, the SDK captures events but writes **nothing** to > the device (no anonymous ID, no session, no cookie) and the server derives a > daily-rotating anonymous ID instead. Everything in this quickstart works that > way; the one thing that doesn't is `identify()`, which needs a stored identifier > to merge. See [Tracking consent](/sdks/web#tracking-consent) for the three states and > how to gate them behind a banner. ### Vite / React ```ts // src/main.tsx import { init, track } from '@pug-sh/browser' init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY' }) track('signup', { plan: 'pro' }) ``` ### Next.js App Router `init` must run in the browser, so wrap it in a client component: ```tsx // components/PugProvider.tsx 'use client' import { init } from '@pug-sh/browser' import { useEffect } from 'react' export function PugProvider({ children }: { children: React.ReactNode }) { useEffect(() => { init(process.env.NEXT_PUBLIC_PUG_PROJECT_ID!, { apiKey: process.env.NEXT_PUBLIC_PUG_PUBLIC_KEY! }) }, []) return <>{children} } ``` Add `PugProvider` to your root layout and store the values in `.env.local`: ``` NEXT_PUBLIC_PUG_PROJECT_ID=your-project-id NEXT_PUBLIC_PUG_PUBLIC_KEY=pub_your_public_key ``` > Only ever expose the **public** key with `NEXT_PUBLIC_*`. The private key stays server-side. ## 4. Verify in the dashboard 1. Open your project in the dashboard. 2. Go to **Live** - the active visitor count should tick up within a few seconds. 3. Go to **Events** - `page_view` (auto-tracked on init) and your `signup` event should appear. Events are batched client-side and flushed every few seconds, so allow up to ~10 seconds for the first one. Force an immediate send with `track('signup', {}, { immediate: true })`. ## 5. Identify a user (optional) After sign-in, link anonymous activity to a known user. This step needs **granted** consent - there is no anonymous ID to merge while the default cookieless state is in force, so call `optInTracking()` once the user has agreed: ```ts import { identify, optInTracking } from '@pug-sh/browser' optInTracking() await identify('user-123', { email: 'user@example.com', plan: 'pro' }) ``` `identify()` returns a promise and **never throws** (invalid input, a missing identifier and transport failures are logged and the promise resolves), so you can `await` it without a try/catch. On sign-out, call `reset()` to start a fresh anonymous session. See [Identity & sessions](/sdks/web#identify-and-sessions). ## You're done when... - [ ] `page_view` and `signup` appear in **Live** and **Events** - [ ] Auto-tracked clicks/scrolls appear (defaults are on) - [ ] `identify()` merges pre-login events into a profile (optional - needs granted consent) ## Common issues | Symptom | Likely cause | Fix | |---------|--------------|-----| | No events in dashboard | Wrong project ID or public key | Re-check the **API Keys** section of your project **Overview** | | Events in console but not dashboard | `dryRun: true` in init options | Remove `dryRun` or set `false` | | CORS errors in the browser | Wrong `endpoint` | Use `https://api.pugs.dev` or your self-hosted URL | | Nothing happens, no errors | `init()` ran outside the browser (SSR) | Call `init()` in a client component / `useEffect` | | Events delayed | Client-side batching | Normal (see step 4) - or use `{ immediate: true }` | | `identify()` does nothing, warns once | Consent is `cookieless` (the default) - no stored ID to merge | `optInTracking()` after the user agrees; see [Tracking consent](/sdks/web#tracking-consent) | | Event counts look right, unique-user counts look low | Cookieless IDs rotate daily, so unique-user metrics, funnels and retention exclude them by default | Expected before consent; see [`include_cookieless`](/api/insights#cookieless-visitors-are-excluded-from-user-counts) | ## Next steps **Next: [Core concepts](/get-started/concepts)** - orgs, projects, keys, and the event pipeline. Then: - [Initialization](/sdks/web#initialize): batching, sessions, auto-track options - [Tracking events](/sdks/web#track-events): custom events and well-known schemas - [Authentication](/get-started/authentication): public vs private keys # Install with AI > Hand your coding agent a prompt that points it at these docs, and let it wire the SDK into your app. Source: https://docs.pug.sh/get-started/ai-setup/ | Markdown: https://docs.pug.sh/get-started/ai-setup/index.md ## The prompt ### Web ```text Add Pug product analytics to this app. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/web/index.md - SDK reference - https://docs.pug.sh/get-started/index.md - quickstart - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the product actually does: its routes or screens, its main models, and the handful of things a user comes here to complete. The events worth tracking are the moments the product exists to produce - an account created, an order placed, a document shared - not every button on the page. If you cannot state the core action in one sentence, keep reading. Then: 1. Install @pug-sh/browser. 2. Call init() exactly once, where the app boots, in the browser only - never during SSR. In the Next.js App Router that means a "use client" provider mounted from the root layout. 3. Read the project ID and public key from environment variables. The public key starts with pub_ and is safe to ship. A private key starts with prv_ and must never reach client code. 4. Leave auto-tracking on and do not hand-roll page views - init() already captures them. 5. Add track() calls for the three or four actions you identified - the ones someone would look at in a weekly review. Property values must be plain JSON scalars: strings, numbers, booleans, dates. 6. If this app has authentication, call identify() after sign-in and reset() on sign-out. Note that the SDK is cookieless until optInTracking() is called, so identify() is a no-op without granted consent - tell me whether I need a consent banner rather than opting users in silently. Name events from the catalog before you invent one. It holds 127 well-known events across 19 families - commerce, authentication, billing, media, forms, support, workspace and more - and a well-known name is type-checked as you write it and fills in dashboards that a custom name leaves empty. Search it for every action you are about to track, and take property names and types from that page rather than from whatever reads idiomatically. Fall back to a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this product does, then list the files you changed, the event names you chose, and the environment variables I need to set. ``` ### Android ```text Add Pug product analytics to this Android app. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/android/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the app actually does: its activities, fragments or composables and how a user moves between them, its main models, and the handful of things a user opens the app to complete. The events worth tracking are the moments the app exists to produce - an account created, an order placed, a workout finished - not every tap. If you cannot state the core action in one sentence, keep reading. Then: 1. Add sh.pug:android from Maven Central to the app module's dependencies. It needs minSdk 21, and works from Kotlin and Java. 2. Call Pug.init() once, in Application.onCreate() - create an Application subclass and register it in the manifest if the app has none. Not in an activity: the SDK has to see each launch's first screen. 3. Keep the project ID and public key (pub_...) out of source - set them as BuildConfig fields from Gradle properties. Pug.init() throws for a key that is not a public key. 4. Leave auto-tracking on: it already tracks app_open, app_close, app_install, app_update and a screen_view per activity. In a single-activity app (Compose, or fragments under one activity), set autoScreenViews = false and call Pug.screen() on every destination change instead. 5. Add tracking for the three or four actions you identified - the ones someone would look at in a weekly review. 6. If this app has authentication, call Pug.identify() after sign-in and Pug.reset() on sign-out. Name events from the catalog before you invent one. Kotlin gets a generated named-argument method for each well-known event the SDK does not track itself - Pug.track.purchase(productId = ..., amount = ...) - and Java an event class - Pug.track(new PurchaseEvent().amount(...)) - so the compiler checks the properties for you, and the dashboards those events drive stay empty for a custom name. Reach for those first, search the catalog for every action you are about to track, and pass schema-external properties through extras. Use Pug.track(kind, properties) with a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not. Android consent has two states, starts granted and is saved across launches, which is not the same as the Web SDK - check the consent section before you add a banner. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this app does, then list the files you changed, the event names you chose, and the Gradle properties I need to set. ``` ### iOS ```text Add Pug product analytics to this iOS app. Read these first. They are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/ios/index.md: SDK reference - https://docs.pug.sh/reference/well-known-events/index.md: the well-known event catalog Then read this codebase before you write anything, and work out what the app actually does: its view controllers or SwiftUI views and how a user moves between them, its main models, and the handful of things a user opens the app to complete. The events worth tracking are the moments the app exists to produce (an account created, an order placed, a workout finished), not every tap. If you cannot state the core action in one sentence, keep reading. Then: 1. Add the Swift package https://github.com/pug-sh/sdk-ios, from 0.1.0, with Swift Package Manager, and link its Pug library to the app target. It needs iOS 15 and Xcode 16, and there is no CocoaPods or Carthage install. 2. Call Pug.initialize(projectId:options:) once: in the App's init() in a SwiftUI app, or in application(_:didFinishLaunchingWithOptions:) in a UIKit one, so the SDK sees each launch's first screen. It throws Pug.ConfigurationError for a bad value, so wrap it in do/catch with an assertionFailure in the catch. 3. Keep the project ID and public key (pub_...) out of source: set them in an xcconfig file that Git ignores and read them through Info.plist. A private key (prv_...) must never ship in the app. 4. Leave auto-tracking on: it already tracks app_open, app_close, app_install, app_update and a screen_view for each of the app's own view controllers. SwiftUI views are not view controllers, so put .pugScreen("Name") on the view each SwiftUI screen shows, inside its NavigationStack, or those screens send no screen_view. 5. Add tracking for the three or four actions you identified: the ones someone would look at in a weekly review. 6. If this app has authentication, call Pug.identify() after sign-in and Pug.reset() on sign-out. Name events from the catalog before you invent one. Swift gets a generated method with labeled arguments for each well-known event the SDK does not track itself, such as Pug.track.purchase(productId: ..., amount: ...), so the compiler checks the properties for you, and the dashboards those events drive stay empty for a custom name. Reach for those first, search the catalog for every action you are about to track, and pass schema-external properties through extras. Durations are TimeInterval seconds. Use Pug.track(_:properties:) with a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not. iOS consent has two states, starts granted and is saved across launches, which is not the same as the Web SDK: check the consent section before you add a banner. It is not App Tracking Transparency, which Pug does not need, so do not add an ATT prompt for it. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this app does, then list the files you changed, the event names you chose, and the build settings I need to set. ``` ### Flutter ```text Add Pug product analytics to this Flutter app. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/flutter/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the app actually does: its screens and navigation graph, its main models, and the handful of things a user opens the app to complete. The events worth tracking are the moments the app exists to produce - an account created, an order placed, a workout finished - not every tap. If you cannot state the core action in one sentence, keep reading. Then: 1. Add pug_flutter to pubspec.yaml. 2. Await Pug.init() in main(), after WidgetsFlutterBinding.ensureInitialized() and before runApp(). 3. Keep the project ID and public key (pub_...) out of source - pass them with --dart-define and read them with String.fromEnvironment. 4. Register PugRouteObserver on the app's navigatorObservers, otherwise screen views never fire. 5. Add tracking for the three or four actions you identified - the ones someone would look at in a weekly review. 6. If this app has authentication, call Pug.identify() after sign-in and Pug.reset() on sign-out. Name events from the catalog before you invent one. Flutter gets a generated named-argument method for all 127 well-known events - Pug.track.purchase(productId: ..., amount: ...) - so the compiler checks the properties for you, and the dashboards those events drive stay empty for a custom name. Reach for Pug.track. first, search the catalog for every action you are about to track, and pass schema-external properties through extras. Use Pug.track(kind, props: {...}) with a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not. Flutter consent has two states and starts granted, which is not the same as the Web SDK - check the consent section before you add a banner. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this app does, then list the files you changed, the event names you chose, and the dart-defines I need to pass. ``` ### Node ```text Add Pug product analytics to this Node backend. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/node/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the service actually does: its routes or handlers, its main models, and the state changes that matter to the business. On a server the events worth tracking are the ones a browser cannot observe - a payment settling, a webhook arriving, a job finishing, a subscription lapsing - not request logging. If you cannot state what this service is for in one sentence, keep reading. Then: 1. Install @pug-sh/node. It is ESM and needs Node 18+. 2. Construct one Pug instance at boot and reuse it across requests - do not build one per request. Its apiKey is the private key (prv_...), read from an environment variable, and it must never be imported into client-side code. 3. Remember the argument order: pug.track(distinctId, kind, props?, options?). The distinctId comes first because a server has no ambient user - use our own user ID, or the anon-... ID forwarded from the client. 4. Add track calls for the three or four state changes you identified. 5. Call identify() when a user record is created or changes materially, not on every request. 6. Await pug.close() in the graceful-shutdown path so queued events and identifies flush, and wire an onError handler so dropped events and identifies are logged rather than lost. Name events from the catalog before you invent one. The Node SDK checks 114 of the 127 well-known events against their schemas when track() runs, not at compile time: a property of the wrong type drops the whole event, and one named as the catalog spells it (product_id) rather than in camelCase (productId) is sent as a custom property instead. The ones a backend is placed to see are exactly the ones whose schemas are worth having - purchase, subscription_started, invoice_paid, payment_failed, order_refunded. Search the catalog for every action you are about to track, take property names - in camelCase - and types from that page, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not. There is no reset() or destroy() on the server SDK, and no immediate option on track - use flush(). Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this service does, then list the files you changed, the event names you chose, and the environment variables I need to set. ``` ### Go ```text Add Pug product analytics to this Go backend. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/go/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the service actually does: its routes or handlers, its main models, and the state changes that matter to the business. On a server the events worth tracking are the ones a browser cannot observe - a payment settling, a webhook arriving, a job finishing, a subscription lapsing - not request logging. If you cannot state what this service is for in one sentence, keep reading. Then: 1. Run go get github.com/pug-sh/sdk-go. It needs Go 1.26+, and its package is named pug, so import it as pug "github.com/pug-sh/sdk-go". 2. Construct one client with pug.New at startup and share it - do not build one per request. It is safe for concurrent use, so hand it to handlers the way this codebase passes its other dependencies. Its APIKey is the private key (prv_...), read from an environment variable, never committed. pug.New returns an error for a missing or public key - handle it at startup. 3. Remember the argument order: client.Track(distinctID, kind, fields...). The distinctID comes first because a server has no ambient user - use our own user ID, or the anon-... ID forwarded from the client. Properties are typed fields such as pug.String("plan", "pro") and pug.Float("amount", 49), in the same list as options such as pug.WithTimestamp, and a kind held in a variable needs pug.Kind(name). 4. Add track calls for the three or four state changes you identified. 5. Call client.Identify(externalID, traits...) when a user record is created or changes materially, not on every request. Use the named traits - pug.Name, pug.Email and the rest - for the keys the dashboard reads. 6. Call client.Close(ctx) in the graceful-shutdown path, after the HTTP server has shut down, so queued events and identifies flush, and set an OnError handler so dropped events and identifies are logged rather than lost. Name events from the catalog before you invent one. The Go SDK knows 114 of the 127 well-known events, and client.TrackWellKnown takes each one's typed message - &commoneventsv1.PurchaseProperties{...} from github.com/pug-sh/sdk-go/gen/common/events/v1 - so the compiler checks the properties, where Track with a well-known kind checks them at runtime and drops the event on a wrong type. The ones a backend is placed to see are exactly the ones whose schemas are worth having - purchase, subscription_started, invoice_paid, payment_failed, order_refunded. Search the catalog for every action you are about to track, use TrackWellKnown for the ones that fit, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not. There is no Reset on the server SDK, and no immediate option on Track - use Flush. Track and Identify never return errors; only the reads do. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this service does, then list the files you changed, the event names you chose, and the environment variables I need to set. ``` ### Ruby ```text Add Pug product analytics to this Ruby backend. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/ruby/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the service actually does: its routes or controllers, its main models, and the state changes that matter to the business. On a server the events worth tracking are the ones a browser cannot observe - a payment settling, a webhook arriving, a job finishing, a subscription lapsing - not request logging. If you cannot state what this service is for in one sentence, keep reading. Then: 1. Add the pug-sh gem to the Gemfile. It needs Ruby 3.3+, and it is required as "pug", not "pug-sh". 2. Construct one Pug::Client at boot and share it - do not build one per request. It is thread-safe and fork-safe, so it can be created before Puma or Unicorn fork. In Rails, use the initializer from the SDK reference, guard included, so assets:precompile still boots without credentials. Its api_key is the private key (prv_...), read from an environment variable or Rails credentials, never committed. 3. Remember the argument order: pug.track(distinct_id, kind, properties, options). The distinct_id comes first because a server has no ambient user - use our own user ID, or the anon-... ID forwarded from the client. Without braces, a key named timestamp, session_id or location sets that option instead of a property. 4. Add track calls for the three or four state changes you identified. 5. Call identify when a user record is created or changes materially, not on every request. 6. Call close in the graceful-shutdown path so queued events and identifies flush, and pass an on_error handler taking (error, undelivered) - a Pug::Undelivered whose events or identifies hold what was lost - so dropped items are logged rather than lost. Name events from the catalog before you invent one. The Ruby SDK checks 114 of the 127 well-known events against their schemas, at runtime: a property of the wrong type drops the whole event, so take property names and types from that page. The ones a backend is placed to see are exactly the ones whose schemas are worth having - purchase, subscription_started, invoice_paid, payment_failed, order_refunded. Search the catalog for every action you are about to track, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not. There is no reset on the server SDK, and no immediate option on track - use flush. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this service does, then list the files you changed, the event names you chose, and the environment variables or credentials I need to set. ``` ### HTTP API ```text Add Pug product analytics to this service by calling the HTTP API directly - there is no SDK for this runtime. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/http/index.md - request format, including worked examples - https://docs.pug.sh/api/events/index.md - the full event schema - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the service actually does: its routes or handlers, its main models, and the state changes that matter to the business. The events worth tracking are the moments the service exists to produce, not request logging. If you cannot state what this service is for in one sentence, keep reading. Then: 1. Write one small client that POSTs to /sdk.events.v1.EventsService/BatchCreate on the base URL, with the headers Content-Type: application/json, Connect-Protocol-Version: 1, and x-api-key set to the private key (prv_...) from an environment variable, never committed. 2. Wrap every custom property value in its typed form - stringValue, intValue (a JSON string), doubleValue, boolValue, timestampValue. This is the part that is most often wrong. Property keys must not start with a dollar sign, and the event kind may hold only ASCII letters, digits, _, . and -. 3. Send events in batches of at most 1000, and read "dropped" and "droppedByReason" on the response - a 200 does not mean every event landed. 4. Call it for the three or four actions you identified. Name events from the catalog before you invent one. All 127 well-known events are available over HTTP, and a well-known kind fills in the dashboards built on it, which a custom kind leaves empty. Nothing checks their properties - no compiler, and not the server, which stores what it is sent - so a misspelled name or a wrong type fails silently. Search the catalog for every action you are about to track, take property names and types from that page, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not. Do not invent fields that are not in the events schema above. When you are done, tell me in one sentence what you concluded this service does, then show me the client, the event names you chose, and the environment variables I need to set. ``` ## What you'll need Two values the agent can't find on its own - without them it invents a placeholder and leaves it there: 1. **Project ID** - in the dashboard URL, `/p/`. 2. **Public key** (`pub_...`) for a browser or mobile app, or a **private key** (`prv_...`) for a backend, through the Node, Go or Ruby SDK or the HTTP API. Both live under **Settings > API Keys**; see [Authentication](/get-started/authentication). Every prompt asks for environment variables rather than literals. Only the public key may ship to a client - it is write-scoped, so the worst a leaked one buys is junk events. A private key also reads your analytics. ## Check the agent's work Agents are good at the wiring and careless about the parts that only fail in production. Before you merge, confirm: - [ ] `page_view` and your own events appear under **Live** and **Events** in the dashboard. Allow ~10 seconds - events are batched. - [ ] No key is hardcoded, and no `prv_` key appears anywhere a browser can reach. Grep the diff for `pub_` and `prv_`. - [ ] `init` runs **once**, client-side. A second call no-ops with a console warning; an SSR call warns and does nothing. - [ ] The agent's one-line summary of what your product does is actually right. Each prompt asks for it, and it's the cheapest thing to check: if the agent misread the product, every event name below it is wrong too. - [ ] Every event that could have come from the [well-known catalog](/reference/well-known-events) did. This is the check worth making by hand: the prompt asks the agent to name what it rejected, so read that list. A custom name where a catalog event exists costs you the typed schema, leaves the dashboards built on that event empty, and renaming it later splits the metric in two. - [ ] Nobody was silently opted in. On the Web SDK, `optInTracking()` belongs behind a real consent decision - see [Tracking consent](/sdks/web#tracking-consent). ## Give the agent more than a prompt The prompt is the shortest path. Three more surfaces are worth knowing about: - **Every page as markdown** - Append `/index.md` to any docs URL, or use **Copy page** at the top of a page. [`/llms.txt`](https://docs.pug.sh/llms.txt) indexes the site; [`/llms-full.txt`](https://docs.pug.sh/llms-full.txt) is the whole corpus in one document. - **Read your data from the agent** - The [MCP server](/mcp) gives an agent tools over your own projects: run an insight, browse the event stream, look up one user, build a dashboard. Claude and ChatGPT add it from their directories. That's for asking questions after the SDK is in, not for installing it. > **Keep the docs URLs in the prompt** > > It's tempting to trim the "read these first" block. Don't - it is what stops the > agent reaching for an API from a different analytics SDK, which is the failure > mode these prompts exist to prevent. If your agent can't fetch URLs, paste > [`/llms-full.txt`](https://docs.pug.sh/llms-full.txt) into the conversation > instead. # Authentication > Public keys, private keys and dashboard JWTs - which credential reaches which service, and what each error code means. Source: https://docs.pug.sh/get-started/authentication/ | Markdown: https://docs.pug.sh/get-started/authentication/index.md Pug has three auth boundaries. Each maps to a set of RPC services - using the wrong credential returns `Unauthenticated` or `PermissionDenied`. ## The three credentials | Credential | Format | Used by | Header | Reaches | |------------|--------|---------|--------|---------| | **Public key** | `pub_...` | Browser / app SDK | `x-api-key` | `sdk.events.v1.EventsService`, `sdk.profiles.v1.ProfilesSDKService` | | **Private key** | `prv_...` | Your server | `x-api-key` | The same two `sdk.*` services, and `shared.*`: insights, profiles, activity, projects, dashboards | | **JWT** | session token | Dashboard | `Authorization: Bearer` | `dashboard.*` (and `shared.*`) | The project is resolved **from the API key**, so SDK and server requests don't send a project ID. Dashboard JWT requests optionally include an `x-project-id` header to scope to a project. ## Where keys live Keys live under **Settings > API Keys**. A project holds any number of them, so you can issue one per app or service and revoke it on its own. Your project **Overview** also shows the public key next to the SDK setup snippets. - **Public key** is displayed in plain text: it's safe in client code. It can write events and identify users, but cannot read analytics. - **Private key** is shown **once, when you create it**: copy it then. Pug stores only a digest of the key, so it cannot be revealed afterwards; the list shows a mask (`prv_...3f9c`) to tell your private keys apart. Treat it like a password. It can read insights, profiles, activity and dashboards, and create and edit dashboards. There is no rotate button. To replace a key, create its replacement, update your SDK `apiKey` / server env var, deploy, then revoke the old one. ## Public key: client SDKs The Web and Flutter SDKs take the public key as `apiKey`, the Android SDK as the argument to `Options` and the iOS SDK as `Pug.Options(apiKey:)`; each sends it as `x-api-key` on every request: ```ts import { init } from '@pug-sh/browser' init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY' }) ``` The public key is **write-scoped**: `BatchCreate` (events) and `Identify` (profiles). It cannot reach the `shared.*` read APIs, so it's safe to ship in a browser bundle or mobile binary. ## Private key: your servers Use the private key from trusted server-side code to read analytics. The **[Node](/sdks/node#server-side-reads)**, **[Go](/sdks/go#server-side-reads)** and **[Ruby](/sdks/ruby#server-side-reads)** SDKs wrap these reads - construct a client with your private key and call `pug.insights`, `pug.profiles`, or `pug.activity` (`client.Insights`, `client.Profiles` and `client.Activity` in Go): ```ts import { Pug } from '@pug-sh/node' const pug = new Pug({ apiKey: process.env.PUG_PRIVATE_KEY! }) const result = await pug.insights.query({ /* spec, timeRange, granularity */ }) ``` From any other language, send the private key as `x-api-key` against the `shared.*` services (which accept a private key **or** a dashboard JWT): ```bash curl -X POST https://api.pugs.dev/shared.insights.v1.InsightsService/Query \ -H "x-api-key: prv_YOUR_PRIVATE_KEY" \ -H "Connect-Protocol-Version: 1" \ -H "Content-Type: application/json" \ -d '{ /* InsightQuerySpec */ }' ``` Replace the body with a real `InsightQuerySpec` - see [Insights API](/api/insights) for the field-by-field shape and a complete example. Pug's [MCP server](/mcp) hands the same APIs to an AI agent as tools. A client that can sign in, such as Claude or ChatGPT, uses your Pug account and needs no key; any other client connects with a private key. Never ship a private key to a browser, mobile app, or public repo. ## JWT: the dashboard The dashboard obtains a short-lived JWT when a user signs in, and sends it as `Authorization: Bearer ` (plus `x-project-id` to scope to a project). JWTs reach the `dashboard.*` management services and the `shared.*` read services. They're refreshed automatically by the dashboard client - don't hard-code them in scripts; use a private key for automation instead. ## Connect RPC All APIs speak [Connect RPC](https://connectrpc.com/) over HTTP/2 and accept the Connect, gRPC, and gRPC-Web protocols. The request path is `/./`, e.g. `/sdk.events.v1.EventsService/BatchCreate`. For JSON requests, include `Connect-Protocol-Version: 1`. To send events without an SDK, see [Integrate over HTTP](/sdks/http). To generate a typed client from the protobuf definitions, see the [API overview](/api). ## Error responses Connect returns structured errors: | Code | Meaning | Typical cause | |------|---------|---------------| | `Unauthenticated` | Missing or invalid credential | Wrong key, missing `x-api-key`, or a public key calling a `shared.*` read API | | `PermissionDenied` | Valid credential, insufficient access | A dashboard role that doesn't permit the call | | `InvalidArgument` | Payload failed validation | A rejected field: see below | | `NotFound` | Resource doesn't exist | Wrong project or profile ID | Common `InvalidArgument` causes: - A required field is missing. - A custom property key is prefixed with `$` (reserved for auto-properties). - `kind` (the event name) holds a character other than ASCII letters, digits, `_`, `.` and `-`. Responses include field-level details from server-side validation - fix the named field and retry. ## Advanced: proxying > If you need server-side logic before events reach Pug (enrichment, filtering, auth of your own), run your own endpoint that forwards requests to Pug with the appropriate key. This keeps the credential on your backend instead of in the client. ## Further reading - [Core concepts](/get-started/concepts): the auth modes in context - [API overview](/api): service index and conventions - [MCP server](/mcp): connecting an agent by signing in or with a private key - [RPC services](/reference/rpc-services): every service and its auth mode - [Self-hosting configuration](/self-hosting/configuration): `PUG_JWT_SECRET_KEY` and CORS # Core concepts > Orgs, projects, events, profiles, sessions and insights - the vocabulary every other page builds on. Source: https://docs.pug.sh/get-started/concepts/ | Markdown: https://docs.pug.sh/get-started/concepts/index.md Shared vocabulary used across Pug, open-source product analytics: its SDKs, the API, and the dashboard. Read this once - every other page builds on these ideas. ## Organization and project Pug is multi-tenant. Your data always lives inside a **project**; projects belong to an **organization**. You only deal with these for billing and access - the things you actually instrument are **events** and **profiles**. - `Organization` - billing & member boundary - `Members (roles)` - `Project` - data boundary - `API keys (public + private)` - `Events` - `Profiles` | Concept | What it is | Scope | |---------|-----------|-------| | **Organization** | Team workspace with members and billing | All projects in the org | | **Project** | Isolated analytics environment | Events, profiles, insights | | **Public key** (`pub_...`) | Client credential for SDKs | Single project | | **Private key** (`prv_...`) | Secret credential for your servers | Single project | The dashboard URL is prefixed with the active project: `/p//...`. ## Event pipeline When your app calls `track()`, the event travels through an async pipeline before it appears in analytics. 1. **SDK (browser / app)** - `track('purchase', { productId: 'sku_123', amount: 29.99, currency: 'USD' })` 2. **sdk.events.v1.EventsService/BatchCreate** (Connect RPC, x-api-key auth) 3. **NATS (JetStream queue)** 4. **Workers** (geo, user-agent, bot-score enrichment) 5. **ClickHouse** (analytics storage) 6. **Dashboard & shared.insights.v1** (queries, charts, KPIs) **Timing:** ingestion is near-real-time. Events typically appear in **Live** within seconds and in **Insights** queries within the same minute. Profile writes are fully async, processed by profile workers. ## Events An **event** is a named occurrence with properties and a timestamp. ```ts track('button_clicked', { label: 'Sign up', page: '/pricing' }) ``` - **Event name** (`kind`): ASCII letters, digits, `_`, `.` and `-`; [well-known events](/reference/well-known-events) have typed schemas. - **Custom properties**: your key/value pairs (string, number, boolean, timestamp). - **Auto-properties**: fields prefixed with `$` that the SDK and server attach automatically (e.g. `$url`, `$browser`, `$country`). `$`-prefixed keys are reserved; see [Auto-properties](/reference/auto-properties). - **Timestamp**: defaults to send time; override per event for offline replay. Events are immutable once stored. Corrections mean a new event or a profile-trait update. ## Profiles A **profile** represents a user - anonymous or identified. ### Anonymous to identified 1. A visitor arrives and consents. The SDK creates an **anonymous ID** (`anon-...`) tied to the device. 2. Events accumulate against that anonymous ID. 3. The user signs in. You call `identify('user-123', { email: '...' })`. 4. On that **first** identify, the SDK sends the anonymous ID alongside your external ID so the backend can **merge** the prior anonymous activity into the identified profile. Step 1 is what consent buys. Under the Web SDK's default [cookieless](/sdks/web#tracking-consent) state there is no device-side anonymous ID at all - the server derives a daily-rotating one instead, events still count as traffic, and step 4 has nothing to merge. Granting consent later starts a fresh anonymous ID; it does not reach back. To join the two halves of that funnel you need a value you know on both sides, such as an email captured at signup and passed to `identify()`. ```ts // Before sign-in - anonymous track('page_view') track('add_to_cart', { productId: 'sku_123' }) // After sign-in - merges anonymous history into the identified profile await identify('user-123', { email: 'user@example.com', plan: 'pro' }) track('purchase', { productId: 'sku_123', amount: 29.99, currency: 'USD' }) ``` Three ID terms recur across the SDKs and API: | ID | What it is | When used | |----|-----------|-----------| | **Anonymous ID** (`anon-...`) | Device ID the SDK generates | Before sign-in, once consent is granted | | **External ID** | Your stable user ID, passed to `identify()` | After sign-in | | **Distinct ID** | The umbrella value stored on every event | Anonymous ID until identified, then external ID | | **Cookieless ID** (`cookieless-...`) | Server-derived, rotates daily, never stored on the device | Before consent; excluded from user counts | ### Storage and timing - **Writes** (identify, trait updates, merges) are processed asynchronously by profile workers via NATS. - Expect a few seconds between an `identify()` call and the profile appearing in dashboard search. - Use a **stable** external ID (your database user ID), not something that changes like an email. ## Sessions A **session** groups events within a single visit. SDKs manage session IDs automatically: - A new session starts on the first event after the **idle timeout** (default 30 minutes of inactivity). - The session extends on each event inside the window, up to a **max duration** (default 24 hours). - The Web SDK syncs the session ID across browser tabs via `localStorage`. - Before consent, the Web SDK stores no session and sends none - the server stitches one from the cookieless ID instead, on the same 30-minute inactivity rule. Force a new session without clearing identity with `rotate()`. Clear identity and start fresh with `reset()`. ## Insights An **insight** is a query specification - the definition of an analytics question, not a saved chart: | Field | Example | |-------|---------| | Events | `page_view`, `purchase` | | Time range | Last 7 days | | Granularity | Day | | Aggregation | Unique users | | Breakdown | `$country` | | Filters | `plan = 'pro'` | The same insight model powers the dashboard's charts and the [`shared.insights.v1.InsightsService`](/api/insights) API, which you can query from your own backend with a **private key**. Insight types include trends, funnels, retention, segmentation, user flow, and session metrics. ## Authentication modes Pug has three auth boundaries: the **public key** (`pub_...`) authenticates client SDKs, the **private key** (`prv_...`) authenticates your server, and a **JWT** authenticates the dashboard. See [Authentication](/get-started/authentication) for the full matrix of headers, scopes, and examples. ## Further reading - [Authentication](/get-started/authentication): keys, headers, Connect RPC - [Well-known events](/reference/well-known-events): typed event schemas - [Glossary](/reference/glossary): quick term lookup # SSO & domains > Verify your company's domain, add your team automatically, require SSO, and connect Okta, Entra ID or any other OIDC provider. Source: https://docs.pug.sh/get-started/sso/ | Markdown: https://docs.pug.sh/get-started/sso/index.md Org admins set up single sign-on under **Settings > SSO & domains**. Only admins see the tab. It works the same on Pug Cloud and on a self-hosted server. [Cloud and self-hosted](#cloud-and-self-hosted) lists the few differences. | Setting | What it does | Default | |---------|--------------|---------| | [Domains](#verify-a-domain) | Prove your org owns a domain, such as `acme.com`, with a DNS record. The other settings need one. | - | | [Auto-join](#auto-join) | People who sign in through SSO with an `@acme.com` account join your org. | Off | | [Let members create their own organizations](#org-creation) | When off, `@acme.com` people can't create orgs of their own. | On | | [Require SSO](#require-sso) | `@acme.com` accounts can sign in only through SSO. Passwords and email links stop working for them. | Off | | [SSO connections](#sso-connections) | Sign people in through your company's identity provider, such as Okta, Microsoft Entra ID or Keycloak. | None | ## What counts as SSO On this page, "SSO" means a sign-in through a provider that speaks for your domain. Only these sign-ins **prove** a domain: | Sign-in | Proves `acme.com`? | |---------|--------------------| | **Continue with Google**, with a Google Workspace account on `acme.com` | Yes | | **Continue with Google**, with a personal Google account, even one with an `@acme.com` address | No | | The [SSO connection](#sso-connections) that signs in `acme.com` | Yes | | A provider the operator set up for `acme.com` on a [self-hosted server](/self-hosting/authentication#domains-a-provider-speaks-for) | Yes | | An email link or a password | No | Google Workspace needs no setup. Google marks Workspace accounts with their domain, but only once the company has proved to Google that it owns the domain. A personal Google account has no such mark, so it proves nothing. ## Verify a domain 1. **Add the domain** Under **Domains**, choose **Add domain** and enter it, for example `acme.com`. 2. **Add the TXT record at your DNS provider** The domain's row shows a record for your org. Copy both values from there: | Type | Name | Value | | - | - | - | | `TXT` | `_pug-verification.acme.com` | `pug-verification=...` | 3. **Choose Verify now** The domain turns **Verified**. DNS changes can take a few minutes to show up, so try again if the record isn't found yet. A pending domain stays in the list until you verify or remove it. **Keep the record.** Pug checks it again whenever your org turns on something that acts on other people, such as auto-join, Require SSO or a new SSO connection. If the record is gone, the change is refused. Turning a setting back off always works. - Each org gets its own value. Several orgs can verify the same domain, such as two orgs of one company. DNS allows several TXT records with the same name. - Subdomains are separate. `eng.acme.com` needs its own verification. - An org can add up to 10 domains. - The settings apply to every domain the org verified, including ones verified later. Can't add a DNS record? The operator can verify the domain for you, and it then shows as **Verified by your administrator**. On Pug Cloud, [contact us](#cloud-and-self-hosted). On a self-hosted server, the operator runs [`pug domains verify`](/self-hosting/cli#domains). ## Auto-join Auto-join is off by default. Turn it on and pick the **Role for new people**: Viewer (the default) or Member. Auto-join never makes anyone an admin. While it's on, people who sign in through SSO with an account on one of your verified domains join your org: | Who | When they join | |-----|----------------| | A new person | At their first SSO sign-in. They don't get an org of their own. | | An existing Pug user | At their next SSO sign-in. They keep the orgs they already have. | | Someone already signed in through SSO | The next time their session refreshes, about once a day while they use Pug. | | Someone signed in with an email link or a password | Not through auto-join. Invite them, or they join at their next SSO sign-in. | They see "You joined Acme." in the dashboard, and the **Members** page marks them `via acme.com`. - A pending invite wins. Someone with a pending invite that hasn't expired isn't auto-joined, and the invite's role applies when they accept it. - Auto-join never changes the role of someone already in the org. - Turning auto-join off stops new joins. People who already joined stay. > **Removing someone doesn't stick while auto-join is on** > > A removed member, or one who left, is added back at their next SSO sign-in or session refresh. The only way to keep one person out is to turn auto-join off. ## Org creation **Let members create their own organizations** is on by default. When you turn it off, people with an email on your verified domains: - can't create new orgs. The dashboard hides the option, and the server refuses with "your company doesn't allow creating new orgs". - get no org when they sign up. Auto-join or an invite adds them to yours. Until then they see "You're not in an org yet". Admins of your org can still create orgs. People on other domains, such as a contractor on `gmail.com`, aren't affected. Orgs that already exist are not touched. ## Require SSO Each verified domain has a **Require SSO** switch. When it's on, accounts on that domain must sign in through SSO: - Passwords and email links stop working for them. Pug keeps the passwords, so they work again if you turn Require SSO off. - People signed in another way are signed out within a day, at their next session refresh. So are SSO sessions started before Require SSO was available. - It applies to every account on the domain, in every org, **admins included**. - An invited person on the domain is asked to sign in through SSO, and the invite is accepted after that. - API keys keep working. They belong to projects, not people, so SDKs, the API and key-based [MCP](/mcp) clients are not affected. An MCP connection made by signing in belongs to a person, though: one approved without SSO stops within the hour. On the sign-in page, an `@acme.com` email goes straight to the domain's SSO buttons, with no email link option. The switch stays disabled until someone has signed in once through SSO with an account on the domain. This stops an admin from locking out a company that doesn't use that provider. > **If SSO breaks, nobody on the domain can sign in** > > For example, when your identity provider's client secret expires. That includes your admins, so nobody can sign in to turn Require SSO off. On Pug Cloud, [contact us](#cloud-and-self-hosted). On a self-hosted server, the operator runs `pug domains unenforce acme.com`, which turns Require SSO off in every org. ## SSO connections A connection signs people in through your company's own identity provider over OIDC. Okta, Microsoft Entra ID, Keycloak, Auth0, OneLogin and most others work. You need a verified domain first. Google Workspace needs no connection. 1. **Create an app at your identity provider** Create an OIDC web application that uses the Authorization Code flow and has a client secret. Assign the people or groups who should use Pug. Note the issuer URL, client ID and client secret. If the provider asks for a redirect URL now, leave it blank or enter a placeholder. You get the real one in step 3. 2. **Add the connection in Pug** Under **SSO connections**, choose **Add connection**, fill in the fields below, and choose **Save**. Pug reads the issuer's OpenID configuration on save, so a wrong issuer URL fails right away. 3. **Register the redirect URL** The saved connection shows its **Redirect URL**. Add it to the app at your identity provider. On Pug Cloud it looks like this: ```text https://app.pug.sh/oauth/callback/ ``` 4. **Test it** In a private window, open the sign-in page. Enter an email on one of the connection's domains, choose **Continue**, then choose the connection's button. | Field | What to enter | |-------|---------------| | **Button label** | What people see on the sign-in button, such as "Acme SSO". | | **Issuer URL** | The provider's issuer, exactly as its OpenID configuration names it, including any trailing slash. It must use HTTPS. | | **Client ID** | From the app you created. | | **Client secret** | From the app you created. Pug stores it encrypted and never shows it again. When you edit a connection, leave it blank to keep it. A new issuer or client ID needs it again. | | **Domains** | The verified domains this connection signs in. | Pug asks for the `openid`, `profile` and `email` scopes. Your provider must send the `email` claim in the ID token. It doesn't need to send `email_verified`. | Provider | Issuer URL | |----------|------------| | Okta | `https://`, or `https:///oauth2/default` for a custom authorization server | | Microsoft Entra ID | `https://login.microsoftonline.com//v2.0`. Use your tenant ID, not `common`. | | Keycloak | `https:///realms/` | | Auth0 | `https:///`, with the trailing slash | When in doubt, open `/.well-known/openid-configuration` and copy its `issuer` field. ### How people sign in with a connection A connection doesn't add a button to the sign-in page. People enter their work email and choose **Continue**. For a domain with a connection, the page then shows **Continue with Acme SSO**. It also offers **Email me a link instead**, unless the domain requires SSO. A connection signs in only emails on the domains it lists. People on other domains, such as contractors, sign in another way and join by invite. ### Connection rules - **One connection per domain**, across every org that verified it. The form shows which connection already signs in a domain, and that domain can't be picked. - An org can have up to 10 connections, each for its own domains. A company that buys another can keep both identity providers while it merges them. - **A new issuer unlinks** the people who signed in through the connection. They link again by email at their next sign-in. Deleting a connection unlinks them too. - A connection can't be deleted or lose a domain while any org requires SSO for that domain. Turn Require SSO off first. - A connection can't use Google's issuer. Google Workspace accounts already prove their domain through **Continue with Google**. ## Several orgs, one domain Each org that verified a domain gets every setting. When their choices differ, the strictest wins: | Setting | With two orgs | |---------|---------------| | Auto-join | Each org decides for itself. A person can join both, with each org's role. | | Let members create their own organizations | Off if either org turns it off. Admins of either org can still create orgs. | | Require SSO | On if either org turns it on. | | SSO connection | One per domain. It signs the domain in for every org that verified it. | The tab says when another org is stricter, for example "Also required by another organization that verified acme.com." To lift a limit, every org that set it must turn it off. ## Cloud and self-hosted Everything above works on both. These things differ: | | Pug Cloud | Self-hosted | |---|---|---| | Google Workspace | Works with no setup, through **Continue with Google**. | The operator adds a Google client to `PUG_CONFIG_FILE` once. See [Authentication](/self-hosting/authentication#google). | | SSO connections | On. Your issuer must be reachable from the internet. | On once the operator sets `PUG_SSO_SECRET_KEY`. See [Org SSO connections](/self-hosting/authentication#org-sso-connections). | | Redirect URL | `https://app.pug.sh/oauth/callback/` | `https:///oauth/callback/` | | A provider for the whole server | - | The operator can list your identity provider in `PUG_CONFIG_FILE` with `emailDomains`. It shows as a button for everyone. | | Verifying a domain without DNS | Contact us. | The operator runs `pug domains verify`. | | Getting back in after a Require SSO lockout | Contact us. | The operator runs `pug domains unenforce`. | On Pug Cloud, contact us at [hello@pug.sh](mailto:hello@pug.sh) and include the domain. To have a domain verified, also include your **Organization ID**, from **Settings > Organization**. ## Not supported yet - **SAML.** Use OIDC. Okta, Entra ID, OneLogin and other SAML providers speak it too. - **SCIM.** Suspending someone at your identity provider stops their new sign-ins, but a session they already have keeps working. Remove people who leave on the **Members** page, and mind the [auto-join caution](#auto-join). - **Group-to-role mapping.** Roles come from auto-join or invites. - **Single logout.** Signing out of Pug doesn't sign you out of your identity provider. - **Wildcard subdomains.** Verify each subdomain on its own. ## Troubleshooting | Message | Cause | Fix | |---------|-------|-----| | "no TXT record for acme.com holds this org's verification value" | The record isn't there, or doesn't show up yet. | Check the name and value, and wait a few minutes. | | "we couldn't reach DNS to check the record" | The DNS lookup failed. | Try again in a minute. | | "verify a domain before turning this on" | The org has no verified domain. | Verify one first. | | Require SSO stays disabled | Nobody has signed in through SSO with an account on the domain yet. | Sign in once through SSO with an account on it. | | "enter the issuer exactly as its OpenID configuration names it" | The issuer URL differs from the `issuer` field, often by a trailing slash. | Copy the `issuer` field. | | "we couldn't read the issuer's OpenID configuration" | Pug couldn't fetch `/.well-known/openid-configuration`. | Check the URL. Pug Cloud needs an issuer on the internet. | | "the issuer is on a private network address" | The issuer's address is private, and the server doesn't reach those. | Self-hosted: the operator sets `PUG_SSO_ALLOW_PRIVATE_ISSUERS=true`. | | "enter the client secret again" | The issuer or client ID changed, or the server's key did. | Enter the client secret. | | "another SSO connection already signs in this domain" | One connection per domain. | Use that connection, or ask its admins to take the domain off it. | | "Acme SSO sign-in could not be started" | The browser couldn't read the provider's OpenID configuration. | The provider must allow cross-origin requests to it. Okta, Entra ID, Auth0 and Google do. | | "Acme SSO can't sign in that account to Pug" | The email, or the Pug account it belongs to, isn't on a domain the connection lists. | Add the domain to the connection, or sign in another way. | | "Acme SSO couldn't sign you in" | Usually the connection's setup, such as its client secret or a missing `email` claim. | Check both at your identity provider, then edit the connection. | ## Further reading - [Self-hosting authentication](/self-hosting/authentication): provider config, `PUG_SSO_SECRET_KEY`, and the domain commands - [CLI reference](/self-hosting/cli#domains): `pug domains` - [Core concepts](/get-started/concepts): orgs, projects and members # MCP server > Pug's analytics API for AI agents: sixteen tools that read and one that creates and edits dashboards, reached by signing in to Pug or with a private key. Source: https://docs.pug.sh/mcp/ | Markdown: https://docs.pug.sh/mcp/index.md Pug, open-source product analytics, serves its analytics API as a **Model Context Protocol** server at `/mcp`, so an agent can answer questions about your product's data (run an insight, browse the raw event stream, look up one user) without you writing the query. Sixteen of its seventeen tools read; `upsert_dashboard` creates and edits dashboards. The endpoint is a thin adapter, not a second API: every tool call is replayed through the same Connect handlers an HTTP request hits, so validation, authentication and authorization behave identically. Anything the [Insights](/api/insights), [Profiles](/api/profiles) or Activity services refuse over HTTP, they refuse here. ## Use with Claude connectors Pug is listed in [Claude's connectors directory](https://claude.ai/directory/pug), so Claude's apps (claude.ai, Desktop and mobile) need no URL or config file. Each person connects Pug from the directory and signs in to it. ### Pro, Max and other individual plans 1. In Claude, go to **Customize > Connectors** and select **Discover**. 2. Search for `Pug` and open its listing, or go straight to [claude.ai/directory/pug](https://claude.ai/directory/pug). 3. Select **Connect to Claude**. 4. A Pug page opens. Sign in if asked, review the projects Claude will read and click **Allow**, and you are back in Claude. ### Team and Enterprise plans An Owner opens Pug's listing and selects **Connect for your team**, which adds Pug for the whole organization. Each member then selects **Connect to Claude** there and approves the connection on Pug's page with their own account, as in step 4 above. Until an Owner adds Pug, members see **Request**, or a note to ask an Owner, in place of the connect button. Every connection belongs to one person and acts with their role, so removing someone from a Pug org cuts their connection off from it at their next call. Disconnecting in Claude leaves the connection listed in Pug until it expires, so remove it under **Settings > AI connections** as well. ### As a custom connector The directory listing connects to Pug Cloud. To connect Claude to a [self-hosted](#self-hosting) server, or with a private key, add Pug by its URL: 1. In Claude, go to **Customize > Connectors**. 2. Click **+ Add**, then **Add custom connector**. 3. Name it `Pug`, the name your connector list shows. 4. Paste your server's `/mcp` URL, or `https://api.pug.sh/mcp` for Pug Cloud, and click **Continue**. 5. Claude detects Pug's sign-in. Keep **Sign in now**, and **Use Claude's published identity** as the OAuth client, then click **Add** and approve the connection on Pug's page. On Team and Enterprise plans, an Owner adds it under **Organization settings > Connectors**: click **Add**, hover over **Custom**, select **Web** and continue from step 3. Members then find Pug under **Customize > Connectors**, marked **Custom**, and click **Connect**. Keep **Use Claude's published identity**: Pug recognizes Claude by the metadata document Anthropic publishes and has no dynamic client registration, so the other two OAuth client choices fail. If your dialog shows **Advanced settings** instead, leave the OAuth client ID and secret empty. ### With a private key Choosing **No sign in** in step 5 connects with a [private key](#private-key) instead. Add it under **Request headers**, picking `x-api-key` and pasting the key on its own: | Header | Value | |--------|-------| | `x-api-key` | `prv_YOUR_PRIVATE_KEY` | > **Claude sends the header value verbatim** > > It adds no scheme of its own. Under `Authorization` you would have to type > `Bearer ` and then the key, space included; entering the bare key there sends > `Authorization: prv_...`, which has no bearer scheme to parse and comes back > `401`. `x-api-key` carries no scheme to get wrong, which is why it is the one to > choose. > > Request-header authentication is in **beta** on Anthropic's side and available > to a limited set of organizations. If the section is not in your dialog, sign in > instead. A request header is stored on the connector, not on a person, so everyone who can use that connector shares one key: they read the same project and can edit its dashboards, whatever their role in Pug, and revoking the key disconnects all of them at once. That suits a team that wants one project without each person needing a Pug account; it is not a way to give each person their own scope. Claude can't change a connector's authentication once it is added. To move one that uses a key over to sign-in, remove it and add it again. ## Use with ChatGPT Pug is listed in [ChatGPT's plugins](https://chatgpt.com/plugins/plugin_asdk_app_6af72bdabb608191b3fcd1b20baa12bc), so ChatGPT needs no URL. Each person installs Pug and signs in to it: 1. In ChatGPT, go to **Plugins** and search for `Pug`, or go straight to [its listing](https://chatgpt.com/plugins/plugin_asdk_app_6af72bdabb608191b3fcd1b20baa12bc). 2. Select **Install plugin**. 3. When ChatGPT sends you to Pug, sign in if asked, review the projects ChatGPT will read and click **Allow**. Removing the plugin in ChatGPT leaves the connection listed in Pug until it expires, so remove it under **Settings > AI connections** as well. ### As a custom MCP server The listing connects to Pug Cloud. To connect ChatGPT to a [self-hosted](#self-hosting) server, add Pug by its URL, from ChatGPT on the web: 1. Go to **Plugins**, select **Add**, then **Add custom MCP server**. 2. Name it `Pug`, enter your server's `/mcp` URL, or `https://api.pug.sh/mcp` for Pug Cloud, and choose **OAuth**, leaving any client ID and secret empty. 3. Accept the risk warning, select **Create as a plugin**, then install it. 4. When ChatGPT sends you to Pug, sign in if asked, review the projects ChatGPT will read and click **Allow**. ## Endpoint | Environment | URL | |-------------|-----| | Pug Cloud | `https://api.pug.sh/mcp` | | Self-hosted / local | `http://localhost:3000/mcp` | Use `api.pug.sh` even though the [HTTP API](/api) is at `api.pugs.dev`. Both hosts reach the same server and a private key works at either, but signing in works only at `api.pug.sh`, the host that issues the tokens. Transport is **streamable HTTP** in stateless mode, with no stdio bridge, so your client needs remote-server support. Both `/mcp` and `/mcp/` are served, so a trailing slash from an ingress or a pasted URL is fine. Every reply comes back on the POST as JSON. The spec's optional standalone SSE stream (`GET /mcp`) is refused with `405`, since a stateless server has no session for it to attach to. Clients that treat that stream as optional, as the ones on this page do, are unaffected. ## Authentication `/mcp` takes one of two credentials. Signing in acts as you in every project of your orgs and needs no key. A private key reaches its own project, for clients that can't sign in. ### Sign in A client that supports MCP sign-in (OAuth) and identifies itself with a client ID metadata document, as Claude's apps, Claude Code and ChatGPT do, needs only the URL. It opens a Pug page where you sign in if asked, see the projects it will read, and click **Allow**. Pug offers no dynamic client registration, so a client that registers only that way needs a [private key](#private-key) instead. The connection reads every project in the orgs you belong to when you approve it, including projects added to them later, for as long as you stay in each org. An org you join, or leave and rejoin, after approving isn't included until you connect again. The connection acts with your current role in each org: where you are a viewer it only reads, and where you are a member or an admin it can also create and edit dashboards. There is no key to store or leak. Pug lists every connection under **Settings > AI connections**, with its orgs and when it was last used. **Disconnect** one there and the client's next call fails. A connection unused for 90 days expires, after which the client asks you to sign in again. ### Private key A client that can't sign in sends a private key, either way: ```http Authorization: Bearer prv_YOUR_PRIVATE_KEY ``` ```http x-api-key: prv_YOUR_PRIVATE_KEY ``` Use whichever your client makes easy. If a request carries both, `x-api-key` wins. The key names its project, so the config carries no project ID: `list_projects` returns that project alone, and a call naming any other is refused. A key has no role, so whoever holds it reads the project and can create and edit its dashboards. Public keys (`pub_...`) and dashboard JWTs are both rejected with `401`. See [Authentication](/get-started/authentication) for where keys live. > **Keep the key out of the config file** > > `.cursor/mcp.json`, `.vscode/mcp.json` and a project's `.codex/config.toml` live > in the repo and get committed. None of them needs the key inline: Cursor > interpolates `${env:VAR}`, VS Code prompts for a `${input:...}`, and Codex reads a > named environment variable, as the examples below do. Issue a **dedicated key > per client** under Settings > API Keys so you can revoke one without breaking the > others. ## Connect a client ### Claude Code Claude Code logged in with a Claude account picks up that account's connectors, so if you connected Pug in Claude's apps, `/mcp` already lists it and there is nothing to add. Otherwise add it yourself: ```bash claude mcp add --transport http pug https://api.pug.sh/mcp ``` Then run `/mcp` inside Claude Code, or `claude mcp login pug` in your shell, and sign in when your browser opens. `/mcp` also confirms the server connected and lists its tools. The token never lands in `.mcp.json`, so `--scope project` can share the server with your team, and each person signs in as themselves. To use a private key instead: ```bash claude mcp add --transport http pug https://api.pug.sh/mcp \ --header "Authorization: Bearer prv_YOUR_PRIVATE_KEY" ``` That writes to your own local config. With `--scope project` it would write the key into the repo's `.mcp.json`, which gets committed: use an environment variable there, or keep the default scope. ### Codex ```bash codex mcp add pug --url https://api.pug.sh/mcp \ --bearer-token-env-var PUG_PRIVATE_KEY ``` Or write it into `~/.codex/config.toml`, or `.codex/config.toml` for a single trusted project: ```toml [mcp_servers.pug] url = "https://api.pug.sh/mcp" bearer_token_env_var = "PUG_PRIVATE_KEY" ``` Codex sends that variable's value as `Authorization: Bearer ...`. There is no inline token field (a literal key in the config is rejected), so export `PUG_PRIVATE_KEY` before launching Codex. ### Cursor In `~/.cursor/mcp.json` (global) or `.cursor/mcp.json` (this project only): ```json { "mcpServers": { "pug": { "url": "https://api.pug.sh/mcp", "headers": { "Authorization": "Bearer ${env:PUG_PRIVATE_KEY}" } } } } ``` Cursor resolves `${env:...}` from the environment it was launched with, so export `PUG_PRIVATE_KEY` in your shell profile rather than pasting the key here. ### VS Code In `.vscode/mcp.json`. The `inputs` entry makes VS Code prompt for the key once and store it itself, so nothing secret lands in the file: ```json { "inputs": [ { "type": "promptString", "id": "pug-private-key", "description": "Pug private API key", "password": true } ], "servers": { "pug": { "type": "http", "url": "https://api.pug.sh/mcp", "headers": { "Authorization": "Bearer ${input:pug-private-key}" } } } } ``` ### Any other client A client that can [sign in](#sign-in) needs only the URL. Anything else that speaks streamable HTTP and can set a request header works with a private key: point it at `https://api.pug.sh/mcp` and add `Authorization: Bearer prv_...`. To check the URL and key without a client, ask the server for its tool list. The endpoint is stateless, so this works with no prior handshake: ```bash curl -X POST https://api.pug.sh/mcp \ -H "Authorization: Bearer prv_YOUR_PRIVATE_KEY" \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` A healthy response lists every tool with its description and input schema. `401` means the credential was refused; check the `prv_` prefix and that the key has not been revoked. `400` with a complaint about `Accept` means that header is missing a half: it must offer **both** `application/json` and `text/event-stream`, even though the reply comes back as JSON. The server ships its own guidance to the agent at initialize, so a client that surfaces MCP instructions already knows to call `list_projects` first, to discover the schema before querying, which tools are project-wide and which describe one user, and to remove a dashboard tile only when you ask. ## Tools Every tool but `list_projects` works in one project, named by its `project_id` argument. With a key it is optional, since the key names its project. With a sign-in every call needs it, and a call without one is refused with a message naming `list_projects`. The server describes each tool to the agent itself; in outline: | Group | Tools | What the agent can do | |-------|-------|-----------------------| | Projects | `list_projects` | List the projects the connection reads, each with its org | | Discovery | `get_insights_filter_schema`, `get_insights_property_values`, `get_activity_filter_schema`, `get_activity_property_values` | List the event kinds and property keys that exist, and the values seen for one key, so a query names real ones | | Project-wide | `query_insights`, `explore_events` | Run trends, funnels, retention, segmentation, user flows, top-K and maps (the [Insights API](/api/insights) spec), or page through the raw event stream | | One user | `get_profile`, `get_profile_by_external_id`, `get_activity_feed`, `get_activity_heatmap`, `get_profile_sessions`, `get_profile_stats` | Look a profile up by its Pug id or by the `external_id` your application assigned, then read that user's activity feed, daily heatmap, sessions and stats | | Dashboards | `list_dashboards`, `get_dashboard`, `upsert_dashboard` | List dashboards and read one with its tiles, then create a dashboard or edit one: rename it, change its time range, and add, change or remove tiles | | Compliance | `get_deletion_request` | Report the status of an erasure request someone already submitted | `upsert_dashboard` is the only tool that writes. An edit needs the dashboard's `update_time`, from `get_dashboard` or the last `upsert_dashboard`, and fails rather than overwrite a change made since. Tiles the call leaves out stay as they are, and a tile goes only when the call lists it for removal. It can't delete or share a dashboard, or edit one that has a share link on. Dashboards can't show segmentation insights or session metrics, markdown tiles can't contain images, and a dashboard holds at most 100 tiles. `upsert_dashboard` is marked destructive, so Claude asks you before each call unless you choose to always allow it. The `tools/list` request under **Any other client** above returns each tool's description and input schema. ## What is deliberately not exposed The tool surface is a curated subset, not everything the API can do: - **Profile erasure** (`Delete`, `DeleteDataSubject`): GDPR/DPDP erasure is irreversible, so it stays a human action through the [Profiles API](/api/profiles), never an LLM-callable tool. `get_deletion_request` only reads the status of a request someone already submitted. - **`SegmentUsers`**: the drill-down insight is still in progress; it is served as a Connect RPC but held off the tool surface until it lands. - **`List` (profiles)**: server-streaming, which MCP tools do not model. Use `explore_events` or a profile lookup instead. - **Everything under `sdk.*` and `dashboard.*`**: ingest, identity and management are out of scope, deleting and sharing dashboards included. The exposed set is pinned in the server: a generated tool with no policy entry, or a policy entry with no matching tool, fails startup rather than shipping a surprise tool. Renaming an RPC upstream breaks the build, not your agent. ## Limits and errors - **Two minutes per tool call.** A wide `query_insights` over a long window is the one that will hit it; narrow the time range or the breakdown. - **Time-range caps by granularity** apply exactly as they do on the [Insights API](/api/insights): the same handler enforces them. - **Errors are Connect errors.** A rejected argument comes back as `invalid_argument` naming the field, an unknown profile as `not_found`, a project the credential can't read as `unauthenticated`, a viewer's dashboard edit as `permission_denied`, and a stale edit or one to a dashboard with a share link on as `failed_precondition`. See the [error model](/api#error-model). - **A failed tool returns the whole error as JSON**: `code`, `message` and the `details` array. The correlation id is in there, as a `google.rpc.RequestInfo`; quote it in a support request. ## Self-hosting `/mcp` is mounted on every Pug deployment and takes private keys with no configuration, on the same host and port as the rest of the API (`3000` by default, see [Configuration](/self-hosting/configuration)). Signing in stays off until you set `PUG_API_BASE_URL` to the API's public origin, such as `https://api.example.com`. It takes no path, because the sign-in metadata sits at the root of that host. `PUG_DASHBOARD_BASE_URL` must then be https too, since the dashboard serves the page where people approve a connection, or the server won't start. Either may be http on `localhost` or `127.0.0.1`. Claude's apps and ChatGPT reach your server from Anthropic's and OpenAI's infrastructure, so they need a public URL; Claude Code connects from your own machine, so `PUG_API_BASE_URL=http://localhost:3000` is enough to try sign-in locally. Pug fetches each client's metadata document over outbound HTTPS, ignoring any proxy, so signing in needs direct outbound access. `get_dashboard` and `upsert_dashboard` link each dashboard under `PUG_DASHBOARD_BASE_URL`, and return no link while it is unset. Behind a reverse proxy, pass `/mcp` through, plus `/oauth/token` and `/.well-known/oauth-*` once sign-in is on, and keep the `Authorization` header across the hop. A proxy that strips it is the usual cause of a server that connects from `localhost` but answers `401` in production. ## Further reading - [Insights API](/api/insights): the query spec behind `query_insights` - [Profiles API](/api/profiles): profile lookups and erasure over HTTP - [Authentication](/get-started/authentication): issuing and revoking private keys - [API overview](/api): headers, base URLs and the Connect error model # Auto-properties > Every $-prefixed property the SDKs and server attach automatically, per platform. Source: https://docs.pug.sh/reference/auto-properties/ | Markdown: https://docs.pug.sh/reference/auto-properties/index.md Auto-properties are `$`-prefixed properties Pug attaches to events automatically: the SDK sets its own before an event leaves the device, and the server adds more at ingestion. You don't need to set any yourself; what happens to a server-set one you send depends on the property (see [Server-set properties](#server-set-properties)). **The `$` prefix is reserved.** `autoProperties` keys must start with `$` and `customProperties` keys must not; a request that breaks either rule fails whole with `invalid_argument` (see [Events API](/api/events#validation-summary)). ## SDK-set properties: Web Set by `@pug-sh/browser` on every event, all as strings. | Property | Type | Description | Example | |---|---|---|---| | `$projectId` | string | Project ID passed to `init()` | `d47k2sl3gmq7c1tvb6e0` | | `$platform` | string | Always `web` | `web` | | `$url` | string | Current page URL (`window.location.href`), with [`redactUrlParams`](/sdks/web#redacting-pii) applied | `https://app.example.com/pricing` | | `$referrer` | string | `document.referrer`, redacted the same way; an empty string when there is none | `https://google.com` | | `$pageTitle` | string | Page title (`document.title`), on `page_view` only | `Pricing - Acme` | | `$locale` | string | Browser locale (`navigator.language`) | `en-US` | | `$screenWidth` | string | Screen width in CSS pixels (`window.screen.width`) | `1920` | | `$screenHeight` | string | Screen height in CSS pixels (`window.screen.height`) | `1080` | | `$sdkVersion` | string | Web SDK version | `0.1.8` | | `$browser` | string | Browser name, from `navigator.userAgentData` brands | `Google Chrome` | | `$browserVersion` | string | Browser major version | `124` | | `$os` | string | Operating system (`navigator.userAgentData.platform`) | `macOS` | | `$osVersion` | string | OS version (high-entropy hint) | `14.4.1` | | `$device` | string | Device model (high-entropy hint); desktops report none | `Pixel 8` | | `$mobile` | string | `"true"` or `"false"`: whether the browser reports a mobile device | `"false"` | | `$utmSource` | string | `utm_source` query parameter | `google` | | `$utmMedium` | string | `utm_medium` query parameter | `cpc` | | `$utmCampaign` | string | `utm_campaign` query parameter | `spring_sale` | | `$utmContent` | string | `utm_content` query parameter | `banner_a` | | `$utmTerm` | string | `utm_term` query parameter, decoded | `analytics software` | `$browser`, `$browserVersion`, `$os`, `$osVersion`, `$device` and `$mobile` come from the [User-Agent Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API), which only Chromium browsers expose; other browsers get them from the [server](#user-agent-enrichment-server-side-fallback). `$osVersion` and `$device` are read asynchronously after `init()`, so events built before that read resolves, such as the first `page_view`, lack them. UTM parameters are read from `window.location.search` for each event, and each is sent only when present. [`beforeSend`](/sdks/web#redacting-pii) can change or remove any of these except `$projectId`, `$platform` and `$sdkVersion`. See [Auto-tracking](/sdks/web#auto-tracking) for which events the SDK sends itself. ## SDK-set properties: Android Set by `sh.pug:android` on every event. Device and app details are read when `Pug.init` runs, and locale, time zone, display and network type for each event. A value the device doesn't report is left out. | Property | Type | Description | Example | |---|---|---|---| | `$projectId` | string | Project ID passed to `Pug.init` | `d47k2sl3gmq7c1tvb6e0` | | `$sdkVersion` | string | Android SDK version | `0.2.1` | | `$platform` | string | Always `android` | `android` | | `$os` | string | Always `Android` | `Android` | | `$osVersion` | string | Android release (`Build.VERSION.RELEASE`) | `15` | | `$device` | string | Device model (`Build.MODEL`) | `Pixel 9` | | `$deviceModel` | string | Same value as `$device` | `Pixel 9` | | `$deviceManufacturer` | string | Manufacturer (`Build.MANUFACTURER`) | `Google` | | `$deviceType` | string | `tv` on Android TV, else `mobile` | `mobile` | | `$mobile` | boolean | `true` unless a TV or a tablet (smallest width of 600 dp or more) | `true` | | `$screenWidth` | integer | Display width in dp, in the current orientation | `412` | | `$screenHeight` | integer | Display height in dp, in the current orientation | `915` | | `$screenScale` | number | Display density | `2.625` | | `$locale` | string | Device locale as a BCP 47 language tag | `en-US` | | `$timezone` | string | IANA timezone identifier | `Europe/Berlin` | | `$appName` | string | App label from the manifest | `Acme` | | `$appPackage` | string | Package name | `com.example.acme` | | `$appVersion` | string | `versionName` | `1.4.2` | | `$appBuild` | string | `versionCode` | `42` | | `$networkType` | string | Active connectivity type, only when your app holds `ACCESS_NETWORK_STATE`, which the SDK doesn't declare | `wifi`, `mobile`, `ethernet`, `vpn`, `bluetooth`, `other`, `none`, `unknown` | | `$url` | string | Current screen: the resumed activity's simple class name, or the name passed to `Pug.screen` | `CheckoutActivity` | | `$referrer` | string | Previous screen | `CartActivity` | The device name is never collected. See [Auto-tracking](/sdks/android#auto-tracking) for the events that move `$url` and `$referrer`. ## SDK-set properties: iOS Set by the iOS SDK (`github.com/pug-sh/sdk-ios`) on every event. Locale, time zone and network type are read for each event; the OS version and the screen each time the app comes to the foreground or a screen appears, and with each SDK call made on the main thread; the rest once per launch. A value the device doesn't report is left out. | Property | Type | Description | Example | |---|---|---|---| | `$projectId` | string | Project ID passed to `Pug.initialize` | `d47k2sl3gmq7c1tvb6e0` | | `$sdkVersion` | string | iOS SDK version | `0.1.0` | | `$platform` | string | Always `ios` | `ios` | | `$os` | string | Always `iOS`, on an iPad too | `iOS` | | `$osVersion` | string | iOS or iPadOS version | `26.1` | | `$device` | string | The model's marketing name, or its hardware identifier for a model the SDK doesn't know yet; on a simulator, the simulated model | `iPhone 16 Pro` | | `$deviceModel` | string | Same value as `$device` | `iPhone 16 Pro` | | `$deviceManufacturer` | string | Always `Apple` | `Apple` | | `$deviceType` | string | `desktop` for an iPhone or iPad app running on a Mac, else `mobile` | `mobile` | | `$mobile` | boolean | `true` on an iPhone; `false` on an iPad and on a Mac | `true` | | `$screenWidth` | integer | Screen width in points, in the current orientation | `402` | | `$screenHeight` | integer | Screen height in points, in the current orientation | `874` | | `$screenScale` | number | Screen scale | `3.0` | | `$locale` | string | The user's preferred language and region as a BCP 47 language tag | `en-US` | | `$timezone` | string | IANA timezone identifier | `Europe/Berlin` | | `$appName` | string | `CFBundleDisplayName`, else `CFBundleName` | `Acme` | | `$appPackage` | string | Bundle identifier | `com.example.acme` | | `$appVersion` | string | `CFBundleShortVersionString` | `1.4.2` | | `$appBuild` | string | `CFBundleVersion` | `42` | | `$networkType` | string | Active connectivity type; reading it needs no permission | `wifi`, `mobile`, `ethernet`, `other`, `none`, `unknown` | | `$url` | string | Current screen: a view controller's type name, or the name passed to `pugScreen` or `Pug.screen` | `CheckoutViewController` | | `$referrer` | string | Previous screen | `CartViewController` | The device name is never collected. See [Auto-tracking](/sdks/ios#auto-tracking) for the events that move `$url` and `$referrer`. ## SDK-set properties: Flutter Set by `pug_flutter` on every event. App, device and network details, the IANA time zone and the OS on web are read once, at `Pug.init`; the rest for each event. With a custom `autoPropertyProvider`, the SDK sets only `$projectId`, `$sdkVersion`, `$url` and `$referrer`, and the provider supplies the rest, `$platform` included. ### Core | Property | Type | Description | Example | |---|---|---|---| | `$projectId` | string | Project ID passed to `Pug.init` | `d47k2sl3gmq7c1tvb6e0` | | `$sdkVersion` | string | Flutter SDK version | `0.1.1` | | `$platform` | string | `web` on Flutter web; otherwise the **lowercase** operating system: `android`, `ios`, `macos`, `linux`, `windows`, `fuchsia`, with anything else passed through lowercased ([changed in 0.0.3](#casing-differences-between-sdks)) | `ios` | | `$deviceType` | string | Form factor: `tv`, `mobile` or `desktop`. Omitted on web and on any target it can't classify | `mobile` | | `$os` | string | `Platform.operatingSystem`, equal to `$platform`. On web, the Client Hints platform, Chromium only | `android` | | `$osVersion` | string | The OS release on Android and iOS; on desktop, or when that's missing, Dart's free-form `Platform.operatingSystemVersion`. On web, the Client Hints version, Chromium only | `14` | | `$locale` | string | Device locale as a BCP 47 language tag | `en-US` | | `$timezone` | string | IANA timezone identifier from `flutter_timezone`, else `DateTime.now().timeZoneName`'s abbreviation | `America/New_York` | | `$url` | string | Current route name, once a [`PugRouteObserver`](/sdks/flutter#auto-tracking) is wired | `/checkout` | | `$referrer` | string | Previous route name, set alongside `$url` | `/cart` | ### Screen | Property | Type | Description | Example | |---|---|---|---| | `$screenWidth` | integer | Logical width of the app's view in dp; on desktop and web, the window rather than the screen | `390` | | `$screenHeight` | integer | Logical height of the same view | `844` | | `$screenScale` | number | Device pixel ratio | `3.0` | ### App | Property | Type | Description | Example | |---|---|---|---| | `$appName` | string | App name from `PackageInfo` | `Acme App` | | `$appPackage` | string | Bundle / package identifier | `com.example.acme` | | `$appVersion` | string | App version string | `1.4.2` | | `$appBuild` | string | App build number | `42` | ### Device (populated per platform) | Property | Platform | Description | Example | |---|---|---|---| | `$deviceManufacturer` | Android, iOS, macOS, Linux | The manufacturer on Android, `Apple` on iOS and macOS, and the distribution's full name on Linux | `Samsung`, `Apple`, `Ubuntu 24.04.1 LTS` | | `$deviceModel` | Android, iOS, macOS, Linux, Windows | The model on Android. On iOS and macOS the marketing name, falling back to `UIDevice.model` (`iPhone`) on iOS and the model identifier on macOS; the distribution's name on Linux; the Windows product name | `iPhone 15 Pro`, `MacBookPro18,3`, `Windows 11 Pro` | The user-assigned device name is never collected. For phone versus desktop, use `$deviceType` rather than parsing `$deviceModel`. ### Network | Property | Type | Description | Example | |---|---|---|---| | `$networkType` | string | Connectivity type when `Pug.init` ran | `wifi`, `mobile`, `ethernet`, `vpn`, `bluetooth`, `other`, `none`, `unknown` | See [Auto-tracking](/sdks/flutter#auto-tracking) for the navigation events a `PugRouteObserver` sends: `screen_view` on mobile, `page_view` on web. ## SDK-set properties: Node Set by `@pug-sh/node` on every event. | Property | Type | Description | Example | |---|---|---|---| | `$lib` | string | Library identifier: always `pug-node` | `pug-node` | | `$sdkVersion` | string | Node SDK version | `0.1.0` | | `$platform` | string | Always `server` | `server` | The only other auto-properties it sets are the [geo keys](#geo-enrichment-cloudflare) that [`track()`'s `location` option](/sdks/node#visitor-location) (**0.0.6+**) renders, and `props` become custom properties, so pass anything else there. It sets no `$projectId`. Its requests use a private key, so the server adds no geo or user agent to its events ([Server-set properties](#server-set-properties)): without `location` they land in the empty bucket of a `$country` or `$browser` breakdown. To set `$browser` and the like on a server event, send it over the [HTTP API](/api/events). ## SDK-set properties: Go Set by `github.com/pug-sh/sdk-go` on every event. | Property | Type | Description | Example | |---|---|---|---| | `$lib` | string | Library identifier: always `pug-go` | `pug-go` | | `$sdkVersion` | string | Go SDK version | `0.0.1` | | `$platform` | string | Always `server` | `server` | As with Node, the only other auto-properties it sets are the geo keys [`pug.WithLocation`](/sdks/go#visitor-location) renders, it sets no `$projectId`, and the server adds no geo or user agent to its events. ## SDK-set properties: Ruby Set by `pug-sh` on every event. | Property | Type | Description | Example | |---|---|---|---| | `$lib` | string | Library identifier: always `pug-ruby` | `pug-ruby` | | `$sdkVersion` | string | Ruby SDK version | `0.1.1` | | `$platform` | string | Always `server` | `server` | As with Node, the only other auto-properties it sets are the geo keys [`track`'s `location` option](/sdks/ruby#visitor-location) renders, it sets no `$projectId`, and the server adds no geo or user agent to its events. ## Casing differences between SDKs Every SDK sets `$platform` and `$sdkVersion`, and the server never sets `$platform`. `$platform` values are lowercase in every SDK and stored as sent, so a breakdown on it groups traffic by platform across SDKs: Flutter shares `android`, `ios` and `web` with the Android, iOS and Web SDKs, and the three server SDKs all send `server`, which `$lib` tells apart. Auto-property keys are camelCase, except the server-set `$bot_reason`, `$bot_score` and `$verified_bot`. > **pug\_flutter changed these values in 0.0.3** > > Before 0.0.3 the Flutter SDK sent `iOS` and `macOS` where every other Pug SDK sends `ios` and `macos`, and Flutter **web** reported the browser's host OS instead of `web`. Dashboards, filters and saved segments that match the old casing, or treat Flutter web traffic as iOS, need updating. | SDK | `$platform` value | Example | |---|---|---| | `@pug-sh/browser` | always `web` | `web` | | `sh.pug:android` | always `android` | `android` | | `github.com/pug-sh/sdk-ios` | always `ios` | `ios` | | `pug_flutter` | `web` on Flutter web, else the lowercase OS | `android`, `ios`, `macos` | | `@pug-sh/node` | always `server` | `server` | | `github.com/pug-sh/sdk-go` | always `server` | `server` | | `pug-sh` | always `server` | `server` | The Web, Android, iOS and Flutter SDKs name shared concepts as below. **"not set"** means the SDK doesn't send the property though its platform has the concept; **"not applicable"** means the platform doesn't. Node, Go and Ruby are left out: they set only `$lib`, `$sdkVersion`, `$platform` and the geo keys from `location`. | Concept | Web SDK property | Android SDK property | iOS SDK property | Flutter SDK property | |---|---|---|---|---| | URL / screen name | `$url` (full URL) | `$url` (current activity or `Pug.screen` name) | `$url` (current view controller, `pugScreen` or `Pug.screen` name) | `$url` (current route name; set when `PugRouteObserver` is wired) | | Page / screen title | `$pageTitle` (on `page_view` only) | not set | not set | not set | | Referrer | `$referrer` | `$referrer` (previous screen) | `$referrer` (previous screen) | `$referrer` (previous route name) | | Platform | `$platform` (always `web`) + `$os` (Client Hints platform) | `$platform` (always `android`) + `$os` (always `Android`) | `$platform` (always `ios`) + `$os` (always `iOS`) | `$platform` (`web`, or the lowercase OS) + `$os` (equals `$platform` natively) | | OS version | `$osVersion` | `$osVersion` | `$osVersion` | `$osVersion` | | Browser | `$browser` | not applicable | not applicable | not set (on web, the [server](#user-agent-enrichment-server-side-fallback) sets it) | | Browser version | `$browserVersion` | not applicable | not applicable | not set (on web, the server sets it) | | Device model | `$device` | `$device` and `$deviceModel` (same value) | `$device` and `$deviceModel` (same value) | `$deviceModel` | | Form factor | `$mobile` (string `"true"`/`"false"`) | `$deviceType` (`tv` or `mobile`) + `$mobile` (boolean) | `$deviceType` (`mobile` or `desktop`) + `$mobile` (boolean) | `$deviceType` (`tv`, `mobile` or `desktop`; omitted on web) | | Screen width | `$screenWidth` (string; the screen) | `$screenWidth` (integer) | `$screenWidth` (integer, points) | `$screenWidth` (integer; the window on desktop and web) | | Screen height | `$screenHeight` (string) | `$screenHeight` (integer) | `$screenHeight` (integer, points) | `$screenHeight` (integer) | | Locale | `$locale` | `$locale` | `$locale` | `$locale` | | Timezone | not set client-side | `$timezone` | `$timezone` | `$timezone` | | UTM source | `$utmSource` | not set | not set | not set | | UTM medium | `$utmMedium` | not set | not set | not set | | UTM campaign | `$utmCampaign` | not set | not set | not set | | UTM term | `$utmTerm` | not set | not set | not set | | UTM content | `$utmContent` | not set | not set | not set | | App info | not applicable | `$appName`, `$appPackage`, `$appVersion`, `$appBuild` | `$appName`, `$appPackage`, `$appVersion`, `$appBuild` | `$appName`, `$appPackage`, `$appVersion`, `$appBuild` | | Network type | not set | `$networkType` (with `ACCESS_NETWORK_STATE`) | `$networkType` | `$networkType` (at `Pug.init`) | The server stores `$mobile` as a boolean whichever form arrives. Flutter's campaign capture, which set the `$utm*` properties and the click IDs `$gclid`, `$fbclid`, `$msclkid` and `$ttclid`, was removed in [0.0.5](/sdks/flutter#v005), and no SDK sends click IDs. ## Server-set properties The ingestion server adds these during `BatchCreate`. Geo and user-agent properties are derived only on public-key requests: on a private-key request the connection is your backend, so the server derives neither and keeps those the event carries. `$ip` is stripped from every event and never stored. Six keys are server-only, and any value a client sends for them is dropped: `$bot` and `$bot_reason` ([bot tagging](/api/insights#bot-traffic-is-excluded)), `$bot_score` and `$verified_bot` ([below](#bot-signals-cloudflare)), and `$channel` and `$referrerDomain` (below). On every request the server also derives these from the event's own properties. `$channel` and `$referrerDomain` are always its own, `$locale` is rewritten in place, and each of the others is set only when the event doesn't carry it. | Property | Derived from | Example | |---|---|---| | `$pathname` | The path of `$url`, decoded; `/` when empty | `/pricing` | | `$hostname` | The host of `$url`, lowercased | `app.example.com` | | `$referrerDomain` | The host of `$referrer`, lowercased, minus one leading `www.`; empty for a self-referral (the host of `$url`) or a sign-in host such as `accounts.google.com` | `google.com` | | `$channel` | The marketing channel, from the UTMs and `$referrerDomain` (below) | `Organic Search` | | `$utmSource`, `$utmMedium`, `$utmCampaign`, `$utmTerm`, `$utmContent` | The matching `utm_*` parameter of `$url` | `google` | | `$screenSize` | `$screenWidth` and `$screenHeight` as `WIDTHxHEIGHT`, when both are positive integers | `1920x1080` | | `$locale` | The event's `$locale`, re-cased with `_` read as `-`: `en_us` becomes `en-US` | `en-US` | `$pathname`, `$hostname`, `$channel` and the UTMs need `$url` to be an `http` or `https` URL with a host, such as the Web SDK's; Android's, iOS's and Flutter's `$url` is a screen or route name, so their events get none of them. `$channel` takes the first value that applies: `Paid Search`, `Paid Social` or `Paid Video` for a paid `utm_medium` (containing `cp`, exactly `ppc` or `retargeting`, or starting with `paid`) whose source or referrer is a search engine, social network or video site; `Display` for a `display`, `banner`, `expandable`, `interstitial` or `cpm` medium; `Paid Other` for any other paid medium; `Organic Search`, `Organic Social` or `Organic Video` for a search, social or video source or referrer, or an `organic`, social or `video` medium; `Email` for an email or newsletter source or medium, or a webmail referrer; `Affiliate` for an `affiliate` medium; `Referral` for any other referrer; `Unassigned` for UTMs that match none of these, or a referrer with no host; and `Direct` otherwise. ### Geo enrichment (Cloudflare) On a public-key request the server reads these from Cloudflare's headers: `$country` from `CF-IPCountry`, which the zone's IP Geolocation setting adds, and the rest from the **"Add visitor location headers"** Managed Transform. Each key the headers supply replaces the event's own, the `$timezone` Android, iOS and Flutter send included, and a key they don't supply keeps whatever the event sent. Cloudflare's `XX` (unknown) and `T1` (Tor) countries and `Unknown` regions and cities are left out. Without Cloudflare, the server derives none, and an event has only the geo properties it sends. On a **private-key** request the server keeps the location the event carries, or stores none. Nothing is merged, so your `$city` is never paired with the edge's `$country`, and a `$country` you send is stored verbatim: use ISO 3166-1 alpha-2, since `USA` or `us` becomes its own breakdown value and won't render on the map. From the server SDKs, `track`'s `location` option ([Node](/sdks/node#visitor-location), [Ruby](/sdks/ruby#visitor-location)) or [`pug.WithLocation`](/sdks/go#visitor-location) in Go writes these keys, after checking the country code and coordinate ranges. | Property | Description | Example | |---|---|---| | `$continent` | Continent code | `NA` | | `$country` | ISO 3166-1 alpha-2 country code | `US` | | `$region` | Region or state name | `California` | | `$city` | City name | `San Francisco` | | `$postalCode` | Postal / ZIP code | `94107` | | `$metroCode` | Metro code (US DMA) | `807` | | `$latitude` | Latitude (float64) | `37.7749` | | `$longitude` | Longitude (float64) | `-122.4194` | | `$timezone` | IANA timezone name from Cloudflare | `America/Los_Angeles` | ### User-agent enrichment (server-side fallback) On a public-key request the server parses the `User-Agent` header and sets each of these the event doesn't already carry, for every client SDK. Browsers without Client Hints (Firefox, Safari and every iOS browser) get them from here, and on Chromium it fills what Client Hints leave out, such as `$device` on a Mac. Android's, iOS's and Flutter's own User-Agents yield nothing, Flutter web events get the browser's, and a Flutter app sending through `CupertinoClient` or `CronetClient` gets values parsed from that client, with its app name, or `Android`, as `$browser`. To set these on a server event, send them over the [HTTP API](/api/events). | Property | Description | Example | |---|---|---| | `$browser` | Browser name, spelled as the Web SDK spells it (`Google Chrome`, `Microsoft Edge`) | `Firefox` | | `$browserVersion` | Browser major version | `126` | | `$os` | Operating system, spelled as the Web SDK spells it (`macOS`, and `Linux` for any distribution) | `iOS` | | `$osVersion` | OS version; omitted when the User-Agent freezes it (macOS 10.15, Windows 10 and 11, Chrome's reduced Android) | `17.5.1` | | `$device` | Device family: `Mac` for any Mac, none for other desktops or Chrome's reduced Android | `iPhone` | | `$mobile` | `true` for an iPhone or iPod, or Android with `Mobile` in the User-Agent; else `false` | `true` | ### Bot signals (Cloudflare) The server sets `$bot_score` and `$verified_bot` from Cloudflare's `CF-Bot-Score` and `CF-Verified-Bot` headers, on private-key requests too, where they describe your backend's connection. Without those headers, as in a self-hosted setup without Cloudflare, both are absent. | Property | Type | Description | Example | |---|---|---|---| | `$bot_score` | integer | Cloudflare bot score (0-99; lower = more likely bot) | `2` | | `$verified_bot` | boolean | `true` if Cloudflare identified a known good bot | `false` | ## Using auto-properties in queries Filter and break down on an auto-property in Insights as on a custom property, by its full key, `$` included. **Breakdown by country:** - **Events** - page_view - **Breakdown** - $country - **Aggregation** - Unique users **Filter to Chrome users only:** - **Events** - purchase - **Filter** - $browser = "Google Chrome" - **Aggregation** - Sum of amount **UTM campaign performance:** - **Events** - signup - **Breakdown** - $utmCampaign - **Aggregation** - Total events - **Filter** - $utmSource = "google" **Only traffic Cloudflare scored as likely human:** - **Events** - page_view - **Filter** - $bot_score > 50 - **Aggregation** - Unique users An event without a `$bot_score` doesn't match `>`, so this also drops all traffic Cloudflare didn't score. Insights already leaves out events tagged [`$bot`](/api/insights#bot-traffic-is-excluded). ## Related - [Events API](/api/events): validation rules, including the `$` rule for property keys - Auto-tracking: what each SDK captures automatically ([Web](/sdks/web#auto-tracking) interactions; [Android](/sdks/android#auto-tracking) activities, app lifecycle and installs; [iOS](/sdks/ios#auto-tracking) view controllers, named SwiftUI screens, app lifecycle and installs; [Flutter](/sdks/flutter#auto-tracking) navigation, app lifecycle and installs) # Glossary > Quick definitions for every term used across the Pug docs, SDKs and API. Source: https://docs.pug.sh/reference/glossary/ | Markdown: https://docs.pug.sh/reference/glossary/index.md Quick reference for terms used across the Pug docs, SDKs, and API. Definitions are kept concise - follow the linked pages for full explanations. | Term | Definition | |------|------------| | **Organization** | Top-level tenant. Owns members, billing, and email configuration. Projects belong to an organization. See [Core concepts](/get-started/concepts). | | **Project** | Isolated data boundary inside an organization. Owns events, profiles, insights, and API keys. All analytics queries are project-scoped. See [Core concepts](/get-started/concepts). | | **Public key** (`pub_...`) | Project-scoped write credential for client SDKs. Sent as `x-api-key`; lets you ingest events and identify users, but cannot read analytics. Safe to ship in a browser bundle or mobile binary. See [Authentication](/get-started/authentication). | | **Private key** (`prv_...`) | Project-scoped read/write credential for trusted server-side code. Sent as `x-api-key`; reaches `shared.*` services (insights, profiles). Never ship in client code. See [Authentication](/get-started/authentication). | | **Event** | A named occurrence with custom properties and a timestamp: the atomic unit of analytics data. The event name is its `kind`, made of ASCII letters, digits, `_`, `.` and `-`. See [Events API](/api/events). | | **Property** | A custom key/value pair attached to an event (string, integer, double, boolean, or timestamp). Keys must not start with `$`. Sent in `customProperties` on each event. | | **Auto-property** | A `$`-prefixed property attached automatically by the SDK or server - for example `$url`, `$browser`, `$country`. `$`-prefixed keys are reserved and cannot be set as custom properties. See [Auto-properties](/reference/auto-properties). | | **Well-known event** | A standard event name (e.g. `page_view`, `purchase`) that carries a typed schema. Custom event names not in the registry are also accepted without schema validation. See [Well-known events](/reference/well-known-events). | | **Profile** | A persistent record representing one user (identified or anonymous) with an accumulated set of traits (properties). Created or updated by `identify()`. See [Profiles API](/api/profiles). | | **Anonymous ID** | An SDK-generated identifier in the form `anon-...`, created when a visitor first arrives. Events are attributed to this ID until the user is identified. | | **External ID** | Your stable user identifier (e.g. a database user ID), passed as `external_id` to `Identify`. Use a value that does not change - not an email address. | | **Distinct ID** | The identifier an event is attributed to: the anonymous ID before `identify()` is called, the external ID after. Stored as `distinct_id` on every event. | | **Alias** | The association of multiple identifiers with one profile: most commonly the anonymous-to-identified merge on the first `identify()` call (there is no separate `alias()` method). See [Profiles API](/api/profiles). | | **Session** | A window of activity grouped by the SDK. A new session starts after the idle timeout (default 30 min) or the maximum session duration (default 24 h). The session ID is synced across browser tabs. See [Core concepts](/get-started/concepts). | | **Insight** | A server-side analytics query specification: event selection, filters, time range, granularity, aggregation, and optional breakdowns. The same spec powers dashboard charts and the `InsightsService` API. Types: `TRENDS`, `SEGMENTATION`, `FUNNEL`, `RETENTION`, `USER_FLOW`, `TOP_K`. See [Insights API](/api/insights). | | **Connect RPC** | The API transport protocol used by all Pug services. Supports the Connect, gRPC, and gRPC-Web protocols over HTTP/1.1 and HTTP/2. Request path format: `/./`. See [Authentication](/get-started/authentication) and the [API overview](/api). | | **Batch** | A single `BatchCreate` call carrying up to 1 000 events. All event ingestion goes through this endpoint - there is no single-event API. See [Events API](/api/events). | | **Tracking consent** | The Web SDK's three-state capture gate - `granted`, `cookieless` (events flow, nothing stored on the device), or `denied`. Defaults to `cookieless`. See [Tracking consent](/sdks/web#tracking-consent). | | **Cookieless ID** | The `cookieless-`-prefixed distinct ID ingest derives for events sent without identity - an HMAC over project, IP and user agent, keyed by a salt that rotates daily. Never stored on the device, never client-settable, and excluded from user-counting metrics by default. See [Cookieless events](/api/events#cookieless-events). | ## Further reading - [Core concepts](/get-started/concepts): detailed explanations of key terms - [Authentication](/get-started/authentication): keys, headers, and error codes - [Profiles API](/api/profiles): identity lifecycle, anonymous -> identified merge - [Insights API](/api/insights): query types and spec format - [Auto-properties](/reference/auto-properties): full `$`-prefixed property catalog # RPC services > Complete index of Connect RPC services by package family, with the auth mode each one requires. Source: https://docs.pug.sh/reference/rpc-services/ | Markdown: https://docs.pug.sh/reference/rpc-services/index.md Complete index of Connect RPC services in the Pug API, grouped by package family. Each family shares an auth mode; see the [API overview](/api) for request headers and the base URL. Endpoint pattern: `POST https://api.pugs.dev/{package}.{Service}/{Method}` ## `public.*`: no authentication Open endpoints. No API key or JWT required. | Package | Service | Purpose | |---------|---------|---------| | `public.auth.v1` | `AuthService` | Dashboard sign-in: email/password, magic link request and completion, OIDC providers and org SSO connections, and the email-first lookup (`DiscoverSignIn`) | | `public.dashboards.v1` | `SharedDashboardsService` | Read a publicly-shared dashboard (`Query`). Authorized by the unguessable **share token** in the request, not by a credential | ## `sdk.*`: SDK key (`x-api-key`) Client-side write access. Safe to embed in browsers and mobile apps. Use your project's **public** API key. | Package | Service | Purpose | Docs | |---------|---------|---------|------| | `sdk.events.v1` | `EventsService` | Ingest event batches (`BatchCreate`) | [Events API](/api/events) | | `sdk.profiles.v1` | `ProfilesSDKService` | Create or update profiles, merge anonymous IDs (`Identify`, `BatchIdentify`) | [Profiles API](/api/profiles) | | `sdk.devices.v1` | `DevicesService` | Push-notification device registration (`Subscribe`, `UpdateStatus`, `UpdateToken`) | _out of scope for these docs_ | ## `shared.*`: private API key or JWT (`x-api-key: prv_...` or `Authorization: Bearer`) Server-side or trusted integrations. Accepts either a **private** API key or a dashboard JWT. Every method of `shared.insights`, `shared.activity`, `shared.profiles`, `shared.projects` and `shared.dashboards` is also exposed as an [MCP tool](/mcp) at `POST /mcp`, except `SegmentUsers`, profile erasure (`Delete`, `DeleteDataSubject`) and the streaming profiles `List`. The tools run the same handlers, reached by signing in to Pug or with a private key, never a JWT. | Package | Service | Purpose | Docs | |---------|---------|---------|------| | `shared.insights.v1` | `InsightsService` | Run analytics queries (`Query`, `SegmentUsers`, `GetFilterSchema`, `GetPropertyValues`) | [Insights API](/api/insights) | | `shared.profiles.v1` | `ProfilesService` | Read, list, and delete profiles (`Get`, `GetByExternalId`, `List`, `Delete`), plus GDPR/DPDP data-subject erasure (`DeleteDataSubject`, `GetDeletionRequest`) | [Profiles API](/api/profiles) | | `shared.activity.v1` | `ActivityService` | Per-profile activity feed, event explorer, heatmap, profile sessions, and profile stats | - | | `shared.projects.v1` | `ProjectsService` | The projects a credential reads (`List`) | - | | `shared.dashboards.v1` | `DashboardsService` | List and read dashboards, and create or edit one (`List`, `Get`, `Upsert`) | - | | `shared.campaigns.v1` | `CampaignService` | Push-campaign management (`BatchGet`, `Create`, `Get`, `Update`, `Delete`) | _out of scope for these docs_ | | `shared.delivery.v1` | `DeliveryService` | Push-delivery event recording (`RecordEvent`) | _out of scope for these docs_ | ## `dashboard.*`: JWT (`Authorization: Bearer`) Browser sessions for the Pug dashboard. Not intended for programmatic API access. Scoping headers (e.g. `x-project-id`) are described in [Authentication](/get-started/authentication). | Package | Service | Purpose | |---------|---------|---------| | `dashboard.orgs.v1` | `OrgsService` | Organization CRUD, member management, and [SSO & domains](/get-started/sso) (verified domains, their settings, SSO connections) | | `dashboard.projects.v1` | `ProjectsService` | Project CRUD and settings | | `dashboard.customers.v1` | `CustomersService` | Caller's own account (`GetMe`, `SetPassword`) | | `dashboard.dashboards.v1` | `DashboardsService` | Dashboard and tile management, dashboard query execution | | `dashboard.orgemailproviders.v1` | `OrgEmailProvidersService` | Organization email provider configuration (`Get`, `Set`, `Remove`, `SendTest`) | ## `common.*`: shared message types only These packages define reusable message and enum types imported by the service packages above. They do **not** define any RPC services. | Package | Contents | |---------|---------| | `common.v1` | `PropertyValue`, `TimeRange`, `TimeRangePreset`, filter types, filter schema types | | `common.events.v1` | Well-known event schemas (navigation, auth, commerce, media, and more) | ## `workers.*`: internal only These packages define NATS message envelopes used between internal backend workers. They are not Connect RPC services and are not client-facing. | Package | Contents | |---------|---------| | `workers.email.v1` | Email job message types (`OrgMemberInvitePayload`, `MagicLinkPayload`) | | `workers.profiles.v1` | Profile worker message types (`ProfileAliasMessage`, `ProfileUpsertMessage`) | | `workers.compliance.v1` | Data-subject erasure job (`EraseMessage`) - drives the compliance worker behind `DeleteDataSubject` | ## Further reading - [API overview](/api) - [MCP server](/mcp) - [Authentication](/get-started/authentication) - [Events API](/api/events) - [Profiles API](/api/profiles) - [Insights API](/api/insights) # Well-known events > The typed event catalog - standard event names that carry validated schemas and richer dashboards. Source: https://docs.pug.sh/reference/well-known-events/ | Markdown: https://docs.pug.sh/reference/well-known-events/index.md Well-known events are the predefined event names Pug recognizes, each with a typed property schema. The catalog holds **127 events across 19 families**, listed in full below. Every SDK type-checks them, but the call shape differs: | SDK | Call | Available | |-----|------|-----------| | **Web** | `track('purchase', { productId, amount })`: the name narrows the property type | 119 (events flagged for other platforms are excluded) | | **Android** | `Pug.track.purchase(productId = ..., amount = ...)` - a generated method per event, or an event class from Java | 118 (the web-only events and the five it tracks itself are excluded) | | **iOS** | `Pug.track.purchase(productId: ..., amount: ...)`: a generated method with labeled arguments per event | 118 (the web-only events and the five it tracks itself are excluded) | | **Flutter** | `Pug.track.purchase(productId: ..., amount: ...)` - a generated method per event | all 127 | | **Node** | `pug.track(distinctId, 'purchase', { ... })` | 114 | | **Go** | `client.TrackWellKnown(distinctID, &commoneventsv1.PurchaseProperties{...})` - a generated message per event - or `client.Track(distinctID, "purchase", ...)` | 114 | | **Ruby** | `pug.track(distinct_id, "purchase", product_id: ..., amount: ...)` | 114 | | **HTTP** | `kind: "purchase"` with wrapped `customProperties` | all 127 | Web, Android, iOS and Flutter check at compile time, so an unknown property or a wrong type is an error before the event leaves the device, and so does Go's `TrackWellKnown`. Node's and Ruby's `track` and Go's `Track` check when they're called, and a wrong type drops the event with a log naming the field. Over HTTP nothing checks them: the server stores the properties as sent. Custom event names, made of ASCII letters, digits, `_`, `.` and `-`, are accepted without schema validation. See [Events API](/api/events) for the validation error format. **Further reading:** [SDKs](/sdks) - sending custom and well-known events from each SDK ## Commerce Product browsing, cart, checkout, and purchase events. `price` is a single-item price; `amount` is a transaction total. `currency` is an uppercase ISO 4217 code (e.g. `USD`, `EUR`). Money fields use the major currency unit (e.g. dollars, not cents). | Event | Properties | Description | |---|---|---| | `product_viewed` | `product_id`\* string, `product_name` string, `category` string, `brand` string, `sku` string, `price` double, `currency` string | User viewed a product detail page | | `product_list_viewed` | `list_id`\* string, `list_name` string, `category` string, `item_count` int | User viewed a product listing, category, or search-results page | | `add_to_cart` | `product_id`\* string, `price` double, `currency` string, `cart_id` string, `quantity` int, `category` string, `brand` string, `sku` string | Item added to cart | | `remove_from_cart` | `product_id`\* string, `price` double, `currency` string, `cart_id` string, `quantity` int, `category` string, `brand` string, `sku` string | Item removed from cart | | `cart_viewed` | `cart_id` string, `item_count` int, `amount` double, `currency` string | User opened the cart | | `wishlist_added` | `product_id`\* string, `wishlist_id` string, `price` double, `currency` string | Item added to wishlist | | `wishlist_removed` | `product_id`\* string, `wishlist_id` string | Item removed from wishlist | | `coupon_applied` | `coupon_id`\* string, `coupon_code` string, `cart_id` string, `discount_amount` double, `currency` string | Coupon applied to cart | | `coupon_removed` | `coupon_id`\* string, `coupon_code` string, `cart_id` string, `reason` string | Coupon removed from cart | | `checkout_started` | `product_id` string, `amount` double, `currency` string, `cart_id` string, `checkout_id` string, `item_count` int | User initiated checkout | | `checkout_step_completed` | `checkout_id`\* string, `step`\* string, `step_index` int | A checkout step was completed | | `purchase` | `product_id` string, `amount` double, `currency` string, `order_id` string, `quantity` int, `category` string, `brand` string, `sku` string | Order completed (fires once per successful order after payment is confirmed) | | `order_refunded` | `order_id`\* string, `amount` double, `currency` string, `reason` string | Order was refunded | ## Authentication Sign-up, sign-in, sign-out, email verification, password reset, and MFA lifecycle. All auth events have no required properties beyond the event kind; common method values are `"email"`, `"google"`, `"github"`, `"totp"`, `"sms"`, `"webauthn"`, `"backup_codes"`. | Event | Properties | Description | |---|---|---| | `signup` | - | User completed registration | | `signin` | - | User signed in | | `signout` | - | User signed out | | `email_verified` | - | Email address was verified | | `password_reset_requested` | - | Password reset was requested | | `password_reset_completed` | - | Password reset flow completed | | `mfa_enabled` | `method` string | MFA was enabled | | `mfa_disabled` | `method` string | MFA was disabled | ## App Lifecycle Native mobile lifecycle events from the Android, iOS and Flutter SDKs; the Web SDK does not emit these. All three auto-emit `app_open`, `app_close`, `app_install` and `app_update` (plus `screen_view` for navigation); the rest are typed events you track manually. All three send `install_source` on `app_install` when the platform records one: see [Android](/sdks/android#auto-tracking), [iOS](/sdks/ios#auto-tracking) and [Flutter](/sdks/flutter#auto-tracking). | Event | Properties | Description | |---|---|---| | `app_open` | - | App launched or brought to the foreground | | `app_close` | - | App moved to the background or closed | | `app_install` | `app_version` string, `install_source` string | First launch after a fresh install | | `app_update` | `app_version`\* string, `previous_version` string | First launch after an app update | | `app_backgrounded` | - | App moved to the background | | `app_foregrounded` | - | App returned to the foreground | | `app_crashed` | `error_message` string, `error_type` string | Unhandled crash (also available on desktop) | | `screen_view` | `screen_name`\* string, `screen_class` string | A native screen was viewed: the mobile equivalent of `page_view` | ## App Usage Cross-platform - available in every SDK. | Event | Properties | Description | |---|---|---| | `feature_used` | `feature_id`\* string, `feature_name` string | A named feature was used | ## Billing Subscription, invoice, payment, trial, and refund lifecycle. `currency` is an uppercase ISO 4217 code; `amount` is the transaction total in the major currency unit. | Event | Properties | Description | |---|---|---| | `subscription_started` | `subscription_id`\* string, `plan_id` string, `amount` double, `currency` string | New subscription was created | | `subscription_changed` | `subscription_id`\* string, `previous_plan_id` string, `new_plan_id` string | Subscription plan was changed | | `subscription_canceled` | `subscription_id`\* string, `plan_id` string, `reason` string | Subscription was canceled | | `subscription_renewed` | `subscription_id`\* string, `plan_id` string, `amount` double, `currency` string | Subscription renewed | | `subscription_paused` | `subscription_id`\* string, `plan_id` string, `reason` string | Subscription was paused | | `subscription_resumed` | `subscription_id`\* string, `plan_id` string, `reason` string | Paused subscription was resumed | | `subscription_trial_will_end` | `subscription_id`\* string, `plan_id` string, `trial_id` string | Trial is nearing expiry (fires in advance, e.g. 3 days before) | | `trial_started` | `trial_id` string, `plan_id` string | Free trial started | | `trial_converted` | `trial_id` string, `subscription_id` string, `plan_id` string | Trial converted to paid subscription | | `invoice_paid` | `invoice_id`\* string, `subscription_id` string, `amount` double, `currency` string | Invoice was paid | | `invoice_failed` | `invoice_id`\* string, `subscription_id` string, `amount` double, `currency` string, `reason` string | Invoice payment failed | | `payment_succeeded` | `payment_id` string, `invoice_id` string, `subscription_id` string, `amount` double, `currency` string | Payment succeeded | | `payment_failed` | `payment_id` string, `invoice_id` string, `subscription_id` string, `amount` double, `currency` string, `reason` string | Payment failed | | `payment_method_added` | `payment_method_id` string, `payment_method_type` string | Payment method was added | | `payment_method_removed` | `payment_method_id` string, `payment_method_type` string | Payment method was removed | | `refund_failed` | `order_id`\* string, `refund_id` string, `amount` double, `currency` string, `reason` string | Refund attempt failed | ## Chat Conversation lifecycle, message delivery, membership, calls, attachments, and reactions. `conversation_id` is the durable chat identifier. `member_id` is the conversation-membership ID, not the SDK `distinct_id`. Common values: `conversation_type`: `"dm"`, `"group"`, `"channel"`, `"broadcast"`; `message_type`: `"text"`, `"image"`, `"video"`, `"audio"`, `"file"`, `"system"`. For `duration`-typed props (e.g. `mute_duration`), see [Notes](#notes). | Event | Properties | Description | |---|---|---| | `chat_created` | `conversation_id`\* string, `conversation_type` string, `participant_count` int | Conversation was created | | `chat_joined` | `conversation_id`\* string, `conversation_type` string | User joined a conversation | | `chat_left` | `conversation_id`\* string, `conversation_type` string, `reason` string | User left a conversation | | `chat_deleted` | `conversation_id`\* string, `conversation_type` string, `reason` string | Conversation was deleted | | `chat_archived` | `conversation_id`\* string, `conversation_type` string | Conversation was archived | | `chat_unarchived` | `conversation_id`\* string, `conversation_type` string | Conversation was unarchived | | `chat_member_added` | `conversation_id`\* string, `member_id`\* string, `role` string | Member was added to a conversation | | `chat_member_removed` | `conversation_id`\* string, `member_id`\* string, `reason` string | Member was removed from a conversation | | `chat_member_role_changed` | `conversation_id`\* string, `member_id`\* string, `previous_role` string, `new_role`\* string | Member's role was changed | | `chat_member_muted` | `conversation_id`\* string, `member_id`\* string, `mute_duration` duration | Member was muted (duration omitted for indefinite mutes) | | `chat_user_blocked` | `user_id`\* string | User was blocked (not conversation-scoped) | | `chat_message_sent` | `conversation_id`\* string, `message_id` string, `conversation_type` string, `message_type` string, `character_count` int, `attachment_count` int, `thread_id` string, `parent_message_id` string | Message was sent | | `chat_message_received` | `conversation_id`\* string, `message_id` string, `conversation_type` string, `message_type` string, `character_count` int, `attachment_count` int, `thread_id` string, `parent_message_id` string | Message was received | | `chat_message_failed` | `conversation_id`\* string, `message_id` string, `conversation_type` string, `reason`\* string, `thread_id` string | Message send failed | | `chat_message_read` | `conversation_id`\* string, `message_id` string, `conversation_type` string, `thread_id` string | Message was read | | `chat_message_deleted` | `conversation_id`\* string, `message_id` string, `conversation_type` string, `reason` string, `thread_id` string | Message was deleted | | `chat_message_edited` | `conversation_id`\* string, `message_id` string, `conversation_type` string, `thread_id` string | Message was edited | | `chat_message_pinned` | `conversation_id`\* string, `message_id` string, `conversation_type` string, `thread_id` string | Message was pinned | | `chat_message_unpinned` | `conversation_id`\* string, `message_id` string, `conversation_type` string, `thread_id` string | Message was unpinned | | `chat_typing_started` | `conversation_id`\* string, `conversation_type` string | User started typing (typer is the SDK `distinct_id`) | | `chat_typing_stopped` | `conversation_id`\* string, `conversation_type` string | User stopped typing | | `chat_attachment_uploaded` | `conversation_id`\* string, `message_id` string, `attachment_id`\* string, `attachment_type` string, `size_bytes` int64, `thread_id` string | Attachment uploaded in chat | | `chat_attachment_downloaded` | `conversation_id`\* string, `message_id` string, `attachment_id`\* string, `attachment_type` string, `size_bytes` int64, `thread_id` string | Attachment downloaded from chat | | `chat_call_started` | `conversation_id`\* string, `call_id`\* string, `call_type` string | Call was started | | `chat_call_joined` | `conversation_id`\* string, `call_id`\* string, `call_type` string | User joined a call | | `chat_call_left` | `conversation_id`\* string, `call_id`\* string, `call_type` string, `duration` duration | User left a call | | `chat_call_screen_shared` | `conversation_id`\* string, `call_id`\* string | Screen sharing started on a call | | `chat_call_recording_started` | `conversation_id`\* string, `call_id`\* string | Call recording started | | `chat_reaction_added` | `conversation_id`\* string, `message_id` string, `reaction`\* string, `thread_id` string | Reaction added to a message | | `chat_reaction_removed` | `conversation_id`\* string, `message_id` string, `reaction`\* string, `thread_id` string | Reaction removed from a message | ## Discovery / Search Search queries, results, recommendations, filters, and sorting. These events capture how users explore and find content. | Event | Properties | Description | |---|---|---| | `search` | `query`\* string | Search query submitted | | `search_result_clicked` | `query`\* string, `result_id`\* string, `index` int | User clicked a search result | | `recommendation_viewed` | `recommendation_id`\* string, `item_id` string, `source` string, `index` int | Recommendation impression | | `recommendation_clicked` | `recommendation_id`\* string, `item_id`\* string, `source` string, `index` int | User clicked a recommendation | | `filter_applied` | `key`\* string, `value` string | Filter was applied | | `sort_changed` | `key`\* string, `direction` string | Sort order was changed | ## Error Application errors and exceptions. `(PII)` marks fields handled under the project's scrubbing and data-residency rules (see [Notes](#notes)). | Event | Properties | Description | |---|---|---| | `error_occurred` | `error_code`\* string, `message` string (PII), `severity` string, `unhandled` bool, `stack` string (PII) | An error was caught or escaped to a global handler. Common `severity` values: `"info"`, `"warning"`, `"error"`, `"fatal"`. Set `unhandled: true` when the error escaped application code | ## File File upload, download, and export events. | Event | Properties | Description | |---|---|---| | `file_uploaded` | `file_id`\* string, `file_name` string (PII), `file_type` string, `size_bytes` int64 | File was uploaded | | `file_downloaded` | `file_id`\* string, `file_name` string (PII), `file_type` string, `size_bytes` int64 | File was downloaded | | `export_started` | `export_id`\* string, `export_type` string | Data export was initiated | | `export_completed` | `export_id`\* string, `export_type` string, `size_bytes` int64 | Data export completed | ## Form Form interaction start and submission. | Event | Properties | Description | |---|---|---| | `form_start` | `form_id`\* string, `form_name` string | User began filling in a form | | `form_submit` | `form_id`\* string, `form_name` string, `action` string | Form was submitted | ## Integration Third-party integration connect and disconnect. Common `integration_type` values: `"slack"`, `"github"`, `"linear"`, `"salesforce"`, `"hubspot"`, `"zapier"`, `"webhook"`. | Event | Properties | Description | |---|---|---| | `integration_connected` | `integration_id` string, `integration_type`\* string | Integration was connected | | `integration_disconnected` | `integration_id` string, `integration_type`\* string, `reason` string | Integration was disconnected | ## Invitation Workspace invitation sent and accepted. | Event | Properties | Description | |---|---|---| | `invite_sent` | `invite_id` string, `workspace_id` string, `inviter_id` string, `invitee_id` string, `invitee_email` string (PII), `role` string | Invitation was sent | | `invite_accepted` | `invite_id` string, `workspace_id` string, `inviter_id` string, `invitee_id` string, `invitee_email` string (PII), `role` string | Invitation was accepted | ## Media Video and audio playback events. `video_started` / `audio_started` fire on first play of a session; `video_play` / `audio_play` fire on resume from pause. `position`, `from_position`, and `to_position` are durations from the start of the media. | Event | Properties | Description | |---|---|---| | `video_started` | `video_id`\* string | Video playback started for the first time in this session | | `video_play` | `video_id`\* string, `position` duration | Video resumed from pause | | `video_pause` | `video_id`\* string, `position` duration | Video was paused | | `video_seeked` | `video_id`\* string, `from_position` duration, `to_position` duration | User seeked in video | | `video_completed` | `video_id`\* string | Video playback reached the end | | `audio_started` | `audio_id`\* string | Audio playback started for the first time in this session | | `audio_play` | `audio_id`\* string, `position` duration | Audio resumed from pause | | `audio_pause` | `audio_id`\* string, `position` duration | Audio was paused | | `audio_seeked` | `audio_id`\* string, `from_position` duration, `to_position` duration | User seeked in audio | | `audio_completed` | `audio_id`\* string | Audio playback reached the end | ## Navigation Page views, clicks, scroll depth, and frustration signals. Page URL, referrer, and UTM parameters are provided as [auto-properties](/reference/auto-properties) (`$url`, `$referrer`, `$utmSource`/`$utmMedium`/`$utmCampaign`/...) on every event, and the page title as `$pageTitle` on `page_view` only - none of them appear as typed properties here. On `click` and `dead_click`, `text` is the clicked element's [own text](/sdks/web#redacting-pii), not its whole subtree. | Event | Properties | Description | |---|---|---| | `page_view` | - | Web page navigation or SPA route change (auto-tracked by Web SDK) | | `click` | `class` string, `id` string, `tag` string, `text` string, `x` int, `y` int | Element click: Web only | | `rage_click` | `click_count` int (>=2), `element` string, `x` int, `y` int | Multiple rapid clicks on the same non-responsive target: Web only | | `dead_click` | `element` string, `text` string, `x` int, `y` int | Click with no observable response: Web only | | `scroll` | `percent` int (0-100), `scroll_y` int | Scroll depth milestone: Web and mobile | ## Notification Notification receipt, click, and dismissal. `notification_type` describes the delivery channel: `"push"`, `"email"`, `"in_app"`, `"sms"`. | Event | Properties | Description | |---|---|---| | `notification_received` | `campaign_id`\* string, `notification_type` string | Notification was received by the client | | `notification_clicked` | `campaign_id`\* string, `notification_type` string | User clicked a notification | | `notification_dismissed` | `campaign_id`\* string, `notification_type` string | User dismissed a notification | ## Social | Event | Properties | Description | |---|---|---| | `share` | - | User shared content | ## Support Feedback, NPS, surveys, support tickets, live chat, and help articles. | Event | Properties | Description | |---|---|---| | `feedback_submitted` | `feedback_id` string, `category` string, `comment` string (PII) | Feedback was submitted | | `nps_submitted` | `score` int (0-10), `comment` string (PII) | NPS score was submitted | | `survey_started` | `survey_id`\* string | Survey was started | | `survey_completed` | `survey_id`\* string, `question_count` int | Survey was completed | | `support_ticket_created` | `ticket_id`\* string, `category` string, `priority` string | Support ticket was opened | | `support_ticket_resolved` | `ticket_id`\* string, `resolution` string (PII) | Support ticket was resolved | | `support_chat_started` | `conversation_id`\* string, `topic` string (PII) | Support chat session started | | `help_article_viewed` | `article_id`\* string, `article_title` string, `category` string | Help article was viewed | ## Workspace Workspace creation, membership, role changes, and settings. | Event | Properties | Description | |---|---|---| | `workspace_created` | `workspace_id`\* string, `workspace_name` string | Workspace was created | | `workspace_joined` | `workspace_id`\* string, `role` string | User joined a workspace | | `workspace_deleted` | `workspace_id`\* string, `reason` string | Workspace was deleted | | `workspace_role_changed` | `workspace_id`\* string, `member_id`\* string, `previous_role` string, `new_role`\* string | Member's workspace role was changed | | `workspace_settings_updated` | `workspace_id`\* string, `setting`\* string | A workspace setting was changed | ## API API key management events. | Event | Properties | Description | |---|---|---| | `api_key_created` | `api_key_id` string, `name` string, `scope` string | API key was created | | `api_key_revoked` | `api_key_id` string, `name` string, `reason` string | API key was revoked | ## Notes **Required props** are marked with \*. The SDKs refuse an event missing one or holding a wrong type, as described at the top of this page; the API doesn't check. Optional props may be omitted. **PII-tagged props** are labelled `(PII)` above. Fields tagged PII in the schema are subject to the project's data-residency and scrubbing rules. **`duration` type**: the Android, iOS, Node, Go and Ruby SDKs send a duration property (e.g. `position`, `mute_duration`, `duration`) as a string of seconds with an `s` suffix, such as `"90.5s"`. The Web SDK drops one whose `seconds` is set, with a console warning. Flutter's typed methods take no duration, and a Dart `Duration` passed in `extras` is dropped with a warning. **`int64` type**: the Web SDK types these as `bigint`, so write the literal with an `n` suffix: `track('file_uploaded', { fileId: 'f1', sizeBytes: 1024n })`. A plain `number` is a compile error, and never encoded correctly. Over raw HTTP an int64 takes a JSON string or a whole number; see [Track events](/sdks/http#track-events). **Web vs mobile**: the Web SDK exposes all events listed here except the mobile app lifecycle events (`app_open`, `app_close`, `app_install`, `app_update`, `app_backgrounded`, `app_foregrounded`, `app_crashed`, `screen_view`). The Flutter SDK includes those and drops the DOM-interaction events (`click`, `rage_click`, `dead_click`). Its navigation event is `screen_view` on mobile; on **web** targets Flutter emits `page_view` instead. The Android and iOS SDKs drop `page_view` along with the DOM-interaction events, so their navigation event is always `screen_view`. # Roadmap > Where Pug is headed - shipped today, and the privacy, SDK and engagement work coming next. Source: https://docs.pug.sh/roadmap/ | Markdown: https://docs.pug.sh/roadmap/index.md Where Pug is headed. This is a **directional** view - the shape of what we're building next, not a dated commitment. Everything under [Available today](#available-today) is shipped and documented; the rest is planned and lands here as it ships. Our first priority is a **rock-solid analytics core** - events, profiles, insights, and dashboards you can trust. The bigger bets below build outward from that foundation. ## Available today Pug is a product analytics platform - capture events, identify the people behind them, and explore behavior through trends, funnels, retention, and segmentation, all on customizable dashboards. Client and server SDKs, plus a language-agnostic HTTP API: | Platform | Package | Docs | |----------|---------|------| | Web | `@pug-sh/browser` | [Web SDK](/sdks/web) | | Android | `sh.pug:android` | [Android SDK](/sdks/android) | | iOS | `github.com/pug-sh/sdk-ios` | [iOS SDK](/sdks/ios) | | Flutter | `pug_flutter` | [Flutter SDK](/sdks/flutter) | | Node.js (server) | `@pug-sh/node` | [Node SDK](/sdks/node) | | Go (server) | `github.com/pug-sh/sdk-go` | [Go SDK](/sdks/go) | | Ruby (server) | `pug-sh` | [Ruby SDK](/sdks/ruby) | | HTTP API | - | [API reference](/api) | You can also [self-host](/self-hosting) the entire stack today, and capture is [cookieless by default](/sdks/web#tracking-consent) - no device identifier is stored until the reader consents. ## Privacy & compliance Pug is privacy-first by design - [tracking-consent gating](/sdks/web#tracking-consent), no visitor-IP persistence, and GDPR/DPDP data-subject erasure are already in the product. **Cookieless capture has shipped, and it's the default.** The Web SDK's `trackingConsent` starts at `'cookieless'`: events flow from the first hit, but nothing is written to the device until the reader answers your banner. Global Privacy Control (`respectGpc`) and a bounded identifier lifetime (`maxAgeDays`, default 365) landed alongside it. See [Tracking consent](/sdks/web#tracking-consent). One area takes it further. ### DPDP hardening Deeper compliance controls for India's **Digital Personal Data Protection Act**: consent records and withdrawal, data-principal rights (access, correction, grievance redressal), retention limits, and breach notification, building on the GDPR/DPDP data-subject erasure, export, and retention the compliance worker already runs. ## More SDKs More client and server-side libraries are in active development, built on the same event and identity model as today's SDKs. **Until each lands, the [HTTP API](/api) works from any language or runtime.** ### Client SDKs | Platform | What | |----------|------| | React Native | Cross-platform tracking for React Native apps | ### Server SDKs Idiomatic server-side libraries that send events and read analytics with your private key, the way the [Node](/sdks/node), [Go](/sdks/go) and [Ruby](/sdks/ruby) SDKs do today. **Rust**, **Java**, and **Python** are in progress. ## Customer engagement Once the analytics core is stable, the next chapter is **acting on** your data, not just measuring it. Run **multi-channel campaigns composed from the same profiles and events you already track** - one composer, delivered to the channels your users are on. **Planned delivery channels:** | Group | Channels | |-------|----------| | Push | Web Push, Android Push, iOS Push | | Messaging | Email, SMS, WhatsApp | | Programmatic | Webhook | The foundations go into the analytics SDKs first - so when the campaign composer lands, your events and devices are already wired up: - **Notification events** - Received, opened, and dismissed notification events already flow into the same analytics pipeline. - **Push registration** - Provider-neutral device registration is built into the Flutter SDK, switched off until the devices endpoint is live. - **Campaign capture** - Capturing inbound campaigns from app links and deep links is built into the Flutter SDK too, switched off until the backend accepts it. ## Shape the roadmap Building something and need a platform sooner, or want a feature that isn't here? Tell us - it genuinely moves priorities: - **GitHub**: open or upvote a discussion at [github.com/pug-sh/pug](https://github.com/pug-sh/pug). - **Discord**: [join the community](https://discord.gg/kDNHDWcBHP). - **Reddit**: [r/pug_sh](https://www.reddit.com/r/pug_sh/). # SDKs > Client and server libraries for sending events and managing identity: Web, Android, iOS, Flutter, Node, Go, Ruby, and the raw HTTP API. Source: https://docs.pug.sh/sdks/ | Markdown: https://docs.pug.sh/sdks/index.md Client and server libraries for sending events and managing identity from your apps. Every integration shares one mental model (**initialize once, track events, identify users, reset on sign-out**) whether you use a browser/app SDK, a server-side SDK (**Node**, **Go** or **Ruby**), or call the API directly. The one exception is *reset*: a server SDK has no ambient user or session to reset, so you name the user's distinct ID on each call instead. - `init(projectId, options)` - once at app startup - `track(name, props)` - throughout the app - `identify(id, traits)` - after sign-in - `reset()` - on sign-out (client SDKs) ## Choose your platform | Platform | Use it when | Package | |----------|-------------|---------| | [**Web**](/sdks/web) | Browser apps: React, Vue, Next.js, or plain JavaScript | `@pug-sh/browser` | | [**Android**](/sdks/android) | Native Android apps, in Kotlin or Java | `sh.pug:android` | | [**iOS**](/sdks/ios) | Native iOS and iPadOS apps, in Swift | `github.com/pug-sh/sdk-ios` | | [**Flutter**](/sdks/flutter) | Cross-platform mobile & desktop apps | `pug_flutter` | | [**Node**](/sdks/node) | A Node.js backend that sends events **and** reads analytics | `@pug-sh/node` | | [**Go**](/sdks/go) | A Go backend that sends events **and** reads analytics | `github.com/pug-sh/sdk-go` | | [**Ruby**](/sdks/ruby) | A Ruby or Rails backend that sends events **and** reads analytics | `pug-sh` | | [**HTTP API**](/sdks/http) | Any other backend or language (anything that can POST JSON) | - | Each SDK page follows the same outline: install, initialize, track events, identify users, auto-tracking, consent, and upgrade notes. Every page is also published as markdown for agents - append `/index.md` to its URL, as in `/sdks/flutter/index.md`. A React Native SDK is on the [roadmap](/roadmap). Until it ships, use **Flutter** for cross-platform mobile, or the **HTTP API** from any runtime. **Client vs server keys.** The **Web**, **Android**, **iOS** and **Flutter** SDKs run in untrusted environments and authenticate with your **public key** (`pub_...`) - write-scoped (events + identify) and safe to ship in client code. The **Node**, **Go** and **Ruby** SDKs run on your server and use your **private key** (`prv_...`), which additionally unlocks analytics **reads** (profiles, activity, insights); never embed it in client code. See [Authentication](/get-started/authentication). > **Endpoint defaults to Pug Cloud** > > Every SDK defaults `endpoint` to `https://api.pugs.dev`, so you only set it when > **self-hosting**, pointing it at your own server (the dev server listens on port > `3000`). See [Connect your SDKs](/self-hosting/connect-sdks). ## Further reading - [Quickstart](/get-started): your first event in five minutes - [Core concepts](/get-started/concepts): events, profiles, sessions, identity - [Well-known events](/reference/well-known-events): the typed event catalog - [Auto-properties](/reference/auto-properties): every `$`-property the SDKs and server attach - [Authentication](/get-started/authentication): public vs. private keys, rotation - [Self-hosting](/self-hosting): run the Pug stack on your own infrastructure - **API reference:** [Events](/api/events) | [Profiles](/api/profiles) | [RPC services](/reference/rpc-services) - **SDK source:** [browser](https://github.com/pug-sh/sdk-browser) | [android](https://github.com/pug-sh/sdk-android) | [ios](https://github.com/pug-sh/sdk-ios) | [flutter](https://github.com/pug-sh/sdk-flutter) | [node](https://github.com/pug-sh/sdk-node) | [go](https://github.com/pug-sh/sdk-go) | [ruby](https://github.com/pug-sh/sdk-ruby) # Android SDK > Typed event tracking, activity and lifecycle auto-tracking, identity and consent for native Android apps, from Kotlin or Java, with sh.pug:android. Source: https://docs.pug.sh/sdks/android/ | Markdown: https://docs.pug.sh/sdks/android/index.md `sh.pug:android` captures events from native Android apps, in Kotlin or Java. It authenticates with your **public key** (`pub_...`), which is write-scoped (events + identify) and safe to ship in the app, and follows the [same model as every Pug SDK](/sdks): initialize once, track events, identify users, reset on sign-out. ## Install The SDK is on Maven Central. Add it to your app module: ```kotlin title="app/build.gradle.kts" dependencies { implementation("sh.pug:android:0.2.1") } ``` [View `sh.pug:android` on Maven Central](https://central.sonatype.com/artifact/sh.pug/android) In a Groovy build script that's `implementation 'sh.pug:android:0.2.1'`. | Requirement | Minimum | |-------------|---------| | Android | API 21 (`minSdk 21`) | | `kotlin-stdlib` | 2.0.21 | | `kotlinx-coroutines-core` | 1.9.0 | Those two are its only runtime dependencies (no AndroidX, OkHttp or protobuf runtime), and they are floors: an app on newer versions keeps its own. The SDK declares only the `INTERNET` permission and needs no R8 or ProGuard rules. To verify, run the app with a minimal [`Pug.init`](#initialize) and `debug = true`: an `app_open` and a `screen_view` appear in **Live** within a few seconds, and `adb logcat -s Pug` shows each event as it is tracked and sent. Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in [Install with AI](/get-started/ai-setup). ```text Add Pug product analytics to this Android app. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/android/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the app actually does: its activities, fragments or composables and how a user moves between them, its main models, and the handful of things a user opens the app to complete. The events worth tracking are the moments the app exists to produce - an account created, an order placed, a workout finished - not every tap. If you cannot state the core action in one sentence, keep reading. Then: 1. Add sh.pug:android from Maven Central to the app module's dependencies. It needs minSdk 21, and works from Kotlin and Java. 2. Call Pug.init() once, in Application.onCreate() - create an Application subclass and register it in the manifest if the app has none. Not in an activity: the SDK has to see each launch's first screen. 3. Keep the project ID and public key (pub_...) out of source - set them as BuildConfig fields from Gradle properties. Pug.init() throws for a key that is not a public key. 4. Leave auto-tracking on: it already tracks app_open, app_close, app_install, app_update and a screen_view per activity. In a single-activity app (Compose, or fragments under one activity), set autoScreenViews = false and call Pug.screen() on every destination change instead. 5. Add tracking for the three or four actions you identified - the ones someone would look at in a weekly review. 6. If this app has authentication, call Pug.identify() after sign-in and Pug.reset() on sign-out. Name events from the catalog before you invent one. Kotlin gets a generated named-argument method for each well-known event the SDK does not track itself - Pug.track.purchase(productId = ..., amount = ...) - and Java an event class - Pug.track(new PurchaseEvent().amount(...)) - so the compiler checks the properties for you, and the dashboards those events drive stay empty for a custom name. Reach for those first, search the catalog for every action you are about to track, and pass schema-external properties through extras. Use Pug.track(kind, properties) with a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not. Android consent has two states, starts granted and is saved across launches, which is not the same as the Web SDK - check the consent section before you add a banner. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this app does, then list the files you changed, the event names you chose, and the Gradle properties I need to set. ``` ## Initialize Call `Pug.init` **once**, in `Application.onCreate`, with your project ID and public key - every other call needs it first. Find your project ID in the dashboard URL (`/p/`), and your public key on your project **Overview** or under **Settings > API Keys**. ```kotlin import android.app.Application import sh.pug.android.Options import sh.pug.android.Pug class App : Application() { override fun onCreate() { super.onCreate() Pug.init(this, "YOUR_PROJECT_ID", Options("pub_your_public_key")) } } ``` If the app has no `Application` subclass yet, register this one on the manifest's `` element with `android:name=".App"`. Initialized there, before any activity starts, the SDK sees the first screen of each launch; initialized later, it tracks from the next activity on. `Pug.init` **throws `IllegalArgumentException`** for a blank project ID; a key that isn't a public key (`pub_...`), or holds a space or any character outside printable ASCII, such as a trailing newline; or an endpoint that isn't an http(s) URL. It's safe on the main thread under StrictMode, and `detectUntaggedSockets` doesn't flag the SDK's sockets. A second `Pug.init` is ignored with a warning until `Pug.destroy()`, and so is any call made before `Pug.init`. Every other call returns at once, can be made from any thread, and **never throws**: calls run in order on one background thread, and failures are logged. Options are set in a block after the key; the ones left out keep their defaults. From Java, build them with `new Options.Builder("pub_...")` - see [From Java](#from-java). ```kotlin Options("pub_your_public_key") { debug = BuildConfig.DEBUG batchMaxSize = 20 defaultTrackingConsent = TrackingConsent.DENIED } ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `endpoint` | `String` | `https://api.pugs.dev` | API base URL: set it only when self-hosting. | | `debug` | `Boolean` | `false` | Log debug messages: each event tracked, sent or dropped, and why. Warnings and errors are logged regardless. | | `dryRun` | `Boolean` | `false` | Build and log events without sending anything; `identify` isn't sent either. Consent is unaffected. | | `batchMaxSize` | `Int` | `10` | Events per request, at most 1000: a batch goes out once this many are queued, or `batchMaxWaitMs` after the first of them. | | `batchMaxWaitMs` | `Long` | `5000` | How long the first queued event waits for a full batch. | | `batchMaxQueueSize` | `Int` | `1000` | Undelivered events to keep; beyond this, the oldest is dropped. | | `sessionIdleTimeoutMs` | `Long` | 30 min | A session ends after this long without events. | | `sessionMaxDurationMs` | `Long` | 24 h | A session ends this long after it began. | | `defaultTrackingConsent` | `TrackingConsent` | `GRANTED` | Consent until the user chooses. See [Tracking consent](#tracking-consent). | | `persistTrackingConsent` | `Boolean` | `true` | Save the user's choice for the next launch. See [Tracking consent](#tracking-consent). | | `autoOpenCloseEvents` | `Boolean` | `true` | Track `app_open` and `app_close`. See [Auto-tracking](#auto-tracking). | | `autoScreenViews` | `Boolean` | `true` | Track a `screen_view` each time an activity resumes on a different screen. | | `autoInstallEvents` | `Boolean` | `true` | Track `app_install` and `app_update`. | | `logger` | `Logger` | Logcat, tag `Pug` | Receive the SDK's messages instead. A logger that throws is contained. | | `storage` | `Storage` | files | Keep the SDK's state somewhere else. `MemoryStorage()` keeps nothing on the device. | Nothing in `Options` throws: a number out of range is logged and replaced by its default, and a `batchMaxSize` above 1000 is capped. ### Delivery and storage Events are sent in batches, one request at a time. A request that fails for a reason that may pass (no network, a timeout, a server error, a captive portal) is retried with exponential backoff, from `batchMaxWaitMs` (at least a second) up to five minutes; one the server rejects for good is dropped and logged as an error. Requests are capped at 4 MiB, and an event over that is dropped when tracked. When the app leaves the foreground, everything queued is sent, whatever `autoOpenCloseEvents` says. Undelivered events, identity and consent live in files under the app's `noBackupFilesDir`, so they survive restarts but aren't restored onto another device by Auto Backup. Writes are grouped and land within a second, and at once when the app leaves the foreground, on a consent change, on `Pug.flush()` and on `Pug.destroy()`. If a custom `storage` throws, the SDK falls back to memory until `Pug.destroy()` or the process ends. In a multi-process app, call `Pug.init` in one process only, usually the main one: processes would otherwise share the SDK's files. ## Track events The first argument is the event **name** (its `kind`). Any name works without a schema; [well-known events](/reference/well-known-events) add typed properties and richer dashboards. ```kotlin // Custom event - any name Pug.track("button_clicked", mapOf("label" to "Sign up", "screen" to "pricing")) // Typed well-known event - compile-time checked Pug.track.purchase(productId = "sku-1", amount = 99.50, currency = "USD") ``` A kind may contain letters, digits, `_`, `.` and `-`; any other kind is dropped with a warning. Properties are read during the call, so the map can be reused as soon as `track` returns. A key starting with `$` is reserved for [auto-properties](/reference/auto-properties) and dropped with a warning - the property, not the event. **Property values** map by type: | Value | Sent as | |-------|---------| | `String`, `CharSequence`, `Char`, an enum (its name) | string, cut to 1024 UTF-8 bytes | | `Boolean` | bool | | `Int`, `Long`, `Short`, `Byte`, `BigInteger`, unsigned integers, `AtomicInteger`, `AtomicLong` | int - one beyond the signed 64-bit range as a string of its digits | | `Double`, `Float`, any other `Number` | double - `NaN` and infinities are dropped | | `Date`, `Calendar`, `Instant` (API 26+) | timestamp | | `Map`, `Iterable`, arrays | JSON string, cut to 1024 UTF-8 bytes | | `null` | omitted | | anything else, such as `UUID` or `Uri` | its `toString()`, cut to 1024 UTF-8 bytes | `TrackOptions` (on `Pug.track` and every typed method): | Option | Type | Default | Description | |--------|------|---------|-------------| | `immediate` | `Boolean` | `false` | Send the event on its own right away instead of with the next batch. If the send fails for a reason that may pass, the event joins the queue. | | `timestamp` | `Long?` | time of the call | Override the event time as **epoch milliseconds**, for an event recorded after the fact. A time before 1970 or after 9999 is logged and replaced by the time of the call. | ```kotlin Pug.track("order_completed", mapOf("orderId" to "o-1"), TrackOptions { immediate = true }) ``` `Pug.track` is also a namespace with a generated method per well-known event, 118 of them: every event in the catalog but the four web-only ones (`page_view`, `click`, `rage_click`, `dead_click`) and the five the SDK [tracks itself](#auto-tracking). Each takes the event's properties by name only - required ones non-null, optional ones nullable with a default - then `extras`, for properties the schema doesn't define, and `options`. A positional call such as `Pug.track.purchase("sku-1", 89.0)` doesn't compile. ```kotlin Pug.track.search(query = "trail shoes") Pug.track.videoPlay(videoId = "v1", positionMs = 1_500) Pug.track.addToCart( productId = "sku-1", extras = mapOf("coupon" to "SPRING"), options = TrackOptions { immediate = true }, ) ``` An extra named like an argument is dropped with a warning when that argument is set. Durations are milliseconds in a parameter ending in `Ms`, sent in seconds as text: `positionMs = 1_500` sends `position` as `"1.5s"`. Values are sent as given: ranges and patterns in the schemas aren't checked on the device. The kinds are constants in `Events` (`Events.ADD_TO_CART` is `"add_to_cart"`). `Pug.track(kind, properties)` works for a well-known kind too: a whole number for a decimal property is sent as a decimal (`"price" to 10` arrives as `10.0`), and with `debug` on, a missing required property is logged. ### From Java ```java Pug.init(this, "YOUR_PROJECT_ID", new Options.Builder("pub_your_public_key") .debug(BuildConfig.DEBUG) .defaultTrackingConsent(TrackingConsent.DENIED) .build()); Map properties = new HashMap<>(); properties.put("cartId", "c1"); Pug.track("checkout_started", properties); Pug.track("order_completed", properties, new TrackOptions.Builder().immediate(true).build()); Pug.track(new PurchaseEvent().orderId("o-1").amount(89).currency("USD").extra("coupon", "FALL10")); Pug.track(new AddToCartEvent().productId("sku-1").price(9.99).quantity(2)); Pug.track.signup(); // an event without properties has no class ``` Each well-known event with properties has a class in `sh.pug.android.events` with a setter for every property, required ones included (numbers as primitives, so `amount(89)` compiles), and `extra(key, value)` adds one the event doesn't define. An unset property isn't sent. An event missing a required one - unset, set to `null`, or dropped as invalid - still goes out, with a warning; each class's documentation names its required properties. From Java, `Pug.track` has methods only for the events without properties, such as `Pug.track.signup()`, and the `Events` constants work in a `switch`. ## Identify and sessions Events accumulate against an anonymous ID until you `Pug.identify()` the user on sign-in, which merges that history into a known profile; call `Pug.reset()` on sign-out. Use a **stable, unique** external ID - your database user ID, not an email, which can change. Only the **first** identify after an anonymous session merges prior activity; the same external ID always resolves to the same profile, and traits are merged server-side, never removed. ```kotlin // On sign-in Pug.identify("user-123", mapOf("email" to "user@example.com", "plan" to "pro")) // On sign-out Pug.reset() // New session ID, identity kept Pug.rotateSession() ``` Once the server accepts an `identify`, events carry the external ID as their distinct ID. A failed one is logged and not retried, so events keep their current distinct ID until a later call succeeds. Traits may nest maps and lists. A blank ID, or one starting with the reserved `cookieless-` prefix, is rejected with an error in the log. `reset()` forgets the external ID and starts a new anonymous ID and session; it does **not** delete the profile. Events queued before it keep the user they were tracked for, and are sent without waiting for the next batch. `Pug.flush()` sends what's queued now and writes the SDK's state to disk; `Pug.destroy()` stops the SDK after a final flush of at most ten seconds, keeping identity, saved consent and undelivered events for the next `Pug.init`, which waits for the teardown to finish. | Function | Forgets the external ID | New anonymous ID | New session ID | |----------|-------------------------|------------------|----------------| | `rotateSession()` | No | No | Yes | | `reset()` | Yes | Yes | Yes | ### Sessions Sessions group events within a single visit, ending at the idle or max-duration timeout: 1. **First event** (session ID created) 2. **Events within timeout** (same session ID) 3. **Idle past timeout** (session expires) 4. **Next event** (new session ID (identity kept)) The session survives restarts: a launch within the timeouts continues it. Set them with the `sessionIdleTimeoutMs` and `sessionMaxDurationMs` [init options](#initialize). ## Auto-tracking By default, the SDK tracks these events itself: | Event | When | Option | |-------|------|--------| | `app_open` | The app comes to the foreground: an activity starts while none was started. | `autoOpenCloseEvents` | | `app_close` | The app leaves the foreground: its last started activity stops, but not for a rotation or other configuration change. Sent at once, not batched. | `autoOpenCloseEvents` | | `screen_view` | An activity resumes on a different screen: `screenName` is its class's simple name, `screenClass` the full one. | `autoScreenViews` | | `app_install` | The first launch with the SDK on this device, with `appVersion` and `installSource`. | `autoInstallEvents` | | `app_update` | The first launch of a new app version, with `appVersion` and `previousVersion`. | `autoInstallEvents` | Every event also carries the SDK's [auto-properties](/reference/auto-properties#sdk-set-properties-android) - device, OS, app version, display, locale, time zone and the current screen - and the server adds geo. `$networkType` is set only when your app holds `ACCESS_NETWORK_STATE`, which the SDK doesn't declare. The device name is never collected. **Screens** are activities until you name them. An activity that resumes after being only paused, as under a permission dialog, is the same screen and isn't tracked again. For a screen that isn't an activity, such as a composable or a fragment, call `Pug.screen`: ```kotlin Pug.screen("Settings") ``` It tracks a `screen_view` unless that screen is already the current one, and every event after it carries the screen as `$url` and the one before as `$referrer`. In a **single-activity app** - Compose, or fragments under one activity - set `autoScreenViews = false` and name every screen yourself: otherwise the activity replaces your screen each time it resumes, as when the app returns to the foreground. With Jetpack Navigation, a destination listener does it: ```kotlin navController.addOnDestinationChangedListener { _, destination, _ -> (destination.route ?: destination.label)?.let { Pug.screen(it.toString()) } } ``` **Installs and updates** are decided once at launch, from the SDK's own state on the device: `app_install` when the SDK has never run there, and `app_update`, carrying `previousVersion`, on the first launch after `versionName` changes. An app without a `versionName` reports neither. `installSource` is the package name of the app that installed yours, such as `com.android.vending` for Google Play, and is left out when none is recorded, as for an app installed with `adb`. **Adding the SDK to an app that is already out** reports each existing user's first launch with it as an `app_install`. Turning `autoInstallEvents` on later, in an app already shipping the SDK, doesn't, and neither does a destroy-and-init cycle. ## Consent and privacy > **Not the Web SDK's default** > > **Android defaults to granted** and stores identity from the first event. The > [Web SDK](/sdks/web#tracking-consent) defaults to `'cookieless'`, which stores > nothing on the device and has no Android equivalent. ### Tracking consent Consent has two states, `TrackingConsent.GRANTED` and `TrackingConsent.DENIED`, and starts granted. To wait for the user's choice, start denied, and show your banner while the choice is still pending: ```kotlin Pug.init(this, "YOUR_PROJECT_ID", Options("pub_your_public_key") { defaultTrackingConsent = TrackingConsent.DENIED }) Pug.whenConsentReady { if (Pug.isConsentPending()) showConsentBanner() } Pug.optInTracking() // the user accepted Pug.optOutTracking() // the user declined ``` The choice is saved, so the banner shows only until the user answers. While consent is denied, events and `identify` are dropped, not kept for later. Opting out drops queued events unsent and removes the stored identity; opting in again starts a new anonymous identity. When the user opts in, the SDK tracks what consent held back: an `app_install` or `app_update` it couldn't track at launch and, if the app is on screen, `app_open` and a `screen_view` of the current screen. The consent getters never wait. Right after `Pug.init`, while the SDK reads the saved choice on its own thread, they answer "not known yet". `Pug.whenConsentReady { ... }` runs its block on the main thread as soon as they answer for this user, or on the main thread's next turn if they already do. | Call | Returns | Not known yet | |------|---------|---------------| | `getTrackingConsent()` | The consent in effect | `null` | | `isTrackingEnabled()` | Whether consent is granted | `false` | | `isConsentPending()` | Whether the user has yet to choose | `true` | If your app keeps the choice itself and calls `optInTracking()` or `optOutTracking()` on every launch, set `persistTrackingConsent = false`: the choice then lasts until `Pug.destroy()` or the process ends. ### Redacting PII There's no device-side redaction and no `beforeSend` hook: keep PII out of the properties you pass to `Pug.track`. ## Upgrading ### v0.2.0 Typed events take their properties by name only, so code written for 0.1.0 may not compile: - **Kotlin**: name every argument of a `Pug.track` method. `Pug.track.addToCart("sku-1")` becomes `Pug.track.addToCart(productId = "sku-1")`. - **Java**: event classes have no constructor arguments; required properties have setters like the rest. `new AddToCartEvent("sku-1")` becomes `new AddToCartEvent().productId("sku-1")`. - **An event object missing a required property is sent** without it, with a warning, where 0.1.0 dropped it. # Flutter SDK > Typed event tracking, screen and lifecycle auto-tracking, and identity for Flutter apps with pug_flutter. Source: https://docs.pug.sh/sdks/flutter/ | Markdown: https://docs.pug.sh/sdks/flutter/index.md `pug_flutter` captures events from Flutter apps on mobile, desktop and the web. It authenticates with your **public key** (`pub_...`), which is write-scoped (events + identify) and safe to ship in the app, and follows the [same model as every Pug SDK](/sdks): initialize once, track events, identify users, reset on sign-out. ## Install ```bash flutter pub add pug_flutter ``` [View `pug_flutter` on pub.dev](https://pub.dev/packages/pug_flutter) To pin the version yourself, add it under `dependencies` instead: ```yaml title="pubspec.yaml" dependencies: pug_flutter: ^0.1.1 ``` | Requirement | Minimum | |-------------|---------| | Dart SDK | `>=3.7.0 <4.0.0` | | Flutter | `>=3.29.0` | Import it wherever you call the SDK: ```dart import 'package:pug_flutter/pug_flutter.dart'; ``` To verify, run the app with a minimal [`Pug.init`](#initialize) in `main()`: an `app_open` appears in **Live** within a few seconds. Navigation events need a [`PugRouteObserver`](#auto-tracking). Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in [Install with AI](/get-started/ai-setup). ```text Add Pug product analytics to this Flutter app. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/flutter/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the app actually does: its screens and navigation graph, its main models, and the handful of things a user opens the app to complete. The events worth tracking are the moments the app exists to produce - an account created, an order placed, a workout finished - not every tap. If you cannot state the core action in one sentence, keep reading. Then: 1. Add pug_flutter to pubspec.yaml. 2. Await Pug.init() in main(), after WidgetsFlutterBinding.ensureInitialized() and before runApp(). 3. Keep the project ID and public key (pub_...) out of source - pass them with --dart-define and read them with String.fromEnvironment. 4. Register PugRouteObserver on the app's navigatorObservers, otherwise screen views never fire. 5. Add tracking for the three or four actions you identified - the ones someone would look at in a weekly review. 6. If this app has authentication, call Pug.identify() after sign-in and Pug.reset() on sign-out. Name events from the catalog before you invent one. Flutter gets a generated named-argument method for all 127 well-known events - Pug.track.purchase(productId: ..., amount: ...) - so the compiler checks the properties for you, and the dashboards those events drive stay empty for a custom name. Reach for Pug.track. first, search the catalog for every action you are about to track, and pass schema-external properties through extras. Use Pug.track(kind, props: {...}) with a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not. Flutter consent has two states and starts granted, which is not the same as the Web SDK - check the consent section before you add a banner. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this app does, then list the files you changed, the event names you chose, and the dart-defines I need to pass. ``` ## Initialize Await `Pug.init` **once** in `main()`, before `runApp()`, with your project ID and public key - every other call needs it first. Find your project ID in the dashboard URL (`/p/`), and your public key on your project **Overview** or under **Settings > API Keys**. ```dart import 'package:pug_flutter/pug_flutter.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await Pug.init( 'YOUR_PROJECT_ID', const PugOptions( apiKey: 'pub_your_public_key', ), ); runApp(const MyApp()); } ``` `Pug.init` **throws `ArgumentError`** if `projectId` or `apiKey` is blank. A second `init` is ignored, with a warning through its `logger`, until [`Pug.destroy()`](#identify-and-sessions). | Option | Type | Default | Description | |--------|------|---------|-------------| | `apiKey` | `String` | **required** | Public key (`pub_...`), sent as `x-api-key`. | | `endpoint` | `String` | `https://api.pugs.dev` | API base URL: set it only when self-hosting. | | `batch` | `BatchConfig` | `maxSize 10`, `maxWaitMs 5000`, `maxQueueSize 1000` | Queue size and flush timing; the queue is persisted to `SharedPreferences`. | | `session` | `SessionConfig` | `idleTimeout 30 min`, `maxDuration 24 h` | Session timeouts as `Duration`s. | | `autoTrack` | `bool` | `true` | Emit `app_open` and `app_close` on lifecycle changes. | | `autoPageViews` | `bool` | `true` | Emit a navigation event on route changes: `screen_view` on mobile, `page_view` on web (needs `PugRouteObserver`). | | `autoInstallEvents` | `bool` | `true` | Emit `app_install` and `app_update` at launch. See [Auto-tracking](#auto-tracking). | | `trackingConsent` | `TrackingConsentConfig` | `const TrackingConsentConfig()` | Consent gate: two states, granted by default. See [Tracking consent](#tracking-consent). | | `dryRun` | `bool` | `false` | Build and log events without sending them; `identify` is still sent. Consent is unaffected. | | `logger` | `PugLogger` | `NoopPugLogger()` | Receives the SDK's messages, which the default discards. Pass `DebugPrintPugLogger()` to print them. | | `httpClient` | `http.Client?` | `package:http`'s default | Send through any `package:http` client, such as `CupertinoClient` (`cupertino_http`) or `CronetClient` (`cronet_http`). The SDK never closes it, so it can be reused across `Pug.destroy()` and `Pug.init()`. Ignored, with a warning, when `transport` is set. | `storage`, `transport` and `autoPropertyProvider` replace the SDK's own, for test doubles or custom collection. ## Track events The first argument is the event **name** (its `kind`). Any name works without a schema; [well-known events](/reference/well-known-events) add typed properties and richer dashboards. A name may hold only ASCII letters, digits, `_`, `.` and `-`: the server rejects any batch containing another, and the SDK logs an error and drops that whole batch. ```dart // Custom event - any name Pug.track('button_clicked', props: {'label': 'Sign up', 'screen': 'pricing'}); // Typed well-known event - compile-time checked Pug.track.purchase(productId: 'sku-1', amount: 99.50, currency: 'USD'); ``` `Pug.track(...)` **never throws**; events are queued and sent in the background. `Pug.track.*` has a typed method per well-known event but the four web-only ones (`page_view`, `click`, `rage_click`, `dead_click`). Pass properties the schema doesn't define in `extras: {...}`; on a key collision, the named argument wins. For a name known only at runtime, call `Pug.track(kind, props: {...})`. **Property values** accept `String`, `bool`, `int`, finite `double`/`num` (non-finite values are dropped) and `DateTime`, sent as a timestamp. An `Iterable` or `Map` is sent as a JSON string, and `null` is omitted. Strings, JSON included, are cut to 1024 UTF-8 bytes. `TrackOptions` (on `Pug.track` and every typed method): | Option | Type | Default | Description | |--------|------|---------|-------------| | `immediate` | `bool` | `false` | Bypass the queue and send now (falls back to the queue on transient failure). | | `timestampMillis` | `int?` | wall clock | Override the event time as **epoch milliseconds**. | ```dart Pug.track.purchase( productId: 'sku-789', amount: 99.0, currency: 'USD', options: const TrackOptions(immediate: true), ); ``` ## Identify and sessions Events accumulate against an anonymous ID until you `Pug.identify()` the user on sign-in, which merges that history into a known profile; call `Pug.reset()` on sign-out. Use a **stable, unique** external ID - your database user ID, not an email, which can change. Only the **first** identify after an anonymous session merges prior activity; the same external ID always resolves to the same profile, and traits are merged server-side, never removed. ```dart // On sign-in await Pug.identify('user-123', traits: {'email': 'user@example.com', 'plan': 'pro'}); // On sign-out Pug.reset(); // New session ID, identity kept Pug.rotate(); ``` `Pug.identify(externalId, {traits})` returns `Future` and **never throws**: invalid input, a call before `Pug.init()`, denied consent and transport failures are logged, and the future completes normally. An `externalId` starting with `cookieless-`, a prefix the server reserves, is invalid. `reset()` starts a new device ID, anonymous ID and session and forgets the external ID; it does **not** delete the profile. `await Pug.flush()` sends everything queued. `Pug.destroy()` makes a final flush, then deletes everything Pug stored except a persisted consent choice: the next `Pug.init` starts a new anonymous user, and undelivered events are lost. | Function | Clears identity | New device ID | New session ID | |----------|-----------------|---------------|----------------| | `rotate()` | No | No | Yes | | `reset()` | Yes | Yes | Yes | ### Sessions Sessions group events within a single visit, ending at the idle or max-duration timeout: 1. **First event** (session ID created) 2. **Events within timeout** (same session ID) 3. **Idle past timeout** (session expires) 4. **Next event** (new session ID (identity kept)) The session survives restarts: a launch within the timeouts continues it. Set them with the `session` [init option](#initialize). ## Auto-tracking By default the SDK tracks app lifecycle and installs itself, and navigation once you add a `PugRouteObserver`. Every event carries the SDK's [auto-properties](/reference/auto-properties#sdk-set-properties-flutter), and the server attaches enrichment properties. Auto-property keys are camelCase (`$deviceType`, `$osVersion`, `$networkType`) except the server-set `$bot_reason`, `$bot_score` and `$verified_bot`. **Navigation** is captured when you wire a `PugRouteObserver` into your `MaterialApp`: ```dart MaterialApp( navigatorObservers: [PugRouteObserver()], // ... rest of your config ) ``` On each route change the SDK tracks `screen_view`, with `screenName` set to the route name, on **iOS/Android**, and `page_view` on **web**; desktop targets track neither. Every event then carries the current and previous route as the `$url` and `$referrer` auto-properties, even with `autoPageViews` off. Route names come from `route.settings.name`, falling back to the route's runtime type. **App lifecycle** needs no wiring: `app_open` when the app comes to the foreground, and `app_close`, sent at once rather than batched, when it goes to the background (`hidden`, `paused` or `detached`). `inactive` - an incoming call, the app switcher, a control-centre swipe - is not a close. **Installs and updates** are checked once at launch, against the `$appVersion` [auto-property](/reference/auto-properties#app) stored at the last launch: `app_install` on the first launch the SDK sees on a device, and `app_update`, carrying `previousVersion`, on the first launch after the version changes. A custom `PugAutoPropertyProvider` that supplies no `$appVersion` turns both off. `app_install` carries `installSource` as `package_info_plus` reports it, such as `com.android.vending` for Google Play or `com.apple` for the App Store, and leaves it out when there is none, as with an `adb install`, on web and desktop, and with a custom `PugAutoPropertyProvider`. An app that already used Pug doesn't report its existing users as installs, but a destroy-and-init cycle does: [`Pug.destroy()`](#identify-and-sessions) deletes the stored version. ## Consent and privacy > **Not the Web SDK's default** > > **Flutter defaults to granted** and stores identity from the first event. The > [Web SDK](/sdks/web#tracking-consent) defaults to `'cookieless'`, which stores > nothing on the device and has no Flutter equivalent. ### Tracking consent Consent has two states, `TrackingConsent.granted` and `TrackingConsent.denied`, and starts granted. There is no `isConsentPending()`. ```dart await Pug.init( 'YOUR_PROJECT_ID', const PugOptions( apiKey: 'pub_YOUR_PUBLIC_KEY', trackingConsent: TrackingConsentConfig( defaultConsent: TrackingConsent.denied, persist: true, ), ), ); Pug.optInTracking(); Pug.optOutTracking(); Pug.isTrackingEnabled(); Pug.getTrackingConsent(); ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `defaultConsent` | `TrackingConsent` | `granted` | Starting state, used when nothing is persisted. The Web SDK calls it `initial`. | | `persist` | `bool` | `false` | Write the choice to `__pug__consent__` and restore it on the next `Pug.init()`. Otherwise the choice lasts until `Pug.destroy()` or the process ends, then resets to `defaultConsent`. | While denied, `Pug.track(...)`, the typed `Pug.track.*` methods, `Pug.identify(...)` and the automatic lifecycle, navigation and install events are dropped. They resume once consent is granted; an `app_install` or `app_update` held back is tracked at the next launch that starts granted. ### Redacting PII `pug_flutter` has no device-side redaction - no `beforeSend` or `redactUrlParams` - and captures no element text, so keep PII out of the properties you pass to `Pug.track(...)`. ## Upgrading ### v0.0.5 Campaign capture and push device registration left the public API until the backend accepts them, so code that used either no longer compiles: | Removed | Fix | |---|---| | `PugOptions.autoCaptureCampaigns` and `linkProvider` | Delete them. No `$utm*` or click-id auto-properties are attached any more | | `PugPush`, `PushProvider`, `PushSubscription`, `PushSubscribeOptions` | Delete the registration code | | `PugLinkProvider`, `AppLinksPugLinkProvider`, `campaignPropertiesFromUri` | Delete them | | `PugTransport.subscribeDevice` | Delete it from a custom transport | The notification events are unaffected: `Pug.track.notificationClicked(...)`, `notificationReceived` and `notificationDismissed` still work alongside your own push integration. Send them with `TrackOptions(immediate: true)`, as the OS can suspend a backgrounded app before the next flush. - **`app_install` and `app_update` are tracked for you**, behind the new [`autoInstallEvents`](#auto-tracking) option (default on). In an app that already used Pug, the first `app_update` comes with the release after the one that ships 0.0.5. If you already track either event yourself, set `autoInstallEvents: false`, or each is counted twice. - **`app_close` no longer fires on `inactive`.** An incoming call, the app switcher or a control-centre swipe used to log an `app_close`/`app_open` pair, so expect fewer of both. ### v0.0.4 Nothing here breaks compilation - the changes are all in the [auto-properties](/reference/auto-properties) each event carries. - **`$deviceType` is new**: `tv`, `mobile` or `desktop`, omitted on web and on any target it can't classify. Android TV reports `tv` with `$platform` `android`. - **`$deviceModel` no longer ships placeholders.** `device_info_plus`'s `"Unknown device"`/`"Unknown Model"` now fall back to the device identifier (`iPhone`, `MacBookPro18,3`); on macOS, any Mac missing from the plugin's table was affected. - **`$osVersion` falls back to the OS version string** when the device-info payload has none, instead of being sent empty. - **`$deviceManufacturer` is no longer sent on Windows**, which exposes no manufacturer - the value being sent was the host name. > **v0.0.3 changed \$platform values - check your saved queries** > > Before 0.0.3 the Flutter SDK sent `iOS` and `macOS` where every other Pug SDK > sends `ios` and `macos`, and Flutter **web** reported the browser's host OS > instead of `web`. Dashboards, filters and saved segments that match the old > casing, or treat Flutter web traffic as iOS, need updating. # Go SDK > Send events and read profiles, activity and insights from a Go backend with github.com/pug-sh/sdk-go and a private key. Source: https://docs.pug.sh/sdks/go/ | Markdown: https://docs.pug.sh/sdks/go/index.md `github.com/pug-sh/sdk-go` sends events from your Go backend **and** reads analytics back - profiles, activity and insights. It authenticates with your **private key** (`prv_...`), so it belongs on the server only. It follows the [same model as every Pug SDK](/sdks) with one exception: a server has no ambient user or session to reset, so you name the `distinctID` on each call instead. ## Install ```bash go get github.com/pug-sh/sdk-go ``` [View `github.com/pug-sh/sdk-go` on pkg.go.dev](https://pkg.go.dev/github.com/pug-sh/sdk-go) The module needs **Go 1.26+**, and its package is named `pug`: ```go import pug "github.com/pug-sh/sdk-go" ``` Keep the private key in an environment variable or a secret store, never in code shipped to a browser or app. Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in [Install with AI](/get-started/ai-setup). ```text Add Pug product analytics to this Go backend. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/go/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the service actually does: its routes or handlers, its main models, and the state changes that matter to the business. On a server the events worth tracking are the ones a browser cannot observe - a payment settling, a webhook arriving, a job finishing, a subscription lapsing - not request logging. If you cannot state what this service is for in one sentence, keep reading. Then: 1. Run go get github.com/pug-sh/sdk-go. It needs Go 1.26+, and its package is named pug, so import it as pug "github.com/pug-sh/sdk-go". 2. Construct one client with pug.New at startup and share it - do not build one per request. It is safe for concurrent use, so hand it to handlers the way this codebase passes its other dependencies. Its APIKey is the private key (prv_...), read from an environment variable, never committed. pug.New returns an error for a missing or public key - handle it at startup. 3. Remember the argument order: client.Track(distinctID, kind, fields...). The distinctID comes first because a server has no ambient user - use our own user ID, or the anon-... ID forwarded from the client. Properties are typed fields such as pug.String("plan", "pro") and pug.Float("amount", 49), in the same list as options such as pug.WithTimestamp, and a kind held in a variable needs pug.Kind(name). 4. Add track calls for the three or four state changes you identified. 5. Call client.Identify(externalID, traits...) when a user record is created or changes materially, not on every request. Use the named traits - pug.Name, pug.Email and the rest - for the keys the dashboard reads. 6. Call client.Close(ctx) in the graceful-shutdown path, after the HTTP server has shut down, so queued events and identifies flush, and set an OnError handler so dropped events and identifies are logged rather than lost. Name events from the catalog before you invent one. The Go SDK knows 114 of the 127 well-known events, and client.TrackWellKnown takes each one's typed message - &commoneventsv1.PurchaseProperties{...} from github.com/pug-sh/sdk-go/gen/common/events/v1 - so the compiler checks the properties, where Track with a well-known kind checks them at runtime and drops the event on a wrong type. The ones a backend is placed to see are exactly the ones whose schemas are worth having - purchase, subscription_started, invoice_paid, payment_failed, order_refunded. Search the catalog for every action you are about to track, use TrackWellKnown for the ones that fit, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not. There is no Reset on the server SDK, and no immediate option on Track - use Flush. Track and Identify never return errors; only the reads do. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this service does, then list the files you changed, the event names you chose, and the environment variables I need to set. ``` ## Initialize Construct a client with `pug.New` **once** at startup with your private key, and share it: a `*pug.Client` is safe for concurrent use. Private keys live under **Settings > API Keys**, but one is only shown when you [create it](/get-started/authentication) - if you don't have yours, issue a new one. ```go import ( "log" "os" pug "github.com/pug-sh/sdk-go" ) // Construct once at startup, share it across goroutines and requests. client, err := pug.New(pug.Options{ APIKey: os.Getenv("PUG_PRIVATE_KEY"), // prv_... - server-side only, never ship to a client OnError: func(err error, lost pug.Undelivered) { log.Printf("pug dropped %d event(s) and %d identify(s): %v", len(lost.Events), len(lost.Identifies), err) }, }) if err != nil { log.Fatal(err) } ``` `pug.New` returns an error if `APIKey` is missing, doesn't start with `prv_`, or holds a space or any character outside printable ASCII, such as a trailing newline. An `Endpoint` that isn't an absolute http(s) URL is refused too; after that, ingestion never fails. | Option | Type | Default | Description | |--------|------|---------|-------------| | `APIKey` | `string` | **required** | Private key (`prv_...`), sent as `x-api-key`. | | `Endpoint` | `string` | `https://api.pugs.dev` | Pug server origin; set it only when self-hosting. | | `Batch` | `pug.BatchConfig` | `MaxSize: 100`, `MaxWait: 5 * time.Second`, `MaxQueueSize: 10_000` | One buffer each for events and identifies: items per request (capped at 1000), the longest an item waits before a send, and how many to hold before the oldest are dropped. Zero fields take the defaults. | | `OnError` | `pug.OnError` | none | Dead-letter hook for events and identifies that couldn't be delivered, called as `(err, lost)`: a permanent send failure, a queue overflow, or what `Close` couldn't send. `lost.Events` or `lost.Identifies` holds the items; the other is empty. | | `Logger` | `*slog.Logger` | `slog.Default()` | Gets the SDK's warnings and errors, each prefixed `pug: `. | | `HTTPClient` | `*http.Client` | a client on `http.DefaultTransport` | Sends every request - set it for a proxy, custom TLS or instrumentation. | | `Timeout` | `time.Duration` | `10 * time.Second` | Bounds each request whose context has no deadline: every background send, and any read you call without one. | Two goroutines, one for events and one for identifies, send in batches when `MaxSize` are queued or `MaxWait` has passed. A transient failure, such as a network error or a timeout, keeps a batch queued and retries `MaxWait` after the failure; a permanent one - a client error such as `Unauthenticated` or `InvalidArgument` - hands it to `OnError` as a [`*pug.Error`](#errors) carrying that code. Overflow arrives as `pug.ErrQueueOverflow`, and what `Close` couldn't send as `pug.ErrClosed` or the error that failed its last attempt; match them with `errors.Is`. Events the server refuses from a batch it otherwise accepts are logged as a warning. `OnError` can run on any goroutine, including the one calling `Track`, `Identify` or `Close`, so it must be safe for concurrent use, return promptly, and not call `Flush` or `Close`. Call `client.Close(ctx)` on graceful shutdown so nothing queued is lost - see [`Flush` and `Close`](#track-events). ### In an HTTP server Construct the client in `main`, use it from your handlers, and close it after the server has shut down, so requests still in flight have queued their events: ```go func main() { client, err := pug.New(pug.Options{APIKey: os.Getenv("PUG_PRIVATE_KEY")}) if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) { order := placeOrder(r) // your handler's own work client.Track(order.UserID, "order.completed", pug.Float("amount", order.Total)) }) srv := &http.Server{Addr: ":8080", Handler: mux} ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() go func() { if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { log.Fatal(err) } }() <-ctx.Done() shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() srv.Shutdown(shutdown) // in-flight requests finish and queue their events client.Close(shutdown) // then the queues drain } ``` ## Track events After the `distinctID`, the next argument is the event **name** (its `kind`). Any name works without a schema; [well-known events](/reference/well-known-events) add typed properties and richer dashboards. ```go // distinctID (who the event is for) comes first - a server has no ambient user. client.Track("user-123", "order.completed", pug.Float("amount", 49), pug.String("currency", "USD")) // Well-known events get typed, validated properties. client.Track("user-123", "purchase", pug.String("productId", "sku_123"), pug.Float("amount", 29.99), pug.String("currency", "USD")) ``` `client.Track(distinctID, kind, opts...)` takes the **`distinctID` first**: your external ID, or an `anon-...` ID forwarded from the client. `Track` **never fails** and returns at once; events are validated, batched and sent in the background, and invalid input is logged and dropped. Properties are typed fields, passed in the same list as the options below and in any order: | Field | Sent as | |-------|---------| | `pug.String(key, v)` | string | | `pug.Int(key, v)` | int, from any integer type | | `pug.Float(key, v)` | double, even for a whole number | | `pug.Bool(key, v)` | bool | | `pug.Time(key, v)` | timestamp | | `pug.Duration(key, v)` | duration string, such as `"1.5s"` | | `pug.Any(key, v)` | mapped by its Go type (table below) | For keys known only at run time, pass a `pug.Properties` map, converting a `map[string]any` with `pug.Properties(m)`. Fields and maps mix freely, and a key set twice in one call takes the later value. The kind is a `pug.Kind`, and may hold only ASCII letters, digits, `_`, `.` and `-`; anything else drops the event. A string literal converts on its own, but a kind held in a variable needs `pug.Kind(name)`: ```go kind := os.Getenv("CHECKOUT_EVENT") client.Track("user-123", pug.Kind(kind), pug.Properties{"plan": "pro", "seats": 5}) ``` There is no `immediate` option on the server - flush explicitly instead: ```go err := client.Flush(ctx) // send what's queued now, and wait for that attempt err = client.Close(ctx) // drain on graceful shutdown so nothing queued is lost ``` Both cover events and identifies, and return `ctx`'s error if it ended first. A `nil` doesn't mean everything was delivered: from `Flush` it means the attempt finished, and a transient failure re-queues for a later send; from `Close` it means the drain finished. Either way, by the time `Close` returns, everything it couldn't send has gone to `OnError` and the log. After `Close`, `Track` and `Identify` calls are dropped with a warning. `Track` options: | Option | Description | |--------|-------------| | `pug.WithTimestamp(t)` | Override the event time with a `time.Time`; it defaults to now. A time before 1970 or after 9999 is ignored with a warning and the event is sent at the current time. | | `pug.WithSessionID(id)` | A UUID to use as this event's session ID - otherwise the client uses one for its lifetime. Anything but a UUID is ignored with a warning. | | `pug.WithLocation(loc)` | Where the **visitor** is. Without it a server event carries no geo at all. See [Visitor location](#visitor-location). | **Property values** in `pug.Any` and `pug.Properties` map by Go type: | Go value | Sent as | |----------|---------| | `string`, `bool` | string, bool | | integers | int - a `uint64` past the int64 range is dropped | | `float32`, `float64` | double - `NaN` and `±Inf` are dropped | | `json.Number` | int when it has no fraction, else double | | `time.Time`, `*timestamppb.Timestamp` | timestamp | | `time.Duration`, `*durationpb.Duration` | duration string, such as `"1.5s"` | | `encoding.TextMarshaler` | its text | | other maps, slices and structs | JSON string | | `nil` | omitted | Pointers are followed, and a nil one is omitted. A value with no mapping, such as a func, is dropped with a warning - the property, not the event. Strings are capped at 1024 bytes and truncated with a warning. Decode JSON request bodies with `json.Decoder.UseNumber` so whole numbers stay ints. **Property keys** are sent as written, so `order_total` stays `order_total`. A [well-known event](/reference/well-known-events)'s properties are checked against its schema before the event is queued, keyed by the fields' JSON names (`productId`). A field's type comes from the schema rather than the Go value, so `pug.Int("amount", 10)` is sent as a double. A value of the wrong type, or one failing a rule such as `currency` needing three uppercase letters, drops the **whole event**, and the log names the field (`quantity: expected int32, got string`). A key that is a field's proto name (`product_id`) doesn't set the field: it is sent as a custom property with a warning, and if the field is required the event is dropped. Keys outside the schema pass through as custom properties. Duration fields such as `position` take a `time.Duration` or `*durationpb.Duration` and are sent as a string like `"92.5s"`. `client.TrackWellKnown(distinctID, event, opts...)` takes the typed schema instead, so the compiler checks field names and types. The kind comes from the message, whose types live in `github.com/pug-sh/sdk-go/gen/common/events/v1`: ```go import ( commoneventsv1 "github.com/pug-sh/sdk-go/gen/common/events/v1" "google.golang.org/protobuf/proto" ) client.TrackWellKnown("user-123", &commoneventsv1.PurchaseProperties{ ProductId: proto.String("sku_123"), Amount: proto.Float64(29.99), Currency: proto.String("USD"), }, pug.String("coupon", "FALL25")) ``` Rules such as the `currency` pattern are still checked when it's called, and a violation drops the event with a log. Fields and `Properties` among `opts` are sent as custom properties alongside the typed ones, except one keyed by a typed field's JSON name, which is skipped with a warning. A message that isn't a well-known server event, such as a web-only event's, is refused with a log. `Track` logs and drops an event whose `distinctID` is empty, isn't valid UTF-8, or starts with `cookieless-`, a prefix the server reserves; it would reject the whole batch. ### Visitor location The server adds no geo to events sent with a private key: an event carries the location you give it with `pug.WithLocation`, or none at all. ```go client.Track("user-123", "purchase", pug.String("productId", "sku_123"), pug.Float("amount", 29.99), pug.String("currency", "USD"), pug.WithLocation(pug.Location{Country: "DE", City: "Berlin"}), ) ``` | Field | Type | Notes | |---|---|---| | `Country` | `string` | ISO 3166-1 alpha-2 (`DE`). Case and surrounding spaces are normalized; a code Pug doesn't recognize is dropped. | | `Continent`, `Region`, `City`, `PostalCode`, `MetroCode` | `string` | Sent as given, trimmed. | | `Timezone` | `string` | IANA name (`Europe/Berlin`). | | `Coordinates` | `*pug.Coordinates` | `Latitude` and `Longitude` in decimal degrees, `-90` to `90` and `-180` to `180`. Sent only as a pair: one out of range drops both. | Each field becomes the matching `$`-prefixed [auto-property](/reference/auto-properties#geo-enrichment-cloudflare): `PostalCode` lands as `$postalCode`. It's the only way to set an auto-property from this SDK: properties become **custom** properties, and one whose key starts with `$` drops the event. An empty field is skipped silently. One that looks like a mistake - a country code Pug doesn't know, a coordinate out of range - is dropped with a warning and **the rest of the event still sends**. A location with no usable field at all logs a warning, and the event carries no geo. ## Identify and sessions Use a **stable, unique** external ID - your database user ID, not an email, which can change. Only the **first** identify after an anonymous session merges prior activity; the same external ID always resolves to the same profile, and traits are merged server-side, never removed. ```go // On the first identify, pass the client's anonymous ID to merge its prior anonymous activity. client.Identify("user-123", pug.Email("user@example.com"), pug.String("plan", "pro"), pug.WithAnonymousID("anon-abc123"), ) ``` `client.Identify(externalID, opts...)` **never fails** and returns at once: identifies are queued and sent in batches like events, and what can't be delivered goes to `OnError` in `lost.Identifies`. A read straight after an identify may not see it yet. Traits are the same typed fields as properties, or a `pug.Traits` map for keys known only at run time. Named traits write the keys the dashboard reads, compile only in `Identify`, and are omitted when empty: | Named trait | Key | |-------------|-----| | `pug.Name(v)` | `name` | | `pug.FirstName(v)` | `firstName` - with `lastName`, the dashboard composes a display name when `name` is unset | | `pug.LastName(v)` | `lastName` | | `pug.Email(v)` | `email` | | `pug.Avatar(v)` | `avatar` - the dashboard shows only an absolute https URL | Traits must be JSON-serializable, and travel as a protobuf `Struct`: a `pug.Time` trait arrives as an RFC 3339 string, a `pug.Duration` as `"1.5s"`, and every number as a double, so an integer past 2^53 arrives rounded. A `time.Duration` in a `pug.Traits` map, though, arrives as a number of nanoseconds. A `NaN` or `±Inf` trait is skipped with a warning and the rest still goes out. Traits that won't serialize, an `externalID` that is empty or starts with the reserved `cookieless-` prefix, and an identify over 900 KiB are logged and nothing is sent. Pass `pug.WithAnonymousID(id)` (must start with `anon-`) on the first identify to merge a client's prior anonymous activity into the profile, and `pug.WithDeviceID(id)` to attach a device. There is no `Reset` or `Rotate`. ### Sessions The client uses one session ID for its lifetime; override it per call with `pug.WithSessionID(id)`. ## Auto-tracking There is no auto-tracking: you send every event with `client.Track`. The server adds no geo or user agent to these events, so pass the visitor's [location](#visitor-location) yourself. ## Consent and privacy The Go SDK has no consent gate and no redaction hooks: respect the visitor's consent choice before you call `Track`, and keep PII out of the properties you pass. ## Server-side reads The private key also authorizes **reads** - the insights, profiles and activity data the dashboard shows. Reads **return a [`*pug.Error`](#errors)** and are never retried. Ingestion (`Track` / `Identify`) still never fails. ```go import ( commonv1 "github.com/pug-sh/sdk-go/gen/common/v1" insightsv1 "github.com/pug-sh/sdk-go/gen/shared/insights/v1" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) // Look up a profile by your external ID. profile, err := client.Profiles.GetByExternalID(ctx, "user-123") // Auto-paginating: ranges over every matching profile; an error ends the loop. for p, err := range client.Profiles.List(ctx, nil) { if err != nil { return err } fmt.Println(p.GetExternalId()) } // Run an insights query - the same spec the dashboard uses. now := time.Now() result, err := client.Insights.Query(ctx, &insightsv1.QueryRequest{ Spec: &insightsv1.InsightQuerySpec{ InsightType: insightsv1.InsightType_INSIGHT_TYPE_TRENDS.Enum(), Events: []*insightsv1.EventQuery{{Event: &commonv1.EventFilter{Kind: proto.String("order.completed")}}}, }, TimeRange: &commonv1.TimeRange{From: timestamppb.New(now.AddDate(0, 0, -30)), To: timestamppb.New(now)}, Granularity: insightsv1.Granularity_GRANULARITY_DAY.Enum(), }) ``` | Namespace | Methods | |-----------|---------| | `client.Profiles` | `Get(ctx, id, opts...)`, `GetByExternalID(ctx, externalID, opts...)`, `Delete(ctx, id)`, `List(ctx, req)`: an auto-paginating `iter.Seq2` | | `client.Activity` | `Feed`, `EventExplorer`, `Heatmap`, `ProfileSessions`, `ProfileStats`, `FilterSchema`, `PropertyValues` | | `client.Insights` | `Query`, `SegmentUsers`, `FilterSchema`, `PropertyValues` | Requests and responses are the generated protobuf types under `github.com/pug-sh/sdk-go/gen` - `shared/insights/v1`, `shared/activity/v1`, `shared/profiles/v1` and `common/v1` - whose optional fields take pointers (`proto.String`, `proto.Bool`) and whose getters, such as `p.GetExternalId()`, are nil-safe. `Profiles.Get` and `GetByExternalID` return the profile itself. `List` takes `nil` to list every profile. The whole iteration is one streamed request, so without a deadline on `ctx` it is bounded by `Timeout`; give a long listing a `ctx` with more time. Property names in reads are the stored ones, as you tracked them. Reads leave out traffic tagged as a bot at ingest: web-SDK events from crawler user agents and datacenter networks. Events from this SDK are never tagged. To count bot traffic, pass `pug.IncludeBots()` to `Profiles.Get` and `GetByExternalID`, or set `IncludeBots` in the request for `Profiles.List`, `Insights.Query` (on its `Spec`) and the activity `Feed`, `EventExplorer`, `Heatmap`, `ProfileSessions` and `ProfileStats`: ```go profile, err := client.Profiles.GetByExternalID(ctx, "user-123", pug.IncludeBots()) sessions, err := client.Activity.ProfileSessions(ctx, &activityv1.GetProfileSessionsRequest{ DistinctId: proto.String("user-123"), IncludeBots: proto.Bool(true), }) ``` The request and response shapes match the `shared.*` Connect services - see the [API reference](/api) for field-by-field schemas. From a backend without an SDK, call those services directly with your private key (see [Authentication](/get-started/authentication)). ### Errors A `*pug.Error` carries the Connect `Code` and `Message` and wraps the underlying error. `errors.Is` matches it to the sentinel for its code - `pug.ErrNotFound`, `pug.ErrUnauthenticated`, `pug.ErrUnavailable` and so on, one per Connect code (see the [error model](/api#error-model)). `Code` is zero when the failure didn't come from the RPC layer, and then it matches none: ```go profile, err := client.Profiles.GetByExternalID(ctx, "user-123") if errors.Is(err, pug.ErrNotFound) { // no profile with that external ID } var perr *pug.Error if errors.As(err, &perr) { log.Println(perr.Code, perr.Message) } ``` ## Upgrading **v0.0.1** is the first release of `github.com/pug-sh/sdk-go`, so there is nothing to upgrade from yet. # HTTP API > Send events and identify users from any language by POSTing JSON to Pug's Connect API - no SDK required. Source: https://docs.pug.sh/sdks/http/ | Markdown: https://docs.pug.sh/sdks/http/index.md No SDK for your runtime? Anything that can POST JSON can send events and identify users. The [API reference](/api) has the full schemas. ## Setup Send requests to `https://api.pugs.dev`, or your self-hosted base URL (e.g. `http://localhost:3000`), with three headers: | Header | Value | |--------|-------| | `Content-Type` | `application/json` | | `Connect-Protocol-Version` | `1` | | `x-api-key` | Your **private key** (`prv_...`) from a backend, or your **public key** (`pub_...`) from the visitor's own device. The key decides what the server adds - see [Auto-tracking](#auto-tracking) | Keep the private key in an environment variable or a secret store, never in code shipped to a browser or app. A public key may go in an `api_key` query parameter instead of the header; a private key can't. Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in [Install with AI](/get-started/ai-setup). ```text Add Pug product analytics to this service by calling the HTTP API directly - there is no SDK for this runtime. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/http/index.md - request format, including worked examples - https://docs.pug.sh/api/events/index.md - the full event schema - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the service actually does: its routes or handlers, its main models, and the state changes that matter to the business. The events worth tracking are the moments the service exists to produce, not request logging. If you cannot state what this service is for in one sentence, keep reading. Then: 1. Write one small client that POSTs to /sdk.events.v1.EventsService/BatchCreate on the base URL, with the headers Content-Type: application/json, Connect-Protocol-Version: 1, and x-api-key set to the private key (prv_...) from an environment variable, never committed. 2. Wrap every custom property value in its typed form - stringValue, intValue (a JSON string), doubleValue, boolValue, timestampValue. This is the part that is most often wrong. Property keys must not start with a dollar sign, and the event kind may hold only ASCII letters, digits, _, . and -. 3. Send events in batches of at most 1000, and read "dropped" and "droppedByReason" on the response - a 200 does not mean every event landed. 4. Call it for the three or four actions you identified. Name events from the catalog before you invent one. All 127 well-known events are available over HTTP, and a well-known kind fills in the dashboards built on it, which a custom kind leaves empty. Nothing checks their properties - no compiler, and not the server, which stores what it is sent - so a misspelled name or a wrong type fails silently. Search the catalog for every action you are about to track, take property names and types from that page, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not. Do not invent fields that are not in the events schema above. When you are done, tell me in one sentence what you concluded this service does, then show me the client, the event names you chose, and the environment variables I need to set. ``` ## Track events Each event's **name** is its `kind`. Any name works without a schema; [well-known events](/reference/well-known-events) add typed properties and richer dashboards, but nothing checks their properties over HTTP. **Endpoint:** `POST /sdk.events.v1.EventsService/BatchCreate` ```json { "events": [ { "eventId": "01966b9e-1234-7abc-abcd-0123456789ab", "distinctId": "anon-abc123", "kind": "purchase", "sessionId": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "occurTime": "2026-06-05T10:00:00Z", "customProperties": { "productId": { "stringValue": "sku_123" }, "amount": { "doubleValue": 29.99 }, "currency": { "stringValue": "USD" } }, "autoProperties": {} } ] } ``` Wrap every property value in a typed object: | Type | JSON shape | Notes | |------|-----------|-------| | String | `{ "stringValue": "hello" }` | At most 1024 characters | | Integer | `{ "intValue": "42" }` | int64, as a JSON string or a whole number | | Double | `{ "doubleValue": 3.14 }` | Must be finite | | Boolean | `{ "boolValue": true }` | | | Timestamp | `{ "timestampValue": "2026-06-05T10:00:00Z" }` | RFC 3339 | Requests must also pass the [validation rules](#errors). The response is `{ "accepted": , "dropped": }`: `dropped` counts [cookieless](#consent-and-privacy) events the server couldn't derive an identity for, and `droppedByReason` says why, so a 200 doesn't mean every event landed. The [Events API reference](/api/events) has the full schema and the drop reasons. ## Identify and sessions Use a **stable, unique** external ID - your database user ID, not an email, which can change. An identify merges a user's prior anonymous activity only when it carries their `anonymousId`, so send it on the first identify after an anonymous session; the same external ID always resolves to the same profile, and traits are merged server-side, never removed. **Endpoint:** `POST /sdk.profiles.v1.ProfilesSDKService/Identify` ```json { "externalId": "user-123", "traits": { "email": "user@example.com", "plan": "pro", "seats": 5 }, "anonymousId": "anon-abc123" } ``` | Field | JSON name | Required | Description | |-------|-----------|----------|-------------| | `external_id` | `externalId` | Yes | Stable user identifier; must not start with `cookieless-` | | `traits` | `traits` | No | Profile properties; shallow-merged on conflict | | `anonymous_id` | `anonymousId` | No | The `distinctId` the user's anonymous events carried; must start with `anon-` | | `device_id` | `deviceId` | No | Device to assign (the Flutter SDK sends one, the Android and iOS SDKs don't; omit for web) | > **traits is plain JSON, not PropertyValue-wrapped** > > Unlike event `customProperties`, `traits` is a `google.protobuf.Struct`: pass > bare JSON values (`"plan": "pro"`, `"seats": 5`). A wrapped value is stored as a > nested object. The response is `{}`; the identify is applied asynchronously, so a read straight after it may not see it yet. You set each event's `distinctId` yourself: the anonymous ID before identify, your external ID after. [`BatchIdentify`](/api/profiles#batchidentify) sends up to 1000 identifies in one request. ### Sessions Each event's `sessionId` is a UUID you choose, grouping events in a visit; the server uses it as sent. A [cookieless](#consent-and-privacy) event omits it, and the server stitches one instead, closed after 30 minutes of inactivity. ## Auto-tracking There is no auto-tracking: you send every event yourself. On a public-key request the server derives geo (`$country`, `$city`, ...) and user-agent properties (`$browser`, `$os`, ...) from the request, so from a backend they describe your server, not the visitor. On a private-key request it derives neither and keeps those you send in `autoProperties`, so forward the visitor's location there, with `$country` as ISO 3166-1 alpha-2 ([Auto-properties](/reference/auto-properties#geo-enrichment-cloudflare)). Either way `$ip` is stripped rather than geolocated, and any server-only property you send (`$bot`, `$bot_reason`, `$bot_score`, `$verified_bot`, `$channel`, `$referrerDomain`) is dropped. ## Consent and privacy There is no consent gate and no redaction: respect the visitor's consent choice before you send, and keep PII out of the properties. For a visitor who hasn't consented, set `"cookieless": true` and omit `distinctId` and `sessionId`; the server derives a daily-rotating identity from the request's IP address and `User-Agent` ([Cookieless events](/api/events#cookieless-events)). Send these from the visitor's own device: from your backend, every visitor gets the same identity. ## Errors Errors use Connect's HTTP status codes, with a JSON body naming the code and the rule broken (see the [error model](/api#error-model)): ```json { "code": "invalid_argument", "message": "validation error: events[0].kind: does not match regex pattern `^[a-zA-Z0-9_.-]+$`" } ``` | HTTP status | Connect code | Meaning | |-------------|--------------|---------| | 400 | `invalid_argument` | The request was malformed or broke a rule below, and nothing in it was stored. Fix it rather than retry | | 401 | `unauthenticated` | Missing or invalid key, or a private key in the `api_key` query parameter | | 409 | `aborted` | An identical batch is still being stored: retry | | 429 | `resource_exhausted` | The body is over 8 MiB, after decompression: split the batch | | 500 | `internal` | Server error: retry with backoff | | 503 | `unavailable` | The key couldn't be checked: retry with backoff | Resend the same events on a retry, with the same `eventId` and `occurTime`, so any stored before the error are deduplicated rather than counted twice. **Validation rules:** | Rule | Detail | |------|--------| | Batch | At most 1000 events, no two with the same `eventId` | | `eventId` | Required, a UUID | | `distinctId`, `sessionId` | Required unless `cookieless` is `true`, then omitted. `sessionId` is a UUID, and `distinctId` must not start with `cookieless-` | | `kind` | Required; only ASCII letters, digits, `_`, `.` and `-` | | `occurTime` | Required, RFC 3339 with `Z` or an offset | | `customProperties` keys | Must **not** start with `$` | | `autoProperties` keys | Must start with `$` | | Property values | Exactly one typed field each, within the [limits above](#track-events) | | Unknown fields | Ignored, not rejected: a misspelled name such as `customProps` loses its data silently | ## Examples ### cURL ```bash curl -X POST https://api.pugs.dev/sdk.events.v1.EventsService/BatchCreate \ -H 'Content-Type: application/json' \ -H 'Connect-Protocol-Version: 1' \ -H "x-api-key: $PUG_PRIVATE_KEY" \ -d '{ "events": [{ "eventId": "01966b9e-1234-7abc-abcd-0123456789ab", "distinctId": "anon-abc123", "kind": "page_view", "sessionId": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "occurTime": "2026-06-05T10:00:00Z", "customProperties": { "path": { "stringValue": "/pricing" } }, "autoProperties": {} }] }' ``` ### Python ```python import os import uuid from datetime import datetime, timezone import requests API_KEY = os.environ["PUG_PRIVATE_KEY"] BASE_URL = "https://api.pugs.dev" def send_event(distinct_id, kind, session_id, custom_props): event = { "eventId": str(uuid.uuid4()), # swap for uuidv7() if available "distinctId": distinct_id, "kind": kind, "sessionId": session_id, "occurTime": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "customProperties": custom_props, "autoProperties": {}, } resp = requests.post( f"{BASE_URL}/sdk.events.v1.EventsService/BatchCreate", headers={ "Content-Type": "application/json", "Connect-Protocol-Version": "1", "x-api-key": API_KEY, }, json={"events": [event]}, timeout=5, ) resp.raise_for_status() return resp.json() result = send_event( "anon-abc123", "signup", "f47ac10b-58cc-4372-a567-0e02b2c3d479", {"plan": {"stringValue": "pro"}, "seats": {"intValue": "5"}}, # int64 as a JSON string ) print(result) # {"accepted": 1, "dropped": 0} ``` ### Go A Go backend can use the [Go SDK](/sdks/go) instead. Over raw HTTP: ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" "os" "time" "github.com/google/uuid" ) const baseURL = "https://api.pugs.dev" // propertyValue is the Connect-JSON encoding of the protobuf oneof. type propertyValue struct { StringValue *string `json:"stringValue,omitempty"` IntValue *string `json:"intValue,omitempty"` // int64 as a JSON string DoubleValue *float64 `json:"doubleValue,omitempty"` BoolValue *bool `json:"boolValue,omitempty"` TimestampValue *string `json:"timestampValue,omitempty"` // RFC 3339 } func strVal(s string) propertyValue { return propertyValue{StringValue: &s} } type event struct { EventID string `json:"eventId"` DistinctID string `json:"distinctId"` Kind string `json:"kind"` SessionID string `json:"sessionId"` OccurTime string `json:"occurTime"` CustomProperties map[string]propertyValue `json:"customProperties"` AutoProperties map[string]propertyValue `json:"autoProperties"` } func main() { body, _ := json.Marshal(map[string]any{ "events": []event{{ EventID: uuid.New().String(), DistinctID: "anon-abc123", Kind: "signup", SessionID: "f47ac10b-58cc-4372-a567-0e02b2c3d479", OccurTime: time.Now().UTC().Format(time.RFC3339), CustomProperties: map[string]propertyValue{"plan": strVal("pro")}, AutoProperties: map[string]propertyValue{}, }}, }) req, _ := http.NewRequest(http.MethodPost, baseURL+"/sdk.events.v1.EventsService/BatchCreate", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Connect-Protocol-Version", "1") req.Header.Set("x-api-key", os.Getenv("PUG_PRIVATE_KEY")) resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println("status:", resp.Status) } ``` # iOS SDK > Typed event tracking, screen and lifecycle auto-tracking, identity and consent for native iOS and iPadOS apps in Swift, with the Pug Swift package. Source: https://docs.pug.sh/sdks/ios/ | Markdown: https://docs.pug.sh/sdks/ios/index.md The iOS SDK (`Pug`, from `github.com/pug-sh/sdk-ios`) captures events from native iOS and iPadOS apps, in Swift. It authenticates with your **public key** (`pub_...`), which is write-scoped (events + identify) and safe to ship in the app, and follows the [same model as every Pug SDK](/sdks): initialize once, track events, identify users, reset on sign-out. ## Install The SDK is a Swift package, which Swift Package Manager resolves from its Git tags; there is no CocoaPods or Carthage install. In Xcode, choose **File > Add Package Dependencies**, enter `https://github.com/pug-sh/sdk-ios` and add the `Pug` library to your app's target. In a `Package.swift`: ```swift title="Package.swift" dependencies: [ .package(url: "https://github.com/pug-sh/sdk-ios.git", from: "0.1.1"), ], targets: [ .target(name: "YourApp", dependencies: [.product(name: "Pug", package: "sdk-ios")]), ], ``` [View `pug-sh/sdk-ios` on GitHub](https://github.com/pug-sh/sdk-ios) | Requirement | Minimum | |-------------|---------| | iOS and iPadOS | 15 | | Mac Catalyst | 15 | | Xcode | 16 | iPhone and iPad apps running on a Mac are covered too. The SDK is written in Swift 6 and works from apps in the Swift 5 language mode; it has no Objective-C API, so Objective-C code calls it through a Swift wrapper of your own. It has no runtime dependencies (Foundation, UIKit, SwiftUI, Network and `os` only), ships a [privacy manifest](#privacy-manifest), and needs no permission, entitlement or App Tracking Transparency prompt. To verify, run the app with a minimal [`Pug.initialize`](#initialize) and `debug = true`: an `app_open` and a `screen_view` appear in **Live** within a few seconds (in a SwiftUI app, the `screen_view` needs a [named screen](#auto-tracking)), and Xcode's console shows each event as it is tracked and sent, under the subsystem `sh.pug`. Working with a coding agent? Paste this instead: it points the agent at the markdown copy of this page. More in [Install with AI](/get-started/ai-setup). ```text Add Pug product analytics to this iOS app. Read these first. They are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/ios/index.md: SDK reference - https://docs.pug.sh/reference/well-known-events/index.md: the well-known event catalog Then read this codebase before you write anything, and work out what the app actually does: its view controllers or SwiftUI views and how a user moves between them, its main models, and the handful of things a user opens the app to complete. The events worth tracking are the moments the app exists to produce (an account created, an order placed, a workout finished), not every tap. If you cannot state the core action in one sentence, keep reading. Then: 1. Add the Swift package https://github.com/pug-sh/sdk-ios, from 0.1.0, with Swift Package Manager, and link its Pug library to the app target. It needs iOS 15 and Xcode 16, and there is no CocoaPods or Carthage install. 2. Call Pug.initialize(projectId:options:) once: in the App's init() in a SwiftUI app, or in application(_:didFinishLaunchingWithOptions:) in a UIKit one, so the SDK sees each launch's first screen. It throws Pug.ConfigurationError for a bad value, so wrap it in do/catch with an assertionFailure in the catch. 3. Keep the project ID and public key (pub_...) out of source: set them in an xcconfig file that Git ignores and read them through Info.plist. A private key (prv_...) must never ship in the app. 4. Leave auto-tracking on: it already tracks app_open, app_close, app_install, app_update and a screen_view for each of the app's own view controllers. SwiftUI views are not view controllers, so put .pugScreen("Name") on the view each SwiftUI screen shows, inside its NavigationStack, or those screens send no screen_view. 5. Add tracking for the three or four actions you identified: the ones someone would look at in a weekly review. 6. If this app has authentication, call Pug.identify() after sign-in and Pug.reset() on sign-out. Name events from the catalog before you invent one. Swift gets a generated method with labeled arguments for each well-known event the SDK does not track itself, such as Pug.track.purchase(productId: ..., amount: ...), so the compiler checks the properties for you, and the dashboards those events drive stay empty for a custom name. Reach for those first, search the catalog for every action you are about to track, and pass schema-external properties through extras. Durations are TimeInterval seconds. Use Pug.track(_:properties:) with a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not. iOS consent has two states, starts granted and is saved across launches, which is not the same as the Web SDK: check the consent section before you add a banner. It is not App Tracking Transparency, which Pug does not need, so do not add an ATT prompt for it. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this app does, then list the files you changed, the event names you chose, and the build settings I need to set. ``` ## Initialize Call `Pug.initialize` **once**, with your project ID and public key: every other call needs it first. Find your project ID in the dashboard URL (`/p/`), and your public key on your project **Overview** or under **Settings > API Keys**. In a SwiftUI app, call it in your `App`'s `init()`: ```swift import Pug import SwiftUI @main struct AcmeApp: App { init() { do { try Pug.initialize(projectId: "YOUR_PROJECT_ID", options: Pug.Options(apiKey: "pub_your_public_key")) } catch { assertionFailure("Pug was not started: \(error)") } } var body: some Scene { WindowGroup { ContentView() } } } ``` In a UIKit app, the same `do`/`catch` goes in `application(_:didFinishLaunchingWithOptions:)`. Initialized in either place, before the first scene connects, the SDK sees the first screen and the `app_open` of each launch; initialized later, it tracks `app_open` at once and screens from the next one that appears. `Pug.initialize` **throws `Pug.ConfigurationError`** for a blank project ID; a key that isn't a public key (`pub_...`), or holds a space or any character outside printable ASCII, such as a trailing newline; or an endpoint that isn't an http(s) URL with a host and no query or fragment. The `assertionFailure` stops a debug build on a bad value, and a release build runs on without analytics. `Pug.initialize` does no disk or network work on the calling thread, so it's safe on the main thread at launch. A second `Pug.initialize` is ignored with a warning until `Pug.destroy()`, and so is any call made before `Pug.initialize`. Every other call returns at once, can be made from any thread, and **never throws**: calls run in order on one background thread, and failures are logged. Options are properties of `Pug.Options`, each set on its own; the ones left out keep their defaults. ```swift var options = Pug.Options(apiKey: "pub_your_public_key") #if DEBUG options.debug = true #endif options.batchMaxSize = 20 options.sessionIdleTimeout = 15 * 60 options.defaultTrackingConsent = .denied try Pug.initialize(projectId: "YOUR_PROJECT_ID", options: options) ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `endpoint` | `URL` | `https://api.pugs.dev` | API base URL: set it only when [self-hosting](/self-hosting/connect-sdks#ios). An `http` URL needs an App Transport Security exception. | | `debug` | `Bool` | `false` | Log debug messages: each event tracked, sent or dropped, and why. Warnings and errors are logged regardless. | | `dryRun` | `Bool` | `false` | Build and log events without sending anything; `identify` isn't sent either. Consent is unaffected. | | `batchMaxSize` | `Int` | `10` | Events per request, at most 1000: a batch goes out once this many are queued, or `batchMaxWait` after the first of them. | | `batchMaxWait` | `TimeInterval` | `5` | Seconds the first queued event waits for a full batch. | | `batchMaxQueueSize` | `Int` | `1000` | Undelivered events to keep; beyond this, the oldest is dropped. | | `sessionIdleTimeout` | `TimeInterval` | `1800` (30 min) | A session ends after this many seconds without events. | | `sessionMaxDuration` | `TimeInterval` | `86400` (24 h) | A session ends this many seconds after it began. | | `defaultTrackingConsent` | `Pug.TrackingConsent` | `.granted` | Consent until the user chooses. See [Tracking consent](#tracking-consent). | | `persistTrackingConsent` | `Bool` | `true` | Save the user's choice for the next launch. See [Tracking consent](#tracking-consent). | | `autoOpenCloseEvents` | `Bool` | `true` | Track `app_open` and `app_close`. See [Auto-tracking](#auto-tracking). | | `autoScreenViews` | `Bool` | `true` | Track a `screen_view` each time one of your view controllers appears on a different screen. | | `autoInstallEvents` | `Bool` | `true` | Track `app_install` and `app_update`. | | `logger` | `(any Pug.Logger)?` | the system log | Receive the SDK's messages instead. | | `storage` | `(any Pug.Storage)?` | files | Keep the SDK's state somewhere else. `Pug.MemoryStorage()` keeps nothing on the device. | Durations are `TimeInterval` seconds. Nothing in `Pug.Options` throws: a number out of range is logged and replaced by its default, and a `batchMaxSize` above 1000 is capped. By default the SDK logs to the system log under the subsystem `sh.pug`, category `Pug`, which Xcode's console and Console.app show. A `Pug.Logger` implements `debug(_:)`, `warning(_:error:)` and `error(_:error:)`, is called from any thread, and gets messages that never contain property values or traits. ### Delivery and storage Events are sent in batches, one request at a time. A request that fails for a reason that may pass (no network, a timeout, a server error, a captive portal) is retried with exponential backoff, from `batchMaxWait` (at least a second) up to five minutes; one the server rejects for good is dropped and logged as an error. Retries reuse the event IDs, which the server deduplicates. Requests are capped at 4 MiB, and an event over that is dropped when tracked. When the app enters the background, the SDK sends everything queued and writes its state to disk, whatever `autoOpenCloseEvents` says, in a background task that ends once the sends settle, since iOS may suspend the app from then on. A send that suspension cuts short is retried. Undelivered events, identity and consent live in files under the app's Application Support directory, in `/pug`, which is excluded from backups: they survive restarts but aren't restored onto another device. Deleting the app deletes them, so a reinstall is a new install with a new anonymous ID. Writes are grouped and land within a second, and at once on `Pug.flush()` and `Pug.destroy()`. If a custom `storage` throws, the SDK falls back to memory until `Pug.destroy()` or the process ends; throw from `string(forKey:)` when a value may exist but can't be read, since `nil` starts a new identity. The files can be read once the device has been unlocked after a restart. When iOS launches the app in the background before that, the SDK starts at the unlock, and the calls made meanwhile run then. **App extensions**, such as a widget or a share extension, can use the SDK too: `track`, `identify` and the rest work as in the app. An extension tracks no automatic events, and since it has a container of its own, it has its own files and anonymous ID. ## Track events The first argument is the event **name** (its `kind`). Any name works without a schema; [well-known events](/reference/well-known-events) add typed properties and richer dashboards. ```swift // Custom event: any name Pug.track("button_clicked", properties: ["label": "Sign up", "screen": "pricing"]) // Typed well-known event: checked at compile time Pug.track.purchase(productId: "sku-1", amount: 99.50, currency: "USD") ``` A kind may contain letters, digits, `_`, `.` and `-`; any other kind is dropped with a warning. Properties are read during the call. A key starting with `$` is reserved for [auto-properties](/reference/auto-properties) and dropped with a warning: the property, not the event. **Property values** map by type: | Value | Sent as | |-------|---------| | `String`, `Substring`, `Character`, an enum with `String` raw values (its raw value) | string, cut to 1024 UTF-8 bytes | | `Bool` | bool | | `Int`, `Int64`, `UInt64` and the other integer types | int; one beyond the signed 64-bit range as a string of its digits | | `Double`, `Float`, `CGFloat`, `Decimal` | double; NaN and infinities are dropped | | `NSNumber` | by what it holds: bool, int or double | | `Date` | timestamp | | arrays, dictionaries and sets | JSON string, cut to 1024 UTF-8 bytes | | `nil`, `NSNull` | omitted | | anything else, such as `UUID`, `URL` or another enum | its `String(describing:)`, cut to 1024 UTF-8 bytes | `Pug.TrackOptions` (on `Pug.track` and every typed method): | Option | Type | Default | Description | |--------|------|---------|-------------| | `immediate` | `Bool` | `false` | Send the event on its own right away instead of with the next batch. If the send fails for a reason that may pass, the event joins the queue. | | `timestamp` | `Date?` | time of the call | When the event happened, for an event recorded after the fact. A time before 1970 or after the year 9999 is logged and replaced by the time of the call. | ```swift Pug.track("order_completed", properties: ["orderId": "o-1"], options: Pug.TrackOptions(immediate: true)) ``` `Pug.track` is also a namespace with a generated method per well-known event, 118 of them: every event in the catalog but the four web-only ones (`page_view`, `click`, `rage_click`, `dead_click`) and the five the SDK [tracks itself](#auto-tracking). Each takes the event's properties as labeled arguments (required ones without a default, optional ones defaulting to `nil`), then `extras:`, for properties the schema doesn't define, and `options:`. ```swift Pug.track.search(query: "trail shoes") Pug.track.videoPlay(videoId: "v1", position: 1.5) Pug.track.addToCart( productId: "sku-1", extras: ["coupon": "SPRING"], options: Pug.TrackOptions(immediate: true) ) Pug.track.signup() ``` An extra named like an argument is dropped with a warning when that argument is set. Durations are `TimeInterval` seconds, sent as text rounded to the millisecond: `position: 1.5` sends `position` as `"1.5s"`. Values are sent as given: ranges and patterns in the schemas aren't checked on the device. The kinds are constants in `Pug.Events` (`Pug.Events.addToCart` is `"add_to_cart"`). `Pug.track(_:properties:options:)` works for a well-known kind too, and a whole number for a decimal property is sent as a decimal (`"price": 10` arrives as `10.0`), so both paths fill the same column. With the automatic events turned off, `Pug.track(Pug.Events.appOpen)` and the like still work. ## Identify and sessions Events accumulate against an anonymous ID until you `Pug.identify` the user on sign-in, which merges that history into a known profile; call `Pug.reset()` on sign-out. Use a **stable, unique** external ID: your database user ID, not an email, which can change. Only the **first** identify after an anonymous session merges prior activity; the same external ID always resolves to the same profile, and traits are merged server-side, never removed. ```swift // On sign-in Pug.identify("user-123", traits: ["email": "user@example.com", "plan": "pro"]) // On sign-out Pug.reset() // New session ID, identity kept Pug.rotateSession() ``` Once the server accepts an `identify`, events carry the external ID as their distinct ID. A failed one is logged and not retried, so events keep their current distinct ID until a later call succeeds. Traits may nest dictionaries and arrays. A blank ID, or one starting with the reserved `cookieless-` prefix, is rejected with an error in the log. `reset()` forgets the external ID and starts a new anonymous ID and session; it does **not** delete the profile. Events queued before it keep the user they were tracked for, and are sent without waiting for the next batch. `Pug.flush()` sends what's queued now and writes the SDK's state to disk; `Pug.destroy()` stops the SDK after a final flush of at most ten seconds, keeping identity, saved consent and undelivered events for the next `Pug.initialize`, which waits for the teardown to finish. | Function | Forgets the external ID | New anonymous ID | New session ID | |----------|-------------------------|------------------|----------------| | `rotateSession()` | No | No | Yes | | `reset()` | Yes | Yes | Yes | ### Sessions Sessions group events within a single visit, ending at the idle or max-duration timeout: 1. **First event** (session ID created) 2. **Events within timeout** (same session ID) 3. **Idle past timeout** (session expires) 4. **Next event** (new session ID (identity kept)) The session survives restarts: a launch within the timeouts continues it. Set them, in seconds, with the `sessionIdleTimeout` and `sessionMaxDuration` [options](#initialize). ## Auto-tracking By default, the SDK tracks these events itself: | Event | When | Option | |-------|------|--------| | `app_open` | The app comes to the foreground: it becomes active or enters the foreground, whichever comes first. | `autoOpenCloseEvents` | | `app_close` | The app enters the background. Control Center, a call or a system alert in front of the app is no exit. Sent at once, not batched. | `autoOpenCloseEvents` | | `screen_view` | One of your view controllers appears on a different screen: `screenName` is its type's name, `screenClass` the module-qualified one. | `autoScreenViews` | | `app_install` | The first launch with the SDK on this device, with `appVersion` and `installSource`. | `autoInstallEvents` | | `app_update` | The first launch of a new app version, with `appVersion` and `previousVersion`. | `autoInstallEvents` | Every event also carries the SDK's [auto-properties](/reference/auto-properties#sdk-set-properties-ios): device, OS, app version, screen size, locale, time zone, network type and the current screen, and the server adds geo. Reading the network type needs no permission, and the device name is never collected. **Screens** are view controllers until you name them. The ones tracked are your app's own, from its executable or the frameworks it embeds, whose parent is none or a navigation, tab bar, split or page view controller. Those containers, UIKit's and SwiftUI's own view controllers (alerts and `UIHostingController` among them) and the children of your own containers are skipped. A view controller that reappears with no other screen in between, as after a share sheet it presented, isn't tracked again. Several windows or scenes count as one app. **SwiftUI views aren't view controllers**, so a SwiftUI-only app gets screen views only for the screens it names. Name one with `pugScreen`, on the view the screen shows, inside its `NavigationStack`: ```swift NavigationStack { List(products) { product in NavigationLink(product.name) { ProductView(product: product) } } .pugScreen("Products") } ``` It's tracked as a view controller is, with `autoScreenViews` off too: a `screen_view` with its `screenName` and no `screenClass` when it appears on a different screen, and again when it comes back after another. Dismissing a sheet makes the screen beneath it current again, and a new name is a new screen. For a screen that is neither, such as a level in a game, call `Pug.screen`: ```swift Pug.screen("Level 3") ``` It tracks a `screen_view` unless that screen is already the current one. Every event after a screen carries it as `$url` and the one before as `$referrer`. With `autoScreenViews` off, view controllers are left alone entirely, so the screens are only the ones you name. **Installs and updates** are decided once at launch, from the SDK's own state on the device: `app_install` when the SDK has never run there, and `app_update`, carrying `previousVersion`, on the first launch after `CFBundleShortVersionString` changes. An app without a `CFBundleShortVersionString` reports neither. `installSource` is `com.apple` for the App Store, `com.apple.testflight` for TestFlight and for the builds Xcode installs, which have the same sandbox receipt, and `com.apple.simulator` on a simulator. **Adding the SDK to an app that is already out** reports each existing user's first launch with it as an `app_install`. Turning `autoInstallEvents` on later, in an app already shipping the SDK, doesn't, and neither does a destroy-and-initialize cycle. **Background launches** track no `app_open`, `app_close` or `screen_view`: an app that iOS launches in the background, as for a background fetch or a location update, tracks them from when the user opens it. The events you track meanwhile are sent as usual. ## Consent and privacy > **Not the Web SDK's default** > > **iOS defaults to granted** and stores identity from the first event. The > [Web SDK](/sdks/web#tracking-consent) defaults to `'cookieless'`, which stores > nothing on the device; the iOS SDK has no cookieless mode. ### Tracking consent Consent has two states, `.granted` and `.denied` (`Pug.TrackingConsent`), and starts granted. To wait for the user's choice, start denied, and show your banner while the choice is still pending: ```swift var options = Pug.Options(apiKey: "pub_your_public_key") options.defaultTrackingConsent = .denied try Pug.initialize(projectId: "YOUR_PROJECT_ID", options: options) Pug.whenConsentReady { if Pug.isConsentPending { showConsentBanner() } } Pug.optInTracking() // the user accepted Pug.optOutTracking() // the user declined ``` The choice is saved, so the banner shows only until the user answers, and an opt-out made in your settings screen still holds after a restart. While consent is denied, events and `identify` are dropped, not kept for later. Opting out drops queued events unsent and removes the stored identity; opting in again starts a new anonymous identity. When the user opts in, the SDK tracks what consent held back: an `app_install` or `app_update` it couldn't track at launch and, if the app is in the foreground, `app_open` and a `screen_view` of the current screen. The consent getters never wait. Right after `Pug.initialize`, while the SDK reads the saved choice on its own thread, they answer "not known yet". `Pug.whenConsentReady { ... }` runs its closure on the main thread as soon as they answer for this user, or on the main thread's next turn if they already do. | Property | Returns | Not known yet | |----------|---------|---------------| | `Pug.trackingConsent` | The consent in effect | `nil` | | `Pug.isTrackingEnabled` | Whether consent is granted | `false` | | `Pug.isConsentPending` | Whether the user has yet to choose | `true` | If your app keeps the choice itself and calls `optInTracking()` or `optOutTracking()` on every launch, set `persistTrackingConsent = false`: the choice then lasts until `Pug.destroy()` or the process ends. This consent is your app's own choice about analytics, as for a GDPR banner. It isn't App Tracking Transparency, which Pug doesn't need: see [Privacy manifest](#privacy-manifest). ### Privacy manifest The SDK ships a privacy manifest (`PrivacyInfo.xcprivacy`), which Xcode adds to your app's privacy report. It declares the data the SDK collects for analytics, linked to the user and used for no tracking: product interaction (the events), the user ID that `identify` passes, and a device ID, the anonymous ID the SDK gives each install. The SDK calls none of the APIs that need a declared reason. It reads no advertising identifier, `identifierForVendor` or device name, and tracks no one across other companies' apps, so it needs no App Tracking Transparency prompt. Your App Store privacy answers still cover what your own events and traits carry, such as purchases or an email address. ### Redacting PII There's no device-side redaction and no `beforeSend` hook: keep PII out of the properties you pass to `Pug.track`. ## Upgrading 0.1.0 is the first release, so there is nothing to migrate yet. # Node SDK > Send events and read profiles, activity and insights from a Node.js backend with @pug-sh/node and a private key. Source: https://docs.pug.sh/sdks/node/ | Markdown: https://docs.pug.sh/sdks/node/index.md `@pug-sh/node` sends events from your Node.js backend **and** reads analytics back - profiles, activity and insights. It authenticates with your **private key** (`prv_...`), so it belongs on the server only. It follows the [same model as every Pug SDK](/sdks) with one exception: a server has no ambient user or session to reset, so you name the `distinctId` on each call instead. ## Install ```bash npm install @pug-sh/node # or: pnpm add @pug-sh/node | yarn add @pug-sh/node | bun add @pug-sh/node ``` [View `@pug-sh/node` on npm](https://www.npmjs.com/package/@pug-sh/node) The package is ESM-only - `require()` can't load it - and needs **Node.js 18+**. Import the `Pug` class: ```ts import { Pug, PugError } from '@pug-sh/node' ``` Keep the private key in an environment variable or a secret store, never in code shipped to a browser or app. Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in [Install with AI](/get-started/ai-setup). ```text Add Pug product analytics to this Node backend. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/node/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the service actually does: its routes or handlers, its main models, and the state changes that matter to the business. On a server the events worth tracking are the ones a browser cannot observe - a payment settling, a webhook arriving, a job finishing, a subscription lapsing - not request logging. If you cannot state what this service is for in one sentence, keep reading. Then: 1. Install @pug-sh/node. It is ESM and needs Node 18+. 2. Construct one Pug instance at boot and reuse it across requests - do not build one per request. Its apiKey is the private key (prv_...), read from an environment variable, and it must never be imported into client-side code. 3. Remember the argument order: pug.track(distinctId, kind, props?, options?). The distinctId comes first because a server has no ambient user - use our own user ID, or the anon-... ID forwarded from the client. 4. Add track calls for the three or four state changes you identified. 5. Call identify() when a user record is created or changes materially, not on every request. 6. Await pug.close() in the graceful-shutdown path so queued events and identifies flush, and wire an onError handler so dropped events and identifies are logged rather than lost. Name events from the catalog before you invent one. The Node SDK checks 114 of the 127 well-known events against their schemas when track() runs, not at compile time: a property of the wrong type drops the whole event, and one named as the catalog spells it (product_id) rather than in camelCase (productId) is sent as a custom property instead. The ones a backend is placed to see are exactly the ones whose schemas are worth having - purchase, subscription_started, invoice_paid, payment_failed, order_refunded. Search the catalog for every action you are about to track, take property names - in camelCase - and types from that page, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not. There is no reset() or destroy() on the server SDK, and no immediate option on track - use flush(). Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this service does, then list the files you changed, the event names you chose, and the environment variables I need to set. ``` ## Initialize Construct a `Pug` instance **once** at boot with your private key - every other call needs it first. Private keys live under **Settings > API Keys**, but one is only shown when you [create it](/get-started/authentication) - if you don't have yours, issue a new one. ```ts import { Pug } from '@pug-sh/node' // Construct once at boot, reuse it across requests. const pug = new Pug({ apiKey: process.env.PUG_PRIVATE_KEY!, // prv_... - server-side only, never ship to a client }) ``` `new Pug(options)` **throws** if `apiKey` is missing or doesn't start with `prv_`; after that, ingestion never throws. | Option | Type | Default | Description | |--------|------|---------|-------------| | `apiKey` | `string` | **required** | Private key (`prv_...`), sent as `x-api-key`. | | `endpoint` | `string` | `https://api.pugs.dev` | Pug server origin; set it only when self-hosting. | | `batch` | `Partial` | `maxSize 100`, `maxWaitMs 5000`, `maxQueueSize 10000` | One queue each for events and identifies: items per request (capped at 1000), the longest an item waits before a send, and how many to hold before the oldest are dropped. | | `onError` | `OnError` | none | Dead-letter hook for events and identifies that couldn't be delivered, called as `(err, { events, identifies })`: a permanent send failure, a queue overflow, or what `close()` couldn't send. One of the two lists is always empty. | Call `await pug.close()` on graceful shutdown, or before a script exits, so nothing queued is lost: a pending send doesn't keep the process alive. See [`flush()` and `close()`](#track-events). ## Track events After the `distinctId`, the next argument is the event **name** (its `kind`). Any name works without a schema; [well-known events](/reference/well-known-events) add typed properties and richer dashboards. ```ts // distinctId (who the event is for) comes first - a server has no ambient user. pug.track('user-123', 'order.completed', { amount: 49, currency: 'USD' }) // Well-known events get typed, validated properties. pug.track('user-123', 'purchase', { productId: 'sku_123', amount: 29.99, currency: 'USD' }) ``` `pug.track(distinctId, kind, props?, options?)` takes the **`distinctId` first**: your external ID, or an `anon-...` ID forwarded from the client. It **never throws** and returns at once; events are validated, batched and sent in the background, and invalid input is logged and dropped. A kind may hold only ASCII letters, digits, `_`, `.` and `-`; anything else drops the event. There is no `immediate` option on the server - flush explicitly instead: ```ts await pug.flush() // send what's queued now, and wait for that attempt await pug.close() // drain on graceful shutdown so nothing queued is lost ``` Both cover events and identifies, and neither guarantees delivery: after `flush()` a transient failure re-queues for a later send, and by the time `close()` resolves, whatever it couldn't send has gone to `onError` and the log. After `close()`, `track()` and `identify()` calls are dropped with a warning. `track(distinctId, kind, props?, options?)` options: | Option | Type | Description | |--------|------|-------------| | `timestamp` | `number` | Override the event time, as **epoch milliseconds** (e.g. `Date.now()`). Anything but a whole number of milliseconds from 1970 to 9999 is ignored with a warning, and the event is sent at the current time. | | `sessionId` | `string` | A UUID to use as this event's session ID - otherwise the instance uses one for its lifetime. Anything but a UUID drops the event. | | `location` | `EventLocation` | Where the **visitor** is. Without it a server event carries no geo at all. See [Visitor location](#visitor-location). | **Property values** are JSON values: a safe integer is sent as an int and any other number as a double, a string is cut to 1024 bytes with a warning, an object or array becomes a JSON string, and `null` or `undefined` is omitted. A `Date` is sent as a timestamp and a `bigint` as an int, though TypeScript rejects both. `NaN`, `Infinity` and anything else that can't be sent are dropped with a warning - the property, not the event. A [well-known event](/reference/well-known-events)'s props are checked against its schema before the event is queued, under the fields' camelCase names (`productId`), not the catalog's `product_id`, which is sent as a custom property without a warning; an event missing a required field is dropped. The schema sets each field's type, so `amount: 10` is sent as a double. A wrong-typed value, or one failing a rule such as `currency` needing three uppercase letters, drops the **whole event**, and the log names the field (`quantity: expected int32, got string`). TypeScript doesn't catch a wrong type, since the call falls back to the signature for custom events. Keys outside the schema pass through as custom properties. Two field types take a particular shape: - **int64** fields such as `sizeBytes` take a safe integer. A string drops the event, and a `bigint` works but doesn't compile. - **Duration** fields such as `position` take `{ seconds, nanos }`, sent as a string like `"90.5s"`. `track()` logs and drops an event over 900 KiB, and one whose `distinctId` is empty or starts with `cookieless-`, a prefix the server reserves; it would reject the whole batch. ### Visitor location The server adds no geo to events sent with a private key: an event carries the `location` you give it (added in **0.0.6**), or none at all. ```ts pug.track('user-123', 'purchase', { productId: 'sku_123', amount: 29.99, currency: 'USD' }, { location: { country: 'DE', city: 'Berlin' } }) ``` | Field | Type | Notes | |---|---|---| | `country` | `string` | ISO 3166-1 alpha-2 (`DE`). Case and surrounding spaces are normalized; a code Pug doesn't recognize is dropped. | | `continent`, `region`, `city`, `postalCode`, `metroCode` | `string` | Sent as given, trimmed. | | `timezone` | `string` | IANA name (`Europe/Berlin`). | | `latitude`, `longitude` | `number` | Decimal degrees, `-90` to `90` and `-180` to `180`. Sent only as a pair: one without the other is dropped. | Each field becomes the matching `$`-prefixed [auto-property](/reference/auto-properties#geo-enrichment-cloudflare): `city` lands as `$city`. It's the only way to set an auto-property from this SDK: `props` become **custom** properties, and one whose key starts with `$` drops the event. A field that is absent, `null` or empty is skipped silently. One that looks like a mistake - unknown key, wrong type, a country code Pug doesn't know, a coordinate out of range - is dropped with a warning and **the rest of the event still sends**, and a location with nothing usable logs a warning. ## Identify and sessions Use a **stable, unique** external ID - your database user ID, not an email, which can change. Only the **first** identify after an anonymous session merges prior activity; the same external ID always resolves to the same profile, and traits are merged server-side, never removed. ```ts // On the first identify, pass the client's anonymous ID to merge its prior anonymous activity. pug.identify('user-123', { email: 'user@example.com', plan: 'pro' }, { anonymousId: 'anon-abc123', }) ``` `pug.identify(externalId, traits?, options?)` **never throws** and returns at once: identifies are queued and sent in batches like events, and what can't be delivered goes to `onError`. A read straight after an identify may not see it yet. `traits` must be a plain object: a string, array, `Date` or `Map` is logged and nothing is sent, as is an `externalId` that is empty or starts with the reserved `cookieless-` prefix, or an identify over 900 KiB. Traits travel as a protobuf `Struct`, where a `Date` value becomes an empty object and `undefined` or a `bigint` becomes `null`, overwriting the stored trait; TypeScript rejects all three. A `NaN` or `Infinity` trait is skipped with a warning, and the rest still goes out. Pass `{ anonymousId }` (must start with `anon-`) on the first identify to merge a client's prior anonymous activity into the profile, and `{ deviceId }` to attach a device. There is no `reset()` or `rotate()`. ### Sessions The SDK uses one session ID for the instance's lifetime; override it per call with `track(..., { sessionId })`. ## Auto-tracking There is no auto-tracking: you send every event with `pug.track()`. The server adds no geo or user agent to these events, so pass the visitor's [`location`](#visitor-location) yourself. ## Consent and privacy The Node SDK has no consent gate and no redaction hooks: respect the visitor's consent choice before you call `track()`, and keep PII out of the properties you pass. ## Server-side reads The private key also authorizes **reads** - the insights, profiles and activity data the dashboard shows. Reads **throw `PugError`** and are never retried. Ingestion (`track()` / `identify()`) still never throws. ```ts import { PugError } from '@pug-sh/node' try { // Look up a profile by your external ID. const profile = await pug.profiles.getByExternalId('user-123') // Auto-paginating async iterator over every matching profile. for await (const p of pug.profiles.list()) { console.log(p.externalId) } // Run an insights query - the same spec the dashboard uses. const result = await pug.insights.query({ /* spec, timeRange, granularity */ }) } catch (err) { // Reads throw; ingestion (track/identify) never does. if (err instanceof PugError) console.error(err.code, err.message) } ``` | Namespace | Methods | |-----------|---------| | `pug.profiles` | `get(id, opts?)`, `getByExternalId(externalId, opts?)`, `delete(id)`, `list(req?)`: an auto-paginating async iterator | | `pug.activity` | `feed`, `eventExplorer`, `heatmap`, `profileSessions`, `profileStats`, `filterSchema`, `propertyValues` | | `pug.insights` | `query`, `segmentUsers`, `filterSchema`, `propertyValues` | `profiles.get` and `getByExternalId` return the profile itself. Every read times out after 10 seconds, with no option to change it, and a `list()` loop is one streamed request: it throws once the whole loop, your loop body included, passes 10 seconds. A `PugError` carries the Connect `code` as a number, as in the `Code` enum from `@connectrpc/connect` (`5` is `not_found`, `4` is `deadline_exceeded`; see the [error model](/api#error-model)), and the underlying error as `cause`. Reads leave out traffic tagged as a bot at ingest: web-SDK events from crawler user agents and datacenter networks. Events from this SDK are never tagged. Set `includeBots: true` (**0.0.7+**) to count bot traffic - `profiles.get` and `getByExternalId` take it in their second argument, and `profiles.list`, `insights.query` (on its `spec`) and the activity `feed`, `eventExplorer`, `heatmap`, `profileSessions` and `profileStats` take it in the request: ```ts const profile = await pug.profiles.getByExternalId('user-123', { includeBots: true }) const { sessions } = await pug.activity.profileSessions({ distinctId: 'user-123', includeBots: true }) ``` The request and response shapes match the `shared.*` Connect services - see the [API reference](/api) for field-by-field schemas. From a backend without an SDK, call those services directly with your private key (see [Authentication](/get-started/authentication)). ## Upgrading ### v0.1.0 - **`identify()` returns `void` and queues**, where it used to return a promise and send right away. The identify goes out with the next batch, `flush()` or `close()`, through `BatchIdentify` or, on a server without it, one `Identify` call each. Drop any `.then()` on its result; `await pug.identify(...)` still compiles but no longer waits for the send. - **`onError` gets `(err, { events, identifies })`** instead of `(err, events)`. Failed identifies retry on transient errors and reach it like events, where 0.0.7 only logged them. - **An event or identify over 900 KiB is dropped** at the call with a log. - **A `NaN` or `Infinity` trait is skipped** with a warning; 0.0.7 sent it and the server stored it as a string. ### v0.0.7 Nothing here breaks compilation, but input that 0.0.6 altered and sent anyway is now dropped with a `[Pug SDK]` error, so check your logs after upgrading. - **A well-known event with a wrong-typed prop is dropped**, where 0.0.6 sent it without that field under an "unsupported scalar type" warning. - **`identify()` needs plain-object traits.** A string, array, `Date` or `Map` used to go out as empty traits (`{}`); now the call logs and sends nothing. - **int64 and Duration props are sent.** 0.0.6 skipped a number in an int64 field such as `sizeBytes`, and skipped a Duration such as `position`, or dropped the whole event when its `seconds` was a number. - **A `distinctId` starting with `cookieless-` is dropped**, since the server rejects the whole batch over one. - **Server-side drops are logged.** Events the server refuses from a batch it otherwise accepts now log a warning with the reasons. - **`includeBots` is new on reads.** Reads leave bot-tagged traffic out whichever SDK version you run; 0.0.7 is the first that can ask for it back. # Ruby SDK > Send events and read profiles, activity and insights from a Ruby or Rails backend with the pug-sh gem and a private key. Source: https://docs.pug.sh/sdks/ruby/ | Markdown: https://docs.pug.sh/sdks/ruby/index.md The `pug-sh` gem sends events from your Ruby backend **and** reads analytics back - profiles, activity and insights. It authenticates with your **private key** (`prv_...`), so it belongs on the server only. It follows the [same model as every Pug SDK](/sdks) with one exception: a server has no ambient user or session to reset, so you name the `distinct_id` on each call instead. ## Install ```bash bundle add pug-sh # or, without Bundler: gem install pug-sh ``` [View `pug-sh` on RubyGems](https://rubygems.org/gems/pug-sh) The gem needs **Ruby 3.3+** and loads as `pug`: in Rails, `Bundler.require` loads it for you; elsewhere, require it before you construct the client: ```ruby require "pug" ``` Keep the private key in an environment variable or Rails credentials, never in code shipped to a browser or app. Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in [Install with AI](/get-started/ai-setup). ```text Add Pug product analytics to this Ruby backend. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/ruby/index.md - SDK reference - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the service actually does: its routes or controllers, its main models, and the state changes that matter to the business. On a server the events worth tracking are the ones a browser cannot observe - a payment settling, a webhook arriving, a job finishing, a subscription lapsing - not request logging. If you cannot state what this service is for in one sentence, keep reading. Then: 1. Add the pug-sh gem to the Gemfile. It needs Ruby 3.3+, and it is required as "pug", not "pug-sh". 2. Construct one Pug::Client at boot and share it - do not build one per request. It is thread-safe and fork-safe, so it can be created before Puma or Unicorn fork. In Rails, use the initializer from the SDK reference, guard included, so assets:precompile still boots without credentials. Its api_key is the private key (prv_...), read from an environment variable or Rails credentials, never committed. 3. Remember the argument order: pug.track(distinct_id, kind, properties, options). The distinct_id comes first because a server has no ambient user - use our own user ID, or the anon-... ID forwarded from the client. Without braces, a key named timestamp, session_id or location sets that option instead of a property. 4. Add track calls for the three or four state changes you identified. 5. Call identify when a user record is created or changes materially, not on every request. 6. Call close in the graceful-shutdown path so queued events and identifies flush, and pass an on_error handler taking (error, undelivered) - a Pug::Undelivered whose events or identifies hold what was lost - so dropped items are logged rather than lost. Name events from the catalog before you invent one. The Ruby SDK checks 114 of the 127 well-known events against their schemas, at runtime: a property of the wrong type drops the whole event, so take property names and types from that page. The ones a backend is placed to see are exactly the ones whose schemas are worth having - purchase, subscription_started, invoice_paid, payment_failed, order_refunded. Search the catalog for every action you are about to track, and fall back to a custom snake_case name only when nothing fits. When you do, tell me which event you considered and why it did not. There is no reset on the server SDK, and no immediate option on track - use flush. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this service does, then list the files you changed, the event names you chose, and the environment variables or credentials I need to set. ``` ## Initialize Construct a `Pug::Client` **once** at boot with your private key - every other call needs it first. Private keys live under **Settings > API Keys**, but one is only shown when you [create it](/get-started/authentication) - if you don't have yours, issue a new one. ```ruby require "pug" # Construct once at boot, share it across threads and requests. pug = Pug::Client.new( api_key: ENV.fetch("PUG_PRIVATE_KEY"), # prv_... - server-side only, never ship to a client on_error: ->(error, undelivered) { warn "Pug dropped #{undelivered.events.size} event(s), #{undelivered.identifies.size} identify(s): #{error.message}" }, ) ``` `Pug::Client.new` **raises `ArgumentError`** if `api_key` is missing, doesn't start with `prv_`, or holds a space or any character outside printable ASCII, such as a trailing newline. A malformed `endpoint`, `batch`, `on_error` or `logger` raises too; after that, ingestion never raises. | Option | Type | Default | Description | |--------|------|---------|-------------| | `api_key` | `String` | **required** | Private key (`prv_...`), sent as `x-api-key`. | | `endpoint` | `String` | `https://api.pugs.dev` | Pug server origin; set it only when self-hosting. Redirects aren't followed, so give the final URL. | | `batch` | `Hash` | `max_size: 100`, `max_wait: 5`, `max_queue_size: 10_000` | One buffer each for events and identifies: items per request (capped at 1000), seconds between sends, and how many to hold before the oldest are dropped. | | `on_error` | callable | none | Dead-letter hook for events and identifies that couldn't be delivered, called with `(error, undelivered)`: a permanent send failure, a queue overflow, or what `close` couldn't send. | | `logger` | `Logger`-like | `Logger.new($stderr)` at `WARN` | Gets the SDK's `[Pug SDK]` warnings and errors - anything with `warn` and `error`, such as `Rails.logger`. | | `timeout` | `Numeric` | `10` | Request timeout, in seconds. | Two background threads, one for events and one for identifies, send in batches when `max_size` are queued or `max_wait` has passed. A transient failure, such as a network error or a timeout, keeps a batch queued and retries `max_wait` after the failure, but no sooner than a second; a permanent one - a client error such as `:unauthenticated` or `:invalid_argument` - hands it to `on_error` as a `Pug::Error` carrying that code. Overflow arrives as a `Pug::QueueOverflowError`, and what `close` couldn't send as a `Pug::ClosedError` or the error that failed its last attempt. Events the server refuses from a batch it otherwise accepts are logged at `WARN`. `undelivered` is a `Pug::Undelivered` whose `events` or `identifies` hold what was lost; the other is empty. `on_error` must take both arguments - a lambda that takes one raises at construction - and runs on a sender thread, the thread calling `close`, or for overflow the thread that called `track` or `identify`, so keep it thread-safe and quick. Call `pug.close` on graceful shutdown so nothing queued is lost - see [`flush` and `close`](#track-events). One client is safe to share across threads. A client created before a fork (Puma, Unicorn, Sidekiq) starts empty in each child, with its own sender threads and connections; events and identifies queued in the parent stay with the parent. ### Rails ```ruby title="config/initializers/pug.rb" unless ENV["SECRET_KEY_BASE_DUMMY"] PUG = Pug::Client.new(api_key: Rails.application.credentials.pug_private_key, logger: Rails.logger) at_exit { PUG.close(timeout: 5) } end ``` Without the guard, `Pug::Client.new` raises during the `assets:precompile` step of Rails' generated Dockerfile, which boots the app with `SECRET_KEY_BASE_DUMMY=1` and no credentials. ## Track events After the `distinct_id`, the next argument is the event **name** (its `kind`). Any name works without a schema; [well-known events](/reference/well-known-events) add typed properties and richer dashboards. ```ruby # distinct_id (who the event is for) comes first - a server has no ambient user. pug.track("user-123", "order.completed", amount: 49.0, currency: "USD") # Well-known events get typed, validated properties. pug.track("user-123", "purchase", product_id: "sku_123", amount: 29.99, currency: "USD") ``` `pug.track(distinct_id, kind, properties = nil, options = nil)` takes the **`distinct_id` first**: your external ID, or an `anon-...` ID forwarded from the client, as a String or an Integer such as a record's `id`. `track` **never raises** and returns at once; events are validated, batched and sent in the background. Properties are a Hash, braces optional, and options follow as keywords. Without braces, a key named after an option - `timestamp`, `session_id` or `location` - sets that option, so a property with one of those names needs the braces: ```ruby pug.track("user-123", "signup", plan: "pro") pug.track("user-123", "signup", plan: "pro", timestamp: Time.now - 3600) pug.track("user-123", "signup", { plan: "pro", location: "landing" }, location: { country: "DE" }) ``` There is no `immediate` option on the server - flush explicitly instead: ```ruby pug.flush # send what's queued now, and wait for that attempt pug.close # drain on graceful shutdown so nothing queued is lost ``` Both cover events and identifies, take a `timeout:` in seconds, and return `false` if it ran out first. A `true` doesn't mean everything was delivered: from `flush` it means the attempt finished, and a transient failure re-queues for a later send; from `close` it means the drain finished. Either way, by the time `close` returns, everything it couldn't send has gone to `on_error` and the log. `track(distinct_id, kind, properties = nil, options = nil)` options: | Option | Type | Description | |--------|------|-------------| | `timestamp` | `Time` | Override the event time with a `Time` or `DateTime` - not epoch milliseconds. Anything else, or a time outside 1970-9999, is ignored with a warning and the event is sent at the current time. | | `session_id` | `String` | A UUID to use as this event's session ID - otherwise the client uses one for its lifetime. Anything but a UUID is ignored with a warning. | | `location` | `Hash` | Where the **visitor** is. Without it a server event carries no geo at all. See [Visitor location](#visitor-location). | **Property values** map by Ruby type: | Ruby value | Sent as | |------------|---------| | `String`, `Symbol` | string | | `true`, `false` | bool | | `Integer` | int - dropped outside the int64 range | | `Float`, `BigDecimal`, `Rational` | double - `NaN` and `Infinity` are dropped | | `Time`, `DateTime`, `Google::Protobuf::Timestamp` | timestamp | | `Date` | ISO 8601 date string, such as `"2026-10-10"` | | `Google::Protobuf::Duration` | duration string, such as `"1.5s"` | | `Hash`, `Array` | JSON string | | `nil` | omitted | Anything else is dropped with a warning - the property, not the event. Inside a `Hash` or `Array`, times become ISO 8601 strings, while a value JSON has no form for, such as a `Set`, drops the whole property. Strings are capped at 1024 bytes and truncated with a warning. **Property keys** in snake_case are sent in camelCase, so `order_total:` arrives as `orderTotal`. Any other key, camelCase or not, is sent as written, as are the keys inside a nested `Hash`. The Node, Go and Python SDKs send every key as written, so `order_total` from them stays `order_total`. If two keys come out the same, such as `order_total` and `orderTotal`, the last one is sent and the other is dropped with a warning, as with `Hash#merge`. A [well-known event](/reference/well-known-events)'s properties are checked against its schema before the event is queued. Keys may be the field's name (`product_id`) or its JSON name (`productId`), but not both, which drops the event; either way the property is sent under the JSON name. A field's type comes from the schema rather than the Ruby value, so `amount: 10` is sent as a double. A value of the wrong type, or one failing a rule such as `currency` needing three uppercase letters, drops the **whole event**, and the log names the field (`quantity: expected int32, got String`). Keys outside the schema pass through as custom properties. Duration fields such as `position` take seconds as a number, `{ seconds:, nanos: }` or a `Google::Protobuf::Duration`, and are sent as a string like `"92.5s"`. `track` logs and drops an event whose `distinct_id` starts with `cookieless-`, a prefix the server reserves; it would reject the whole batch. ### Visitor location The server adds no geo to events sent with a private key: an event carries the `location` you give it, or none at all. ```ruby pug.track("user-123", "purchase", { product_id: "sku_123", amount: 29.99, currency: "USD" }, location: { country: "DE", city: "Berlin" }) ``` | Field | Type | Notes | |---|---|---| | `country` | `String` | ISO 3166-1 alpha-2 (`DE`). Case and surrounding spaces are normalized; a code Pug doesn't recognize is dropped. | | `continent`, `region`, `city`, `postal_code`, `metro_code` | `String` | Sent as given, trimmed. | | `timezone` | `String` | IANA name (`Europe/Berlin`). | | `latitude`, `longitude` | `Numeric` | Decimal degrees, `-90` to `90` and `-180` to `180`. Sent only as a pair: one without the other is dropped. | Each field becomes the matching `$`-prefixed [auto-property](/reference/auto-properties#geo-enrichment-cloudflare): `postal_code` lands as `$postalCode`, and the camelCase key works too. It's the only way to set an auto-property from this SDK: properties become **custom** properties, and one whose key starts with `$` drops the event. A field that is absent, `nil` or empty is skipped silently. One that looks like a mistake - unknown key, wrong type, a country code Pug doesn't know, a coordinate out of range - is dropped with a warning and **the rest of the event still sends**. ## Identify and sessions Use a **stable, unique** external ID - your database user ID, not an email, which can change. Only the **first** identify after an anonymous session merges prior activity; the same external ID always resolves to the same profile, and traits are merged server-side, never removed. ```ruby # On the first identify, pass the client's anonymous ID to merge its prior anonymous activity. pug.identify("user-123", { email: "user@example.com", plan: "pro" }, anonymous_id: "anon-abc123") ``` `pug.identify(external_id, traits = nil, options = nil)` **never raises** and returns at once: identifies are queued and sent in batches like events, and what can't be delivered goes to `on_error`. A read straight after an identify may not see it yet. `traits` must be a Hash of JSON-serializable values, with keys camelCased like [property keys](#track-events): `first_name:` arrives as `firstName`. They travel as a protobuf `Struct`, whose numbers are doubles, so an Integer past 2^53 is refused. A refused trait, an `external_id` starting with the reserved `cookieless-` prefix, or an identify over 900 KiB is logged and nothing is sent. A trait holding `NaN` or `Infinity` is skipped with a warning, and the rest still goes out. Pass `anonymous_id:` (must start with `anon-`) on the first identify to merge a client's prior anonymous activity into the profile, and `device_id:` to attach a device; as with `track`, those keys set options even without braces. There is no `reset` or `rotate`. ### Sessions The client uses one session ID for its lifetime; override it per call with `track(..., session_id:)`. ## Auto-tracking There is no auto-tracking: you send every event with `pug.track`. The server adds no geo or user agent to these events, so pass the visitor's [`location`](#visitor-location) yourself. ## Consent and privacy The Ruby SDK has no consent gate and no redaction hooks: respect the visitor's consent choice before you call `track`, and keep PII out of the properties you pass. ## Server-side reads The private key also authorizes **reads** - the insights, profiles and activity data the dashboard shows. Reads **raise `Pug::Error`** and are never retried. Ingestion (`track` / `identify`) still never raises. ```ruby # Look up a profile by your external ID. profile = pug.profiles.get_by_external_id("user-123") # Auto-paginating: yields every matching profile, or returns an Enumerator without a block. pug.profiles.list.each { |p| puts p.external_id } # Run an insights query - the same spec the dashboard uses. result = pug.insights.query( spec: { insight_type: :INSIGHT_TYPE_TRENDS, events: [{ event: { kind: "order.completed" } }] }, time_range: { from: Time.now - (30 * 86_400), to: Time.now }, granularity: :GRANULARITY_DAY, ) ``` | Namespace | Methods | |-----------|---------| | `pug.profiles` | `get(id, include_bots: false)`, `get_by_external_id(external_id, include_bots: false)`, `delete(id)`, `list(request = nil, timeout: nil)`: auto-paginating | | `pug.activity` | `feed`, `event_explorer`, `heatmap`, `profile_sessions`, `profile_stats`, `filter_schema`, `property_values` | | `pug.insights` | `query`, `segment_users`, `filter_schema`, `property_values` | Requests are a Hash, braces optional, or the generated request message. Responses are the generated messages under `Pug::Proto` (`Pug::Proto::Shared::Insights::V1::QueryResponse`, ...) - call `to_h` on one for plain Ruby data - except that `profiles.get` and `get_by_external_id` return the profile itself. `list` streams, and the client's `timeout` bounds the whole stream, your block's time included; pass `timeout:` (seconds) to give a long listing more. Property names in reads are the stored ones, so a property tracked as `order_total:` is filtered on, and comes back, as `orderTotal`. `Pug::Error#code` is the Connect code as a Symbol (`:not_found`, `:unavailable`, ... - see the [error model](/api#error-model)), or `nil` when the failure didn't come from the RPC layer, and `cause` is the underlying exception: ```ruby begin profile = pug.profiles.get_by_external_id("user-123") rescue Pug::Error => e raise unless e.code == :not_found end ``` Reads leave out traffic tagged as a bot at ingest: web-SDK events from crawler user agents and datacenter networks. Events from this SDK are never tagged. Set `include_bots: true` to count bot traffic - `profiles.get` and `get_by_external_id` take it as a keyword, and `profiles.list`, `insights.query` (on its `spec`) and the activity `feed`, `event_explorer`, `heatmap`, `profile_sessions` and `profile_stats` take it in the request: ```ruby profile = pug.profiles.get_by_external_id("user-123", include_bots: true) sessions = pug.activity.profile_sessions(distinct_id: "user-123", include_bots: true).sessions ``` The request and response shapes match the `shared.*` Connect services - see the [API reference](/api) for field-by-field schemas. From a backend without an SDK, call those services directly with your private key (see [Authentication](/get-started/authentication)). ## Upgrading ### v0.1.0 - **`identify` returns at once** instead of waiting for the server: identifies are queued and sent in batches like events, with `BatchIdentify` or, on a server without it, one call each. - **`on_error` receives `(error, undelivered)`**, a `Pug::Undelivered` whose `events` or `identifies` hold what was lost, instead of `(error, events)`. A 0.0.x handler still passes the arity check but fails when it treats the second argument as an Array. Failed identifies reach it too, not only the log. - **A `session_id` that isn't a UUID is ignored with a warning**, where 0.0.x dropped the event. ### v0.0.2 - **Property and trait keys in snake_case are sent in camelCase**: `order_total:` arrives as `orderTotal`. Data 0.0.1 stored keeps its snake_case keys, so saved filters need the camelCase names, and profiles hold both spellings. # Web SDK > Track events, identify users and gate capture on consent from the browser with @pug-sh/browser - via a bundler or the CDN. Source: https://docs.pug.sh/sdks/web/ | Markdown: https://docs.pug.sh/sdks/web/index.md `@pug-sh/browser` is the browser SDK for Pug, open-source product analytics. It captures events from browser apps - React, Vue, Next.js, or plain JavaScript. It authenticates with your **public key** (`pub_...`), which is write-scoped (events + identify) and safe to ship in client code, and follows the [same model as every Pug SDK](/sdks): initialize once, track events, identify users, reset on sign-out. ## Install ```bash npm install @pug-sh/browser # or: pnpm add @pug-sh/browser | yarn add @pug-sh/browser | bun add @pug-sh/browser ``` [View `@pug-sh/browser` on npm](https://www.npmjs.com/package/@pug-sh/browser) Use it from a **bundler** (Vite, webpack, esbuild, Next.js, ...) as below, or with no build step from the **CDN**, through the [loader snippet](#loader-snippet) or a [one-tag install](#one-tag-install). Both expose the same API. Import named exports from the package root, and call `init()` once wherever your app boots. There are no framework-specific packages. ```ts import { init, track, identify, reset } from '@pug-sh/browser' ``` Verify by opening your dashboard's **Live** view - an auto-tracked `page_view` appears within ~15 seconds. Working with a coding agent? Paste this instead - it points the agent at the markdown copy of this page. More in [Install with AI](/get-started/ai-setup). ```text Add Pug product analytics to this app. Read these first - they are the current source of truth, and more recent than your training data: - https://docs.pug.sh/sdks/web/index.md - SDK reference - https://docs.pug.sh/get-started/index.md - quickstart - https://docs.pug.sh/reference/well-known-events/index.md - the well-known event catalog Then read this codebase before you write anything, and work out what the product actually does: its routes or screens, its main models, and the handful of things a user comes here to complete. The events worth tracking are the moments the product exists to produce - an account created, an order placed, a document shared - not every button on the page. If you cannot state the core action in one sentence, keep reading. Then: 1. Install @pug-sh/browser. 2. Call init() exactly once, where the app boots, in the browser only - never during SSR. In the Next.js App Router that means a "use client" provider mounted from the root layout. 3. Read the project ID and public key from environment variables. The public key starts with pub_ and is safe to ship. A private key starts with prv_ and must never reach client code. 4. Leave auto-tracking on and do not hand-roll page views - init() already captures them. 5. Add track() calls for the three or four actions you identified - the ones someone would look at in a weekly review. Property values must be plain JSON scalars: strings, numbers, booleans, dates. 6. If this app has authentication, call identify() after sign-in and reset() on sign-out. Note that the SDK is cookieless until optInTracking() is called, so identify() is a no-op without granted consent - tell me whether I need a consent banner rather than opting users in silently. Name events from the catalog before you invent one. It holds 127 well-known events across 19 families - commerce, authentication, billing, media, forms, support, workspace and more - and a well-known name is type-checked as you write it and fills in dashboards that a custom name leaves empty. Search it for every action you are about to track, and take property names and types from that page rather than from whatever reads idiomatically. Fall back to a custom snake_case name only when nothing in the catalog fits, and when you do, tell me which event you considered and why it did not. Do not use any option that is not in the SDK reference above. When you are done, tell me in one sentence what you concluded this product does, then list the files you changed, the event names you chose, and the environment variables I need to set. ``` ### Next.js App Router In the App Router, `init` must run in the browser, not during SSR, so call it from a client provider: ```tsx title="components/PugProvider.tsx" 'use client' import { init } from '@pug-sh/browser' import { useEffect } from 'react' export function PugProvider({ children }: { children: React.ReactNode }) { useEffect(() => { init(process.env.NEXT_PUBLIC_PUG_PROJECT_ID!, { apiKey: process.env.NEXT_PUBLIC_PUG_PUBLIC_KEY! }) }, []) return <>{children} } ``` The App Router also navigates without a full History push, so auto-tracking fires `page_view` only on the initial load. Track later navigations with `track('page_view')` in a `usePathname()` effect. ### Loader snippet **Via CDN (no bundler).** This and the [one-tag install](#one-tag-install) each load one self-contained file from Pug's CDN (`cdn.pugs.dev`) that puts the full API on `window.pug` (`pug.track(...)`, `pug.identify(...)`, ...). Use one, not both. The version is pinned in the URL (`/v0.1.8/`), so bump it when you upgrade, on every page at once - see [v0.1.0](#v010). Paste this into ``. It defines `window.pug` immediately and loads the bundle asynchronously; calls made before it arrives (`init`, `track`, consent changes) are queued and replayed in order. Call `pug.init()` first - the SDK drops calls queued ahead of it. ```html ``` Queued calls return `undefined` instead of their real value, so put any read or `await` inside `pug.ready(cb)` (CDN only). It runs at its place in the queue, or synchronously once the SDK is live: ```html ``` ### One-tag install One self-initializing tag with no inline script, for pages whose CSP forbids inline scripts. It inits from its `data-*` attributes: `data-project-id` and `data-api-key` are required, `data-endpoint` sets a self-hosted origin, and `data-options` takes any other [init option](#initialize) as JSON (`trackingConsent`, `autoCapture`, ...). ```html ``` JSON can't hold functions, so `beforeSend` isn't available here and [`redactUrlParams`](#redacting-pii), on by default, is the only URL masking. There's no pre-load queue either: `window.pug` exists only once the bundle loads, so call `pug.*` from code that runs later, or use the loader snippet. Attributes are validated at runtime and **fail closed**: a missing `data-project-id` or `data-api-key`, or unparseable `data-options`, aborts the init, and an unrecognized `trackingConsent` value resolves to `'denied'`. ## Initialize Call `init` **once** at startup with your project ID and public key - every other call needs it first. Find your project ID in the dashboard URL (`/p/`), and your public key on your project **Overview** or under **Settings > API Keys**. ```ts import { init } from '@pug-sh/browser' init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY' }) ``` `init` returns nothing. It **throws** if `projectId` or `apiKey` is missing, and no-ops (with a console warning) if called a second time or outside a browser. | Option | Type | Default | Description | |--------|------|---------|-------------| | `apiKey` | `string` | **required** | Public key (`pub_...`), sent as `x-api-key`. | | `endpoint` | `string` | `https://api.pugs.dev` | API base URL; set it only when self-hosting. A non-`https` origin other than localhost warns at init. | | `batch` | `BatchOptions` | `maxSize 10`, `maxWaitMs 5000`, `maxQueueSize 1000` | Queue size and flush timing. | | `session` | `SessionConfig` | `idleTimeoutMinutes 30`, `maxSessionMinutes 1440` | Session idle and max-duration timeouts (minutes). | | `autoCapture` | `boolean \| AutoCaptureSelection` | `true` | `true` enables every tracker, `false` none, an object is an allowlist. See [Auto-tracking](#auto-tracking). | | `trackingConsent` | `TrackingConsent \| TrackingConsentConfig` | `'cookieless'` | Consent gate. See [Tracking consent](#tracking-consent). | | `crossSubdomainTracking` | `boolean \| { domain }` | `false` | Share identity across subdomains through a first-party cookie, once consent is `'granted'`. See [Cross-subdomain identity](#cross-subdomain-identity). | | `maxAgeDays` | `number` | `365` | How long stored identifiers live, counted from first write. See [Retention](#retention). | | `redactUrlParams` | `readonly string[] \| false` | built-in list | Query/fragment params whose values are replaced with `redacted` in `$url`, `$referrer` and form actions. See [Redacting PII](#redacting-pii). | | `beforeSend` | `BeforeSendFn` | - | Redact, rewrite or drop each event before it is sent. Fails closed. See [Redacting PII](#redacting-pii). | | `debug` | `boolean` | `false` | Log internal activity to `console.debug` (DevTools' "Verbose" level). Warnings and errors are logged regardless. | | `dryRun` | `boolean` | `false` | Build events as normal but never send them. Doesn't change consent, or what `isTrackingEnabled()` reports. | | `excludeAutomatedBrowsers` | `boolean` | `false` | Send nothing from automation-driven browsers (Playwright, Puppeteer, Selenium, headless Chrome). See [Automated browsers](#automated-browsers). | `destroy()` tears the SDK down - it flushes the queue and removes listeners - so `init()` can run again. ## Track events The first argument is the event **name** (its `kind`). Any name works without a schema; [well-known events](/reference/well-known-events) add typed properties and richer dashboards. A name may hold only ASCII letters, digits, `_`, `.` and `-`: the server rejects any batch containing another, and the SDK logs an error and drops that whole batch. ```ts import { track } from '@pug-sh/browser' // Custom event - any name track('button_clicked', { label: 'Sign up', page: '/pricing' }) // Well-known event - typed properties track('purchase', { productId: 'sku_123', amount: 29.99, currency: 'USD' }) ``` `track()` **never throws** and returns nothing; events are queued and flushed in the background. **Property values** accept `string` (truncated to **1024 bytes** client-side), `number`, `boolean`, and `Date` (stored as a timestamp). Objects and arrays are JSON-encoded to a string. `null`, `undefined`, and non-finite numbers are dropped. Send numbers as numbers - aggregations like Sum don't work on strings. `track(event, props?, options?)` options: | Option | Type | Description | |--------|------|-------------| | `immediate` | `boolean` | Bypass the batch queue and send right away. | | `timestamp` | `number` | Override the event time, as **epoch milliseconds** (e.g. `Date.now()`). | ```ts // Conversion that must arrive before a redirect track('purchase', { productId: 'sku_789', amount: 99, currency: 'USD' }, { immediate: true }) ``` ## Identify and sessions Events accumulate against an anonymous ID until you `identify()` the user on sign-in, which merges that history into a known profile; call `reset()` on sign-out. Use a **stable, unique** external ID - your database user ID, not an email, which can change. Only the **first** identify after an anonymous session merges prior activity; the same external ID always resolves to the same profile, and traits are merged server-side, never removed. ```ts // On sign-in - merge anonymous history into the known profile await identify('user-123', { email: 'user@example.com', plan: 'pro' }) // On sign-out - clear identity, start a fresh anonymous session reset() // New session ID without clearing identity rotate() ``` `identify(externalId, traits?)` returns a **promise** and **never throws**: invalid input, a call before `init()`, denied consent, cookieless mode, `dryRun` and RPC failures are logged, and the promise resolves without sending. The `externalId` must not start with `cookieless-`, a prefix the server reserves for identities it derives; it rejects any batch carrying one. `reset()` clears the stored identity and starts a new anonymous session; it does **not** delete the profile. It sends any queued events first, and **returns `false`** when something couldn't be removed - with [cross-subdomain identity](#cross-subdomain-identity), that means the cookie survived on the registrable domain and the next person on that machine inherits it. ```ts if (!reset()) { showSignOutWarning() } ``` | Function | Clears identity | New device ID | New session ID | |----------|-----------------|---------------|----------------| | `rotate()` | No | No | Yes | | `reset()` | Yes | Yes | Yes | > **Identify needs a stored identifier** > > Under the default `'cookieless'` consent state there's no stored anonymous ID to > merge, so `identify()` is a no-op (warned once per page load) until the reader > grants consent - see [Tracking consent](#tracking-consent). To branch on that, > check `getTrackingConsent() === 'granted'`; `isTrackingEnabled()` is also `true` > when cookieless. ### Sessions Sessions group events within a single visit, ending at the idle or max-duration timeout: 1. **First event** (session ID created) 2. **Events within timeout** (same session ID) 3. **Idle past timeout** (session expires) 4. **Next event** (new session ID (identity kept)) The session is shared across tabs through `localStorage`; set the timeouts with the `session` [init option](#initialize). Under the default `'cookieless'` consent state, though, the SDK stores no session and sends no `sessionId`: the server derives one from the daily-rotating anonymous ID and closes it after 30 minutes of inactivity. The `session` timeouts apply once consent is granted. ### Cross-subdomain identity Identity is stored in origin-scoped `localStorage` by default, so `www.example.com` and `app.example.com` see two unrelated visitors. `crossSubdomainTracking` moves it to a first-party cookie on the registrable domain, making them one profile. ```ts init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY', crossSubdomainTracking: true, // auto-discover the registrable domain // crossSubdomainTracking: { domain: 'example.com' }, // or pin it explicitly }) ``` It shares the anonymous ID, the `identify()`ed external ID, session state and the persisted consent choice, so an opt-out on one subdomain applies to the others. **Every subdomain must use the same project**: the cookie is keyed by project, and a mismatch silently splits each visitor in two. > **It does nothing until consent is granted** > > In the default [cookieless](#tracking-consent) state nothing is written to the > device, cookie included, so turning this on alone shares nothing until the > reader opts in. If sharing isn't happening, check `getTrackingConsent()` before > your domain. A banner-free pattern for a marketing site and an app on one domain: the **app** grants consent at sign-in and drops back to cookieless on sign-out, and the **marketing site** grants only when the shared cookie already exists, staying cookieless otherwise. Returning customers land on their profile and anonymous readers are still counted, but pre-signup visits never join the profile, since a cookieless visitor has no anonymous ID to merge. Before switching it on: - **It relaxes browser isolation** from same-origin to same-site. - **On a multi-tenant domain not on the [Public Suffix List](https://publicsuffix.org/)** (`a.myplatform.com` and `b.myplatform.com` as separate customers), auto-discovery picks the shared `myplatform.com`, letting tenants read each other's identity. Pin an explicit `{ domain }` there. - **It falls back** to a host-only cookie on `localhost` and IP hosts, and to `localStorage` when cookies are blocked. Cookies set over HTTPS carry `Secure`, so only HTTPS subdomains share identity. - **Sessions end on timeout only**: the usual rotation once every tab is closed is disabled. ## Auto-tracking Six trackers run by default, with no `track()` calls needed. Every auto-tracked event also carries the standard [auto-properties](/reference/auto-properties), and the server attaches enrichment properties to every event. Auto-property keys are camelCase (`$utmSource`, `$pageTitle`, `$screenWidth`) except the server-set `$bot_reason`, `$bot_score` and `$verified_bot`. Pass an allowlist to run only some, and change it at runtime with `setAutoCapture()`: ```ts import { init } from '@pug-sh/browser' init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY', autoCapture: { pageView: true, click: true } }) ``` Omitted keys stay off, and `false` never turns anything on: the object above enables page views and clicks only, and `{ scroll: false }` enables nothing at all. TypeScript accepts only `true` as a value, so for a flag known at runtime, omit the key with `|| undefined`: ```ts autoCapture: { pageView: true, scroll: enableScroll || undefined } ``` Plain JavaScript and the [one-tag install](#one-tag-install) aren't type-checked, so the SDK warns at runtime instead: on an explicit `false`, an unknown key, a non-boolean value, or a selection that enables nothing. | Tracker | Allowlist key | Event(s) | Captured properties | |---------|---------------|----------|---------------------| | Page views | `pageView` | `page_view` | auto-properties only (`$url`, `$referrer`, ...) | | Clicks | `click` | `click` | `tag`, `id`, `class`, `text` (the element's [own text](#redacting-pii), max 50 chars), `x`, `y` | | Scroll | `scroll` | `scroll` | `percent` (0-100), `scrollY` | | Forms | `form` | `form_start`, `form_submit` | form **metadata** only - `formId`, `formName` (both), plus `action` on `form_submit`. Never field values | | Rage clicks | `rageClick` | `rage_click` | `clickCount`, `element`, `x`, `y` | | Dead clicks | `deadClick` | `dead_click` | `element`, `text` (the element's [own text](#redacting-pii), max 20 chars), `x`, `y` | `page_view` fires on the initial load and on History API navigation (`pushState`, `replaceState`, `popstate`), so call `init()` **before** your router mounts. The [Next.js App Router](#nextjs-app-router) needs manual `page_view`s. `$pageTitle` is sent on `page_view` only, not every event; other events join to it through `sessionId`. ## Consent and privacy The Web SDK ships GDPR/CCPA controls that run **in the browser before anything is sent**, so raw values never leave the device. ### Tracking consent Consent has three states: | State | Events sent | Identifier stored on the device | |-------|-------------|--------------------------------| | `'granted'` | Yes | Yes - anonymous ID, session, any `identify()`ed external ID | | `'cookieless'` | Yes | **No** | | `'denied'` | No | No | **`'cookieless'` is the default**: events are counted from the first one, but nothing is written to the device until the reader answers your banner. Pass `'granted'` for full identity from the first event, or `'denied'` to capture nothing. ```ts import { init, optInTracking, optOutTracking, isConsentPending } from '@pug-sh/browser' init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY', trackingConsent: { initial: 'cookieless', // default - events flow, nothing is stored onReject: 'denied', // what optOutTracking() resolves to persist: true, // remember the choice across reloads respectGpc: true, // honor the browser's Global Privacy Control signal } }) // Show your banner only while the reader hasn't chosen. if (isConsentPending()) showCookieBanner() optInTracking() // accepted -> 'granted': attach listeners, start storing identity optOutTracking() // declined -> resolves to `onReject` ``` `TrackingConsentConfig`: | Field | Type | Default | Description | |-------|------|---------|-------------| | `initial` | `'granted' \| 'denied' \| 'cookieless'` | `'cookieless'` | Used until a choice has been persisted. | | `onReject` | `'denied' \| 'cookieless'` | `'denied'` | What `optOutTracking()` resolves to. `'cookieless'` keeps identity-free counts after a rejection. | | `persist` | `boolean` | `false` | Store the choice and restore it on the next `init()`. Without it, consent lives in memory and starts from `initial` on every load. | | `respectGpc` | `boolean` | `false` | Resolve the browser's [Global Privacy Control](#global-privacy-control) signal to `onReject`. Read once per `init()`; a choice made on your site outranks it. Pair it with `persist: true`. | | Function | Returns | Description | |---|---|---| | `optInTracking()` | `boolean` | Grant consent, attach listeners (applying the stored `autoCapture` selection), allow `track()` / `identify()`. | | `optOutTracking()` | `boolean` | Revoke consent, resolving to `onReject`: clears the stored anonymous ID / session and stops `identify()`. Resolving to `'denied'` also removes listeners and drops `track()`. | | `setTrackingConsent(state)` | `boolean` | Set any of the three states. `'denied'` means denied, whatever `onReject` says. | | `isTrackingEnabled()` | `boolean` | Whether events are flowing right now: `true` for both `'granted'` and `'cookieless'`. Independent of `dryRun`. | | `getTrackingConsent()` | `TrackingConsent \| undefined` | The state the SDK is acting on, or `undefined` before `init()`, which is when a persisted choice is read. | | `isConsentPending()` | `boolean` | `true` until the reader chooses. Gate your banner on this: `getTrackingConsent()` can't tell a seeded `'granted'` from a chosen one. | | `setAutoCapture(selection)` | `void` | Change the auto-capture allowlist at runtime: applied immediately while tracking is active, deferred until opt-in when denied. | #### Cookieless mode In `'cookieless'` the SDK stores no session, anonymous ID or cross-subdomain cookie, not even queued event payloads, and sends no identity. The server derives an anonymous ID instead - an HMAC-SHA256 of the project, IP and user agent, keyed by a salt that rotates daily and is deleted within 48 hours. IP and user agent are hash inputs only, never stored or returned. These visitors count toward traffic but not toward user counts. Events otherwise carry the same [auto-properties](/reference/auto-properties). `identify()` is disabled, and granting consent later starts a **fresh** identity: pre-consent events are never linked to it. The only thing stored is the consent choice itself, under `persist: true`. Set both `initial` and `onReject` to `'cookieless'` to count identity-free traffic before the reader answers and after they decline, behind a plain accept/reject banner: ```ts init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY', trackingConsent: { initial: 'cookieless', onReject: 'cookieless', persist: true } }) ``` For a CMP that separates "reject analytics cookies" from "reject everything", set the three states directly: ```ts onAcceptAll(() => setTrackingConsent('granted')) onRejectAnalyticsCookies(() => setTrackingConsent('cookieless')) onRejectAll(() => setTrackingConsent('denied')) ``` > **Cookieless is not automatically consent-exempt** > > The SDK still reads device characteristics (screen dimensions, locale, client > hints), which EDPB Guidelines 2/2023 bring within ePrivacy Art. 5(3), and the > server still processes IP and user agent. Whether that needs consent where you > operate is yours to decide as the controller. #### Withdrawing consent Leaving `'granted'` deletes the stored identity (profile, session, tab registry, cross-subdomain cookie) and **drops queued events unsent** - unlike `reset()`, which sends them first. #### Global Privacy Control [GPC](https://globalprivacycontrol.org/) is a browser "do not sell or share my data" signal, legally binding under CCPA/CPRA, sent by Brave (by default), Firefox, DuckDuckGo and several privacy extensions. With `respectGpc: true`, a visitor sending it starts at your `onReject` state, no banner needed. Precedence, lowest first: `initial`, then GPC, then a choice made on your site, whether stored or a later `optInTracking()`. Pair it with `persist: true`. Without it, GPC re-resolves on every load, `isConsentPending()` stays `false` so your banner never shows, and an `optInTracking()` lasts only for the page, leaving a GPC visitor no way to accept. The SDK warns when it resolves consent from GPC with persistence off. #### Retention `maxAgeDays` (default 365) bounds every identifier the SDK stores: anonymous ID, external ID, session state and the persisted consent choice. The deadline is **absolute** - set at first write, never extended by later visits - as CNIL's 13-month rule requires (`maxAgeDays: 390`). Lowering it also shortens existing deadlines, at their next write. When the consent record lapses, `isConsentPending()` turns `true` again and your banner reappears. Browsers cap it further: Chromium limits any cookie to 400 days, and Safari's ITP limits script-written cookies far more. And the stored choice is a preference cache, not proof of consent - to *demonstrate* consent under GDPR Art. 7(1), record it in your CMP or on your server, with a timestamp and the policy version. #### When a consent change doesn't take `setTrackingConsent()`, `optInTracking()` and `optOutTracking()` return `false` when a change didn't fully take effect: - **Called before `init()`**: nothing is applied. On the CDN install, wrap the call in `pug.ready()`. - **Unrecognized state** (a CMP's `'reject'`, `'opt-out'`, a boolean, `null`): consent **fails closed to `'denied'`**. Map your CMP's values explicitly. - **Not persisted** (`persist: true` with storage full or cookies blocked): it applies in memory, but the next load falls back to `initial`, so an opt-out can quietly revert. - **A stored identifier couldn't be removed**, such as the [cross-subdomain](#cross-subdomain-identity) cookie on the registrable domain. ```ts if (!setTrackingConsent(choice)) { reportConsentFailure(getTrackingConsent()) } ``` ### Redacting PII Four device-side controls keep PII out of captured events. **`redactUrlParams`**: query and fragment params whose values are replaced with `redacted` in `$url`, `$referrer` and a form's `action`. The default list covers credentials and direct identifiers (`token`, `access_token`, `code`, `email`, `password`, ...) plus any param ending in `_token`, such as `reset_password_token`. Pass an array to replace the list (matched case-insensitively by exact name), or `false` to turn redaction off. An empty array warns and keeps the default list. **`beforeSend`**: redact, rewrite or drop each event just before it's sent. Mutate `autoProperties` and `customProperties` in place, then return the event (or nothing) to send it, or `null` to drop it. URLs arrive with `redactUrlParams` already applied. ```ts import { init } from '@pug-sh/browser' init('YOUR_PROJECT_ID', { apiKey: 'pub_YOUR_PUBLIC_KEY', redactUrlParams: ['email', 'invite', 'session_id'], beforeSend: (event) => { const url = event.autoProperties.$url if (typeof url === 'string') { // Mask path IDs the param-level redaction can't see. event.autoProperties.$url = url.replace(/\/orders\/\d+/, '/orders/:orderId') } if (event.kind === 'debug_ping') return null // drop entirely return event } }) ``` It runs synchronously on every event, so keep it cheap. It **fails closed**: a throw or malformed return drops the event, and a non-function `beforeSend` drops every event. `$projectId`, `$platform` and `$sdkVersion` are re-asserted afterwards, and `sessionId` and `distinctId` aren't exposed. Not available on the [one-tag install](#one-tag-install). **Element text**: the click and dead-click trackers capture only the clicked element's own text nodes, never text nested inside it: ```html
Open jane@example.com 4111 1111 1111 1111
``` `