# Quickstart Install datacub and see your first event in a few minutes. ## 1. Get your project key Open [Settings, Integrations](https://datacub.to/en/settings?tab=integrations) in the dashboard. Your project key starts with `pk_live_` (or `pk_test_` while you build). It is public and safe in client code. [More about keys](https://docs.datacub.to/api-keys.md). In [Settings, General](https://datacub.to/en/settings?tab=general), add your website's domain to the sites allowed to send, or your app's bundle ID or package name to the apps allowed to send. datacub refuses events from anywhere else. ## 2. Add the SDK Paste this in your HTML `` (in Next.js, TanStack Start or SvelteKit, see [where the head is](https://docs.datacub.to/frameworks.md)). It loads the SDK from datacub and defines the global `datacub`: ```html script ``` On `localhost`, use your test key (`pk_test_`): datacub refuses live keys from `localhost`. Every project comes with one, marked **Test** in [Settings, Integrations](https://datacub.to/en/settings?tab=integrations). [More about keys](https://docs.datacub.to/api-keys#test-and-live). > Not on npm. Do not install `@datacub/web`, or anything else under `@datacub`, from npm: that npm name does not belong to datacub. The React Native SDK is not published yet: contact the datacub team for early access. ## 3. That is the install datacub tracks page views, sessions, sources and clicks from the first page view. There is no banner to wire. If you want to wait for your visitors' consent first, see [asking for consent](https://docs.datacub.to/consent.md). What the SDK collects, and how to turn parts off, is in [install the web SDK](https://docs.datacub.to/install-web#what-the-sdk-collects). ## 4. Track one thing that matters Pick the moment your product works for someone, and track it after it succeeds: ```ts web async function createProject(name: string) { const project = await api.createProject(name) datacub.track('project_created', { template: project.template }) return project } ``` [How to choose and name events](https://docs.datacub.to/event-naming.md). ## 5. Check it arrived In [Settings, Integrations](https://datacub.to/en/settings?tab=integrations), choose **Check the connection** and open your site or app: datacub tells you the moment the first event lands. **Realtime** shows events as they arrive. Nothing there? On `localhost` the SDK prints a console warning for every call it refuses. See [troubleshooting](https://docs.datacub.to/troubleshooting.md). ## Working with an AI coding agent? Paste the [AI setup prompt](https://docs.datacub.to/ai#setup-prompt) into Claude Code, Cursor, Codex or ChatGPT. It reads your app, installs the SDK, proposes a short event plan and waits for your yes. --- # Install the web SDK The web SDK is one file, about 6 KB with gzip, served by datacub. Add it with a script tag; it works with any site or framework. It collects page views (including single page app routes), page leaves with foreground time and scroll depth, clicks on buttons and links, form submit attempts, and the events you track, with the context listed in [what the SDK collects](#what-the-sdk-collects). It starts at the first page view, with no consent step. If you want to wait for your visitors' consent, see [asking for consent](https://docs.datacub.to/consent.md). > Not on npm. Do not install `@datacub/web`, or anything else under `@datacub`, from npm: that npm name does not belong to datacub. ## Script tag For a site without a build step, paste this before ``. `data-key` starts the SDK as soon as the file loads. ```html script ``` Add `data-api-host` to send through your own [proxy](#first-party-proxy). ## In an app In React, Vue, Next.js and other apps with a build step, paste this in the HTML `` instead. It defines the global `datacub` at once, so your code can call it before the file has loaded: calls wait in order and run when it arrives. [Where the head is in each framework](https://docs.datacub.to/frameworks.md). ```html script ``` Then use the global `datacub` anywhere in client code, for example `datacub.track('signup_completed')`. Call it in event handlers and effects, not in code that runs on the server, where `x` does not exist. ### TypeScript Save the type definitions in your project. They type the global `datacub` and export the option types (`import type { InitOptions } from './x'`): ```sh none curl -o src/datacub.d.ts https://ingest.datacub.example/v1/sdk/datacub-0.4.0.d.ts ``` ## Options Pass them to `datacub.init` in the snippet: | Option | Default | What it does | |---|---|---| | `apiHost` | `https://ingest.datacub.example` | where events go: datacub's ingestion host or your [proxy](#first-party-proxy). Must be `https` (or `http://localhost`) | | `hashRouting` | `false` | treat `#/route` fragments as pages, for hash routers | | `autocapture` | `true` | clicks and form submits. Page views and page leaves are always on | | `release` | none | your app version or deployment ID, sent with every event | ```ts web datacub.init('pk_live_YOUR_PROJECT_KEY', { release: '2026.11.1', hashRouting: false }) ``` `init` runs once; later calls are ignored. ## First-party proxy Some blockers drop requests to analytics hosts. Forward `POST /v1/batch` from a path on your own domain to datacub's ingestion host, then point the SDK at it: ```ts web datacub.init('pk_live_YOUR_PROJECT_KEY', { apiHost: 'https://www.example.sa/datacub' }) ``` The SDK then posts to `https://www.example.sa/datacub/v1/batch`. Pass the body through unchanged. ## What the SDK collects Besides page views, page leaves and clicks, version 0.2.0 collects the context that explains them: - Text of clicked buttons and links: the element's own visible text, at most 100 characters, with emails, phone numbers, IDs and tokens removed. Never text typed into inputs, text areas, selects or editable regions. When a button has no short text, its `aria-label`, `title` or image `alt` is used. - Page titles, scrubbed, at most 200 characters. - URL query values that read as codes your site put in a link, such as `?sort=price_desc` or `?category=shoes`. Never what someone typed: searches, names, addresses and messages, anything with a space or over 40 characters, sensitive keys such as `token`, `code`, `key`, `secret`, `password`, `otp`, `state` and `session`, and any value a detector flags keep the key with an empty value. ID-like values become `:id`. - JavaScript errors: the message (scrubbed), the top 5 stack frames, with URLs reduced to origin and path. - Failed and slow (3 seconds or more) `fetch` and XHR requests: method, origin and templated path, status and duration. Never the query, headers or bodies. - Form interaction details: which fields were started, touched or invalid, and time in each field. Never values, lengths or keystrokes. - Device and browser context, once per batch: screen size, pixel ratio, time zone, CPU cores, device memory, touch, pointer, colour scheme, reduced motion and connection. On Chromium also the device model and OS version. - Web Vitals, long tasks and resource totals, through the insights module. Never collected: values typed into forms, passwords, payment data, credentials. Device traits are never used to identify a visitor: the visitor ID stays random. Raw IP addresses are never stored. List these categories in your own privacy notice. To keep a region out entirely, add `data-datacub-no-capture` to any element (the `datacub-no-capture` class also works): nothing inside it is captured. ### Choose what is collected In [Settings, Data capture](https://datacub.to/en/settings?tab=integrations) a project has six switches, all on by default: Button and link text, Page titles, URL query values, JavaScript errors, Failed network requests, Form interaction details. When one is off, datacub drops those fields at capture, even from a site that still sends them. A site can also stop its own SDK from sending them with the `capture` init option: set any of `text`, `title`, `query`, `errors`, `network` and `forms` to `false`, for example `datacub.init('pk_live_YOUR_PROJECT_KEY', { capture: { text: false, query: false } })`. The script tag has no attribute for this; use `datacub.init`. `insights: false` does not load the insights module at all (Web Vitals, long tasks, resource totals, form field details and device model). ### Content Security Policy If your site sets a Content Security Policy, `script-src` must allow your ingestion host for both `datacub-0.4.0.min.js` and `insights-0.2.0.min.js` (the module loads from `https://ingest.datacub.example/v1/sdk/insights-0.2.0.min.js`), and `connect-src` must allow the same host. ## What the SDK never sends Field values, passwords, payment data, credentials, URL fragments and anything inside an element with `class="datacub-no-capture"` or `data-datacub-no-capture`. IDs in paths are replaced (`/orders/1234` becomes `/orders/:id`). Values that look like emails, phone numbers, national IDs, card numbers or tokens are redacted on the device and again on the server. Details: [privacy](https://docs.datacub.to/consent#what-datacub-never-collects). --- # Install the mobile SDK `@datacub/react-native` is for React Native and Expo apps. Its logic is fully tested; runs on real Android and iOS simulators in CI are still being brought up. No runtime dependencies, about 5 KB with gzip. ## Install > Not published yet: `@datacub/react-native` is not on npm, and nothing under `@datacub` on npm belongs to datacub, so do not install it from there. Contact the datacub team for early access. The SDK works with these, which you install as usual: ```sh none npx expo install @react-native-async-storage/async-storage expo-application ``` `expo-application` is optional in bare apps: pass your own `app` values instead (below). ## Start it ```ts rn file=App.tsx import AsyncStorage from '@react-native-async-storage/async-storage' import * as Application from 'expo-application' import datacub from '@datacub/react-native' datacub.init('pk_live_YOUR_PROJECT_KEY', { storage: AsyncStorage, app: Application }) ``` Then add your app's bundle ID (iOS) or package name (Android), such as `sa.example.shop`, to the apps allowed to send in [Settings, General](https://datacub.to/en/settings?tab=general). Events from an app that is not on the list are refused. `pk_test_` keys also accept Expo Go while you develop. ## Options | Option | What it does | |---|---| | `storage` | where IDs and unsent events live between launches: AsyncStorage, or anything with `getItem`, `setItem`, `removeItem` (sync or async, so an MMKV wrapper works). Without it every launch is a new Guest and unsent events are lost when the app closes | | `app` | `{ applicationId, nativeApplicationVersion?, nativeBuildVersion? }`. `expo-application` already has that shape | | `apiHost` | your ingestion host or proxy. Default `https://ingest.datacub.example` | In a bare app without `expo-application`: ```ts rn import AsyncStorage from '@react-native-async-storage/async-storage' import datacub from '@datacub/react-native' datacub.init('pk_live_YOUR_PROJECT_KEY', { storage: AsyncStorage, app: { applicationId: 'sa.example.shop', nativeApplicationVersion: '2.3.0', nativeBuildVersion: '87' }, }) ``` ## Screens Screens are the app's page views. Send the screen's name or route template, never values from it. ```tsx types tab="React Navigation" file=App.tsx import { NavigationContainer, useNavigationContainerRef } from '@react-navigation/native' import { trackNavigation } from '@datacub/react-native/navigation' export default function App() { const ref = useNavigationContainerRef() return ( trackNavigation(ref)}> {/* your navigators */} ) } ``` ```tsx types tab="Expo Router" file=app/_layout.tsx import { Slot, useSegments } from 'expo-router' import { useEffect } from 'react' import datacub from '@datacub/react-native' export default function RootLayout() { const segments = useSegments() // the route template (/profile/[user]), never the path with values (/profile/sara) useEffect(() => datacub.screen(segments.join('/') || 'index'), [segments]) return } ``` ```ts rn tab=Manual import datacub from '@datacub/react-native' datacub.screen('Checkout') ``` The same name twice in a row counts once. Segments that look like IDs, emails or numbers are replaced (`Product/4512` becomes `Product/:id`). ## What it does on its own - **Sessions**: 30 minutes idle, 24 hours at most, kept across restarts. - **Delivery**: batches every 10 seconds or at 20 events, and when the app goes to the background. Retries with backoff when offline. Up to 1,000 events wait on the device. - **No lifecycle events**: opening and backgrounding the app send nothing, so they never inflate your active users. - **Never sent**: advertising IDs, device IDs, device model, carrier, location, contacts, screen size or time zone. Call `await datacub.flush()` to send what is queued now, for example before a test ends. ## Android backup Android Auto Backup restores app data on a new phone, so a restored install keeps its Guest ID. That is usually the same person. To give every install its own ID, set `android.allowBackup: false` in Expo, or exclude AsyncStorage's database (`RKStorage`) in `dataExtractionRules` in a bare app. --- # React, Next.js and TanStack No framework package is needed. Put the snippet in your HTML head once, and datacub follows every route change on its own. The SDK listens to the browser's History API, so React Router, TanStack Router, Next.js, Vue Router, SvelteKit and plain sites all report one page view per route change without extra code. ## Where the snippet goes Use the snippet from [install the web SDK](https://docs.datacub.to/install-web#in-an-app) (or from [Settings, Integrations](https://datacub.to/en/settings?tab=integrations), with your key filled in) and put it in the page's ``: | Framework | Where | |---|---| | Vite (React, Vue), TanStack Router, plain sites | `index.html`, inside `` | | Next.js App Router | `app/layout.tsx`: a `
``` Then use the global `datacub` in client code. For TypeScript, save [the type definitions](https://docs.datacub.to/install-web#typescript) in your project. ## Identify after login Call `identify` where your app learns who is signed in, and `reset` on logout. See [identifying users](https://docs.datacub.to/identify.md). ```tsx types file=src/use-analytics-user.ts import { useEffect } from 'react' export function useAnalyticsUser(user: { id: string } | null) { useEffect(() => { if (user) datacub.identify(user.id) }, [user]) } ``` ## Hash routers Routers that keep the route in the fragment (`/#/orders/12`) need `hashRouting`: ```ts web datacub.init('pk_live_YOUR_PROJECT_KEY', { hashRouting: true }) ``` --- # Page views and clicks datacub records page views, time on page, clicks and form submits by itself. ## Page views | Event | When | |---|---| | `$pageview` | on the first load, on every route change in a single page app, and when the browser restores a page from its back and forward cache | | `$pageleave` | when the user moves to the next page or hides the tab. Carries foreground time and how far they scrolled, in steps of 10% | Route changes are detected through the History API (`pushState`, `replaceState`, back and forward), 100 ms after the router updates the URL. A route that only rewrites the same path is not counted twice. Hash routers need `hashRouting: true` ([frameworks](https://docs.datacub.to/frameworks#hash-routers)). URLs are cleaned on the device: fragments are removed, query values are kept only when they read as codes, never what someone typed or anything sensitive (see [what the SDK collects](https://docs.datacub.to/install-web#what-the-sdk-collects)), IDs in paths become `:id`, `:uuid`, `:hash` or `:token`, and anything that looks like personal data becomes `:redacted`. UTM parameters and which ad network sent the visit (`gclid`, `fbclid` and others, never their values) are kept for the source reports. ## Clicks Clicks on links, buttons, `summary`, submit inputs and elements with an ARIA role of button, link, menu item or tab are captured as `$click`. The visible text of buttons and links is captured (scrubbed, at most 100 characters; [details](https://docs.datacub.to/install-web#what-the-sdk-collects)). Give important ones a readable name with `data-datacub-name`: ```html none Pricing ``` The name is what reports show, in any language your UI uses. Do not put user data in it: it is scrubbed like any other value. ## Form submits `$form_submit` records that a form was submitted: its `data-datacub-name`, its action path and how many fields it has. Never field names, values or labels. ```html none
...
``` ## A click is not an outcome A click on "Pay" is a click, and a form submit is an attempt. Neither says the payment went through. Track the outcome where your code knows it worked, so funnels stay right when a card is declined or a form shows an error: ```ts web async function pay(planId: string) { const res = await fetch('/api/checkout', { method: 'POST', body: JSON.stringify({ planId }) }) if (res.ok) datacub.track('checkout_completed', { plan: planId }) } ``` ## Leaving parts of the page out Add `class="datacub-no-capture"` or `data-datacub-no-capture` to an element and nothing inside it is captured, clicks or submits: ```html none
``` To turn off clicks and form submits everywhere, keeping page views: ```ts web datacub.init('pk_live_YOUR_PROJECT_KEY', { autocapture: false }) ``` ## In mobile apps Apps have screens instead of pages, and no automatic clicks. See [screens](https://docs.datacub.to/install-mobile#screens). --- # Custom events Track the moments that matter in your product with `datacub.track(name, properties)`. ```ts web datacub.track('signup_completed', { method: 'email' }) datacub.track('project_created', { template: 'blank', members: 3, trial: true }) ``` The same call works in React Native: ```ts rn import datacub from '@datacub/react-native' datacub.track('order_placed', { items: 2, total: 149.5, currency: 'SAR' }) ``` Call it after the action succeeds: when the server answered, the payment was confirmed, the file was saved. Not on the button click. [Choosing events](https://docs.datacub.to/event-naming.md). ## Names - 1 to 100 characters. Use `object_action` in snake case: `invite_sent`, `report_exported`. - Cannot start with `$` (those are datacub's own events). - Refused when they look like an identifier: 6 or more digits in a row, 16 or more hex characters, part of a UUID, or an `@`. Put IDs in properties of a known type instead, or leave them out. A refused call does nothing. On `localhost` the SDK prints why in the console. ## Properties Values can be strings, numbers, booleans, `null`, dates, arrays and objects: ```ts web datacub.track('report_exported', { format: 'csv', rows: 1200, scheduled: false, range: { from: new Date('2026-10-01'), to: new Date('2026-10-31') }, columns: ['users', 'sessions'], }) ``` | Rule | What happens | |---|---| | Up to 200 keys per event | the rest are dropped | | Short strings | a string over 256 characters or 12 words is free text and becomes `[redacted]` | | Objects nest 3 levels | deeper levels become `[depth]` | | Arrays | first 100 items | | Dates | sent as ISO 8601 UTC | | Functions, `undefined`, class instances, `NaN`, `Infinity` | dropped | ## What datacub removes on its own Keys named like secrets or personal data are dropped: password, OTP, PIN, CVV, card number, IBAN, Iqama, national ID, token, secret, session ID, cookie and others, in English and Arabic. Values that contain an email address, 9 or more digits (phone numbers, national IDs, cards, IBANs, in any digit script), bearer tokens or long key-like strings have that part replaced by `[redacted]`. The server repeats every check. This is a safety net, not a plan. Send product facts (`plan`, `step`, `count`, `currency`), never who someone is or what they typed. ## Delivery Events are batched: sent 5 seconds after the first one, at 20 events, or when the page is hidden or closed. Failed sends are retried with backoff. Each event has a unique ID, so a retry is never stored twice. --- # Naming events A handful of well named events answers more than a hundred vague ones. Start with five to eight. ## Track outcomes that mean something Page views and clicks are already captured. Custom events are for what datacub cannot see: that something worked. Good first events for most products: | Event | When it fires | Properties | |---|---|---| | `signup_completed` | the account was created | `method` | | `onboarding_step_completed` | each onboarding step, as one event | `step` | | `project_created` | the first moment someone gets value (yours may differ) | `template` | | `checkout_completed` | the server confirmed the payment | `plan`, `currency`, `value` | | `subscription_started`, `subscription_cancelled` | the subscription changed | `plan` | | `invite_sent` | a teammate was invited | `role` | ## The rules - **`object_action`, snake case, past tense**: `invoice_paid`, `report_exported`. Not `Clicked Pay Button` or `paymentSuccess`. - **One event with a property beats many events**: `onboarding_step_completed` with `{ step: 'profile' }`, not `onboarding_profile_done`, `onboarding_team_done`. - **Names never change**: a renamed event is a new event, and old charts stop matching. Pick carefully, then keep it. - **No values in names**: never `plan_pro_selected` or anything with an ID. Values go in properties. - **Properties are few, flat and repeatable**: plan names, steps, counts, true or false. Not free text, not who the user is. - **English names, any UI language**: names are for your team and your code. Reports show them as written. ```ts web // one event, the step as a property datacub.track('onboarding_step_completed', { step: 'profile' }) datacub.track('onboarding_step_completed', { step: 'invite_team' }) ``` ## Where to put the call Next to the code that does the action, after it succeeded. Then the event stays right when the button moves, the copy changes or a second screen does the same thing. ```ts web export async function inviteTeammate(email: string, role: 'admin' | 'member') { await api.createInvite({ email, role }) // the email stays in your system; datacub only needs the fact datacub.track('invite_sent', { role }) } ``` For funnels built from these events, see [funnels and retention](https://docs.datacub.to/funnels-retention.md). --- # Identifying users Call `datacub.identify(userId)` after login and `datacub.reset()` at logout. The user's earlier activity on that browser or phone is linked to them. ## After login or signup ```ts web async function login(email: string, password: string) { const user = await api.login(email, password) datacub.identify(user.id, { email: user.email, name: user.name }) return user } ``` Use your own stable internal user ID: the one in your database that never changes. Call `identify` again on every page load or app start while the user is signed in; with the same ID and no traits it sends nothing new. ## Name, email and phone Pass them as traits, so the **Users** page shows who a Registered user is and you can find them by email or phone: ```ts web datacub.identify('user_8f3a2c', { email: 'sara@example.sa', name: 'Sara Alqahtani', phone: '0551234567', plan: 'growth', // any other trait, under the same rules as event properties }) ``` - Pass traits at login and when they change (a profile edit), not on every page load: each call with traits sends them again. - datacub tidies them on the server: emails are trimmed and lowercased, phones become international format (a Saudi `05` mobile becomes `+9665...`; other countries need their `+` code). A value that does not parse is dropped, never stored as typed. - They describe the user; they never identify them. Two users with the same email or phone stay two users. - Only these three keys may carry contact data. An email in any other trait or in a `track()` property is still redacted. ## At logout ```ts web async function logout() { await api.logout() datacub.reset() } ``` `reset()` starts a new Guest ID and session. Without it, the next person on a shared phone or computer is counted as the last user. ## Workspaces and teams If your users belong to a company, team or workspace, pass its ID too. It is stored with every event, so you can count active companies, not only people. ```ts web datacub.identify(user.id, { account: workspace.id }) ``` ## IDs datacub refuses So that no personal data becomes a key, `identify` refuses user IDs that look like an email address, a Saudi national or Iqama ID, a Saudi mobile or a phone number in international format, a card number or a JWT, and placeholders such as `null`, `undefined`, `anonymous`, `guest` or `0`. The same rules apply to `account`. A refused call does nothing; on `localhost` the SDK says why in the console. If your user IDs are emails or phone numbers, send a different stable ID from your database instead, and pass the email or phone as a [trait](#name-email-and-phone). ## How linking works - Before `identify`, the user is a **Guest**: a random ID kept in a first-party cookie (web) or app storage (mobile). - `identify` links that Guest's earlier activity to the user, who is now **Registered**. - The same user on a laptop and a phone: each device links when they sign in there with the same ID. - A different user signs in on the same device: the SDK resets first, so two people are never merged. - datacub never matches users by IP address, device traits, email or phone. More in [Guests and Registered users](https://docs.datacub.to/guests-and-registered.md). ## If you ask for consent first With [consent first](https://docs.datacub.to/consent.md) turned on, `identify` before `datacub.consent.grant()` is kept in memory and applied at grant. Nothing is stored or sent before that. ## In React Native The calls are the same: ```ts rn import datacub from '@datacub/react-native' datacub.identify('user_8f3a2c', { account: 'ws_51', email: 'sara@example.sa' }) // at logout datacub.reset() ``` --- # User properties Tell datacub who a signed in user is with traits on `identify`, and describe what they do with properties on events. ## What datacub knows about a user | Property | Where it comes from | |---|---| | User ID | `datacub.identify(userId)`: your own stable internal ID | | Name, email, phone | `datacub.identify(userId, { name, email, phone })`, shown on the **Users** page and searchable | | Other traits | `datacub.identify(userId, { plan: 'growth', role: 'admin' })` | | Account | `datacub.identify(userId, { account })`: their company, team or workspace ID | | First and last seen, sessions, devices, countries, sources | worked out by datacub from their events | | Everything they did | page views, screens, clicks and your custom events, with properties | The **Users** page in the dashboard shows each user's timeline, built from these. ## Traits ```ts web datacub.identify(user.id, { name: user.name, email: user.email, plan: 'growth', seats: 5 }) ``` Traits are sent with `$identify` the first time a user is identified on a browser or phone, and as `$set` when you call `identify` again with traits for the same user. Send them at login and when they change, not on every page load. [The rules for name, email and phone](https://docs.datacub.to/identify#name-email-and-phone). ## Facts belong on events Send the plan, the role or the step as a property of the event where it matters. Each event keeps the value it had at that moment, so a user who upgrades still counts as `free` in last month's funnel. ```ts web datacub.identify(user.id, { account: workspace.id }) datacub.track('subscription_started', { plan: 'growth', billing: 'yearly', seats: 5 }) ``` ## Never send National or Iqama IDs, addresses, passwords, or anything a user typed, in any trait or property. Name, email and phone go only in their own three traits; anywhere else they are redacted ([what datacub removes](https://docs.datacub.to/custom-events#what-datacub-removes-on-its-own)). --- # Guests and Registered users Every user starts as a Guest. After `identify`, they are Registered, and their Guest history comes with them. | | Guest | Registered | |---|---|---| | Who | someone datacub has not been told about | someone your app identified with `datacub.identify(userId)` | | ID | a random ID made by the SDK, unrelated to the person or device | your own user ID | | Shown as | Guest | their name or email if you pass them as [traits](https://docs.datacub.to/identify#name-email-and-phone), else their user ID | | Across devices | each browser and phone is a separate Guest | every device where they sign in links to the same user | | Lasts | until cookies or app data are cleared (see below) | as long as you keep calling `identify` | A Guest ID is random. It is not built from the device, the IP address or anything about the person, so it identifies a browser, not a human. datacub calls these users Guests, not anonymous: the ID is pseudonymous, and once linked by `identify` it belongs to a Registered user. ## How long a Guest ID lasts **Web**: a first-party cookie (`datacub_id`) on your site's own domain, written when the SDK starts (or after `datacub.consent.grant()` if the project asks for [consent first](https://docs.datacub.to/consent.md)). It lasts up to 400 days and is renewed when a session starts. Safari deletes cookies set by scripts after 7 days without a visit, so a Safari user who returns later is a new Guest until they sign in. If the browser refuses cookies, the SDK keeps IDs in memory and every page load is a new Guest. **Mobile**: kept in the storage you pass to `init` (AsyncStorage). It survives restarts and updates, not a reinstall. Without `storage`, every launch is a new Guest. ## Sessions A session ends after 30 minutes without activity, or after 24 hours. It does not split at midnight. On the web all tabs of your site share one session. ## What changes at identify ```ts web // a Guest: page views and clicks carry the Guest ID datacub.identify('user_8f3a2c') // now Registered; earlier Guest activity on this browser is linked datacub.reset() // logout: a new Guest ID and session ``` After `reset()`, the old Guest ID is not reused. The next person on that device starts fresh. --- # Subdomains and other domains Subdomains of one site share users and sessions on their own. Separate domains link through sign in. ## Subdomains: automatic The SDK writes its cookies on your registrable domain, so `www.example.sa`, `app.example.sa` and `shop.example.sa` share one Guest ID and one session. Install the SDK with the same project key on each, and allow each one in the sites allowed to send. `*.example.sa` allows every subdomain; add `example.sa` too if the bare domain serves pages. ```ts web // the same key on www.example.sa and app.example.sa datacub.init('pk_live_YOUR_PROJECT_KEY') ``` ## Different domains: through identify `example.sa` and `example.com` cannot share a cookie, so a user is a separate Guest on each. When they sign in on both, `datacub.identify` with the same user ID links both to one Registered user. datacub does not pass IDs between domains in links or URLs. That would put an identifier in the address bar, in referrers and in other tools' logs. ## Website and app The same applies to your website and your mobile app: separate Guests, linked when the user signs in to both with the same ID. Use one project for both if you want them in the same reports; allow the site and the app in [Settings, General](https://datacub.to/en/settings?tab=general). --- # Asking for consent (optional) By default datacub tracks from the first page view. There is no banner to wire and no call to make. If you want to wait for your visitors' consent first, you can turn that on. Whether you need consent depends on your site and your users. Turn this on if you collect consent. ## Turn it on 1. In your project, open Settings and turn on **Ask for consent first**. 2. Add `requireConsent: true` to `datacub.init`. On the script tag, add the `data-require-consent` attribute instead. 3. Call `datacub.consent.grant()` when the visitor agrees, and `datacub.consent.revoke()` when they withdraw. ```ts web datacub.init('pk_live_YOUR_PROJECT_KEY', { requireConsent: true }) // the visitor accepted analytics datacub.consent.grant({ method: 'banner', policyVersion: '2026-10' }) // the visitor withdrew it later datacub.consent.revoke() ``` With the script tag: ```html script ``` The install snippet in your project settings adds these lines for you when the setting is on. ## Before the visitor agrees | Call | What happens | |---|---| | before `grant()` | no cookies, no storage, no network requests. Events tracked now are not kept. The datacub server also refuses any event that does not carry a grant | | `datacub.consent.grant(options?)` | the SDK writes its cookie, records a `$consent` event and the current page view, and starts sending | | `datacub.consent.revoke()` | stops sending, deletes the SDK's cookies and the queue. Nothing tracked before the revoke is sent later | `grant` options, all optional: | Option | Values | |---|---| | `method` | where the visitor agreed: `banner`, `settings`, `api` or `cmp` (a consent management platform) | | `policyVersion` | the version of your privacy notice they agreed to, up to 64 characters | | `overrideGPC` | see [Global Privacy Control](#global-privacy-control) | The web SDK does not remember a grant between page loads. Your banner or consent platform already stores the visitor's answer: call `grant()` on each page load while it says yes. The mobile SDK keeps the grant in its storage, but call `grant()` at every launch after the user has agreed anyway, so the SDK follows your app's own record. `identify` before `grant()` is kept in memory and applied at the grant. ## With a consent platform Call `grant` and `revoke` from your platform's callbacks. If the platform loads before the SDK file, use the [queue snippet](https://docs.datacub.to/install-web#in-an-app); calls wait in order. Add a `consent` stub to it so early calls are kept: ```html script ``` ```ts web datacub.init('pk_live_YOUR_PROJECT_KEY', { requireConsent: true }) onAnalyticsConsent(() => datacub.consent.grant({ method: 'cmp' })) onAnalyticsConsentWithdrawn(() => datacub.consent.revoke()) ``` In React Native, pass the same option: ```ts rn import AsyncStorage from '@react-native-async-storage/async-storage' import datacub from '@datacub/react-native' datacub.init('pk_live_YOUR_PROJECT_KEY', { storage: AsyncStorage, requireConsent: true }) // once the user has agreed: your app keeps their answer; call it at every launch if (await hasAnalyticsConsent()) datacub.consent.grant() ``` ## Opting out, in every project This part applies whether or not you ask for consent first. - `datacub.consent.revoke()` always works, and datacub remembers it on that device. On the web it sets a first-party cookie, `datacub_optout=1`, for 400 days. It contains no identifier. On mobile it is a flag in the SDK's stored value. - When the SDK starts, a stored opt-out means nothing is sent. - An explicit `datacub.consent.grant()` clears the opt-out. For example, a "stop tracking me" button in your privacy settings: ```ts web datacub.init('pk_live_YOUR_PROJECT_KEY') function onStopTrackingClick() { datacub.consent.revoke() } ``` ## Global Privacy Control If the browser sends Global Privacy Control (GPC), datacub treats it as an opt-out: when the SDK starts, nothing is sent, and `grant()` does nothing. Only when the visitor explicitly opts in on your site, for example in your privacy settings, pass `overrideGPC: true`: ```ts web // only from the visitor's own click on an opt-in control function onAnalyticsToggleOn() { datacub.consent.grant({ method: 'settings', overrideGPC: true }) } ``` ## What datacub never collects This holds in every project, with or without consent first. - field values or URL fragments (button and link text, page titles and URL query values are collected, scrubbed, and you can turn each off in [Settings, Data capture](https://docs.datacub.to/install-web#choose-what-is-collected)) - passwords, OTPs, card data, IBANs, national or Iqama IDs, tokens: dropped or redacted on the device and again on the server - raw IP addresses: used in memory for the country and city and for rate limits, then dropped, never stored - device fingerprints or advertising IDs Where data is stored and how long it is kept is in datacub's privacy notice. ## Your part You choose whether to ask for consent and what basis applies to your users. datacub gives you the switch; it does not decide for you. Keep properties free of personal data, use your own internal ID for `identify`, and call `reset()` at logout. When someone asks for their data to be deleted, see [deleting a person's data](https://docs.datacub.to/deleting-data.md). --- # Deleting a person's data When someone asks you to delete their data, or to see it, do it in datacub too: from their profile in the dashboard, or from your backend. You decide when a request is valid; datacub does the work. Only owners and admins, signed in as themselves, can do it from the dashboard. ## From the dashboard Open the person on the **Users** page and choose **Delete this person's data**, then **Delete for good**. It works for a Registered user and for a Guest. ## From your backend Call datacub from your server when your own account deletion runs, so both happen together. Use a read key (`rk_`) of the workspace that an owner has allowed to handle person requests; the project ID is in [Settings, General](https://datacub.to/en/settings?tab=general). Make one with **New read key** under **Read keys** in [Settings, Integrations](https://datacub.to/en/settings?tab=integrations); it is shown once. A read key reads reports by default. To let it delete and export people, an owner turns on **Can delete and export a person's data** for that key, under **Read keys** in [Settings, Integrations](https://datacub.to/en/settings?tab=integrations). Without it every call below answers `403 capability_required`. ```ts types tab=TypeScript file=delete-from-x.ts // on your server only: a read key opens your dashboard, never ship it to a browser or app export async function deleteFromX(userId: string) { const url = `https://docs.datacub.to/api/backend/projects/${process.env.DATACUB_PROJECT_ID}/persons/user/${encodeURIComponent(userId)}` const res = await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${process.env.DATACUB_READ_KEY}` }, }) if (res.status !== 202) throw new Error(`datacub deletion failed: ${res.status}`) return (await res.json()) as { id: string; status: 'deleted' | 'held' } } ``` ```sh none tab=curl curl -X DELETE "https://docs.datacub.to/api/backend/projects/$DATACUB_PROJECT_ID/persons/user/user_8f3a2c" \ -H "Authorization: Bearer $DATACUB_READ_KEY" ``` | Path | Deletes | |---|---| | `DELETE /api/backend/projects/:id/persons/user/:userId` | a Registered user, by the ID you pass to `identify`, and every browser and phone linked to them | | `DELETE /api/backend/projects/:id/persons/browser/:anonId` | a Guest, by the ID in the `datacub_id_` cookie | The answer is `202` with `{ "id": "...", "status": "deleted" }`, or `"held"` during a [legal hold](#legal-hold). | Error | Means | |---|---| | `401 unauthenticated` | the key is wrong or revoked, or not of this project's workspace | | `403 capability_required` | an owner has not allowed this key to handle person requests | | `400 invalid_person` | the ID is not one datacub can hold | | `429 rate_limited` | over 60 calls a minute for this key; wait a minute | ## Exporting a person's data When someone asks what you hold about them, get everything datacub holds in one JSON file: ```ts types file=export-from-x.ts export async function exportFromX(userId: string) { const url = `https://docs.datacub.to/api/backend/projects/${process.env.DATACUB_PROJECT_ID}/persons/user/${encodeURIComponent(userId)}/export` const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.DATACUB_READ_KEY}` } }) if (!res.ok) throw new Error(`datacub export failed: ${res.status}`) return (await res.json()) as { format: 'datacub.person_export.v1'; traits: Record; events: unknown[] } } ``` The file holds their user ID and linked browsers, their latest traits (name, email, phone and others), their consent events, every event with its properties, their feedback answers, and how many notes your team keeps about them (not the notes' words). Each export is recorded in your workspace's audit log, without the person's ID. The same works for a Guest: `persons/browser/:anonId/export`. ## When someone withdraws consent If a user withdraws consent somewhere your backend sees (an account setting, a support request), report it. datacub deletes what it collected, the same way: ```ts types file=revoke-in-x.ts // anon_id is the Guest ID from the datacub_id_ cookie (: 8 characters of your pk_ key after pk_live_) your own server receives; or send user_id export async function revokeInX(who: { user_id: string } | { anon_id: string }) { const url = `https://docs.datacub.to/api/backend/projects/${process.env.DATACUB_PROJECT_ID}/consent/revoke` const res = await fetch(url, { method: 'POST', headers: { Authorization: `Bearer ${process.env.DATACUB_READ_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify(who), }) if (res.status !== 202) throw new Error(`datacub revoke failed: ${res.status}`) } ``` In the browser, also call `datacub.consent.revoke()` so the SDK stops and clears its cookies ([consent](https://docs.datacub.to/consent.md)). ## What is deleted, and when **At once**: the person's events and traits, the links between their browsers, phones and user ID, your notes about them, their feedback answers and the records of who viewed their profile. They leave every report, funnel and profile immediately. **48 hours later**: datacub deletes again, to catch events that were still on their way, and removes the rows from storage for good. Backups that held them expire within 35 days. After that datacub keeps only a one-way hash of the ID, to prove the request was done and to repeat it if a backup is ever restored. datacub's own limits for every request: unlinked within 1 hour, out of every answer within 7 days, removed from storage within 30 days. ## Legal hold If datacub is required by law to keep a project's data, for example by a court order, the project is under a legal hold. Requests are still accepted and recorded, answered `held`, and carried out as soon as the hold is lifted. ## New events after a deletion datacub stops accepting events for a deleted user ID, so a page left open cannot bring the person back. A deleted Guest ID is refused for 30 days. If the same person signs up again and you want to track them, allow their user ID again: ```sh none curl -X DELETE "https://docs.datacub.to/api/backend/projects/$DATACUB_PROJECT_ID/tombstones/user/user_8f3a2c" \ -H "Authorization: Bearer $DATACUB_READ_KEY" ``` Only what they do from then on is collected; nothing deleted comes back. --- # Project keys Each project has a public key for sending events. It goes in your client code; it cannot read anything. ## Key types | Prefix | Use | Where it may appear | |---|---|---| | `pk_live_` | sending events from your live site or app | client code, public | | `pk_test_` | development: also accepts `localhost`, `127.0.0.1` and Expo Go | client code, public | | `rk_` | a read key: opens your workspace's dashboard | never in client code | | `datacub_mcp_` | connecting an AI tool through [MCP](https://docs.datacub.to/ai.md) | never in client code | A `pk_` key can only send events, and only from the places you allow. That is why it is safe to ship. The SDKs refuse a key that starts with `sk_` in any environment: a secret in a browser or app is a leaked credential. Find the key in [Settings, Integrations](https://datacub.to/en/settings?tab=integrations), under **Write keys**. ## Allowed websites and apps datacub accepts events only from: - **sites** on the project's list: a domain such as `shop.example.sa`, or `*.example.sa` for every subdomain (not the bare domain: add it too if it serves pages) - **apps** whose bundle ID or package name is on the project's list, such as `sa.example.shop` Both lists are in [Settings, General](https://datacub.to/en/settings?tab=general), under **Where data may come from**. Government, education, health and military sites are reviewed by datacub before any of their events are stored. A request from anywhere else is refused with `403 origin_not_allowed` or `403 app_not_allowed`, and the SDK stops sending for that page or launch. These checks stop your key being used on someone else's site by accident. They are not a secret: anyone can still send requests that claim to be your site, so treat incoming events as data, not proof. ## Test and live Use a `pk_test_` key while you build, ideally in a separate project, so test traffic never mixes with real users. datacub accepts events from `localhost`, `127.0.0.1` and Expo Go only with a test key; a live key is refused there. Every new project comes with a test key, marked **Test** in [Settings, Integrations](https://datacub.to/en/settings?tab=integrations); **New test key** makes another. Put the test key in development builds and the live key in production. With Vite, write `datacub.init('%VITE_DATACUB_KEY%')` in the snippet in `index.html` and set `VITE_DATACUB_KEY` in `.env.development` and `.env.production`. ## Changing keys A project can have two keys at once, so you can switch without a gap: in [Settings, Integrations](https://datacub.to/en/settings?tab=integrations), create a new key, ship it, then revoke the old one. A revoked key stops working within 15 seconds. A `pk_` key is public by design, so a copy is not a breach. Switch keys if someone sends junk with it. --- # Funnels and retention Funnels and retention are built in the dashboard from the events you already send. Nothing extra goes in your code. Days, weeks and months are cut in the project's time zone (Settings), so everyone on the team sees the same numbers. To read them in your own time zone instead, choose **Mine** under Report time zone in [Account settings](https://datacub.to/en/settings/account). Daylight saving changes are handled: such a day has 23 or 25 hours. ## Funnels A funnel is a list of up to 6 steps, such as *viewed pricing*, *clicked upgrade*, *checkout completed*. datacub counts how many users get from one step to the next within a time you choose (5 minutes to 90 days) and shows where the rest stopped. A step can be: | Step | Comes from | |---|---| | a page visited | automatic page views (or screens in apps) | | a click | automatic clicks; named ones read best (`data-datacub-name`) | | an event from your product | `datacub.track(...)` | Build one in **Funnels**: pick a starting point, and datacub shows what most users did next. If you add an event datacub has not seen yet, the dashboard shows the `datacub.track` line to add. ### Make funnels reliable - End funnels on outcomes your code confirmed (`checkout_completed`), not on clicks. Clicks happen whether or not the payment worked. - Name the buttons that matter, so a step reads *Clicked "upgrade_plan"* and survives a redesign: ```html none ``` - Call `identify` at login. A user who starts on their phone and finishes on their laptop then counts once, as one user. ## Retention **Engagement** answers *do people come back?*: of the users who first used your product on a given day or week, how many were active again the next day, after 7 days and after 30 days. Activity is a page view, a screen view or an event your product sends. Leaving a page is not activity, and the mobile SDK sends nothing when the app goes to the background, so retention is not inflated by people who only opened the app. ### Make retention reliable - Identify signed in users, so returning on another device counts as coming back, not as a new user. - Track the action that means real use (`report_viewed`, `order_placed`), so you can tell visiting from using. - Keep calling `reset()` at logout: otherwise two people on one device look like one loyal user. --- # Team Invite your team to your workspace. Everyone in it can open its projects, with what their role allows. ## Roles | Role | Can | |---|---| | Owner | everything, including deleting a project and making other owners | | Admin | settings and the team: rename projects, the public link, invite, change roles, remove members | | Analyst | all analytics, including individual users and their timelines | | Viewer | totals only, no individual users | A workspace always keeps at least one owner. Only an owner can make someone an owner or change another owner's role. ## Invite someone Open [Settings, Team](https://datacub.to/en/settings?tab=team) and choose **Invite someone**. Enter their email and a role, then **Create invitation**: datacub gives you an invitation link. Send it to them yourself. The link works once, for 7 days, only for that email address, and is not shown again. Inviting the same address again replaces the old link. They open the link, set their name and a password (at least 12 characters), and join. ## Change a role or remove someone Admins change roles and remove members from the same list. Removing someone signs them out of the workspace at once. Anyone can leave a workspace themselves, except its last owner. ## Billing is the workspace's Plans and payment belong to the workspace, not to a person. Invited members are never billed. See [billing and usage](https://docs.datacub.to/billing.md). ## Share a public link An admin can turn on a public link in Settings. Anyone with it sees the overview cards (users, pages, sources, places and devices) for the last 7, 30 or 90 days, this month or last month. No filters, no users, no events of your own. Numbers on a public link are rounded to the nearest 10 and shown as "about 40"; anything from 1 to 9 shows as "Fewer than 10", and 0 stays 0. Exact numbers stay in your own dashboard. Turning the link off, or making a new one, stops the old address at once. --- # Billing and usage Billing belongs to your workspace. Its plan sets how many events all its projects can send each month, together. ## Who pays The workspace, through the owner who manages its plan. Members you invite are never billed. Everyone in the workspace can see the plan and usage; only owners change the plan, cancel, or see invoices and payments. ## What counts Every stored event from every project in the workspace: page views, page leaves, clicks, form submits, screens, consent and identify events, and your custom events. These do not count: events from bots, duplicates from retries, and anything datacub refused. Usage is updated about every 10 minutes and resets at the start of each calendar month, counted in UTC (midnight UTC is 3 AM in Riyadh). The time zone your reports use never changes your usage or your billing dates. ## Nearing the limit Once you pass 80% of the allowance, every project page in the dashboard shows a notice, so you can upgrade before anything changes. ## Over the limit Tracking does not stop and nothing already stored is touched: | Usage this month | What datacub does | |---|---| | up to the allowance | stores every event | | up to the grace (20% over, unless agreed otherwise) | still stores every event | | beyond the grace | keeps a fixed 10% of users, chosen the same way all month, and marks reports as sampled. The rest are not stored until the month resets or a higher plan is paid for. Upgrading now (a prorated payment for the rest of your billing period) applies within about 10 minutes of the payment; an upgrade at renewal applies from the renewal | You are never charged for going over. Because whole users are kept, funnels and retention for the sampled users stay correct. ## When a trial ends If a trial ends without a paid plan, datacub stops accepting new events (the SDK gets `403 ingestion_paused` and stops for that page or launch). Everything already collected stays in the dashboard. Choosing a plan starts collection again. ## Invite a friend When datacub runs an invite offer, your link is in [Account settings](https://datacub.to/en/settings/account). A friend who signs up with it gets two months of Starter free straight away; you get two months of Starter once they move to any paid plan. Rewards count for your first 12 friends who subscribe, each new account counts once, and signups that look like the same person or company are checked by our team before anything is granted. ## Where to see it Your workspace's plan and this month's usage are in [Settings, Billing](https://datacub.to/en/settings?tab=billing). --- # AI coding agents and MCP Let Claude Code, Cursor, Codex or ChatGPT set up datacub for you. Paste one prompt; it reads your app, works out what your business does, installs datacub and tracks the few actions that matter. ## Setup prompt Copy the prompt for your platform and paste it into your coding agent. It installs the SDK, identifies signed in users, adds three to five events for the actions that show your product works, and checks that an automatic event and one of its events really reach datacub. It never tracks every button and never sends personal data. The same prompt, filled in with your project key, is in [Settings, MCP and AI](https://datacub.to/en/settings?tab=ai). ```text none You are connecting datacub to this website or web app. In short: 1. add datacub's script to the page, 2. track the 3 to 5 actions that matter, for example signup_completed right after someone signs up, 3. check that a real visit and one of those actions reach datacub. The numbered steps below say exactly how. datacub is privacy-first product analytics: it shows how people find the product, start using it (activation), keep using it (engagement), pay (conversion) and come back (retention). Do the whole setup yourself, from the code. Do not ask me to describe the business or to pick event names: work them out from the repository. Keep the change small and touch nothing unrelated. Project Public ingestion key: not filled in yet: ask me for it (it starts with pk_live_ or pk_test_; datacub shows it under Settings, Integrations) These keys are public: they can only send events, so they are safe in client code. Never put any other datacub credential (read keys rk_, MCP tokens datacub_mcp_) in code, and never print secrets from .env files. 1. Inspect the repository Read the README, the package manifests, the routes or screens, the data models and the main flows before changing anything. 2. Understand the business Say in one or two sentences what the product does and for whom, from the code. 3. Find the core customer journey Sign up, the first moment of value (activation), the action people repeat, and paying or subscribing, where each exists. 4. Discover the framework and architecture Entry points, client versus server code, the router or navigation, how login works. 5. Install the official datacub SDK Web (any site or framework). The SDK is not on npm: datacub serves it as a script. Never install an npm package named @datacub/web, @datacub/react-native or anything else under @datacub: datacub has published nothing on npm yet. Paste this in the HTML : index.html for Vite and plain sites. In JSX (the root layout in Next.js or TanStack Start) never paste raw script text between tags: put the snippet's code (what is between ) in Then use the global datacub in client code only (event handlers, effects), never in code that runs on the server. For TypeScript, save https://ingest.datacub.example/v1/sdk/datacub-0.4.0.d.ts as datacub.d.ts in a folder the tsconfig include covers (src/ for Vite, the project root for Next.js): it types the global datacub. Page views, route changes in single page apps, and clicks on buttons and links are captured automatically. Do not add page view or click tracking yourself. To give an important button a readable name in reports, add data-datacub-name="upgrade_plan" to it. The site's domain must be in the project's allowed websites (datacub dashboard, Settings), or datacub refuses its events. On localhost only a test key (pk_test_) is accepted. 6. Automatic analytics Page views, route changes in single page apps, and clicks on buttons and links are captured automatically once datacub.init runs. Do not add your own page view or click tracking. 7. Consent Nothing to add: datacub tracks from the first page view or screen. Do not add a consent banner or datacub.consent calls for datacub. 8. Identify signed-in users After login or signup succeeds, call datacub.identify(user.id) with the app's own stable internal user id. Never use an email address, phone number, national ID or name as the id. Optionally pass { email, name, phone } as the second argument when the user's account has them, at login or when they change, not on every page load: datacub.identify(user.id, { email: user.email, name: user.name }). On logout call datacub.reset(), or the next person on the device inherits the last user's activity. 9. Choose 3 to 5 business events From the journey in step 3, pick the 3 to 5 actions that show the product is working for someone, for example signup_completed, project_created, checkout_completed, subscription_started, teammate_invited. Name them object_action in snake case. Decide yourself; do not wait for me. 10. Instrument them as custom events Track successful outcomes where the code knows the action succeeded (after the API call resolves, in the success branch), not the button click: datacub.track('signup_completed', { method: 'email' }). Add a few flat, low-cardinality properties (plan, step, count, true or false). Put each call next to the code that does the action. 11. Stay clean No passwords, OTPs, tokens, API keys, card data, IBANs, national or Iqama IDs, emails, phone numbers, names, addresses, free text a person typed, or IDs in event names or property values (the identify traits above are the only place for email, name and phone). No duplicate events: one call per outcome, check for existing analytics calls first, never inside code that re-runs on render. No unrelated refactors or formatting changes. 12. Verify for real Run the app, open a page or screen (an automatic event), then do one of the business actions (a custom event). Each must reach datacub: the POST to https://ingest.datacub.example/v1/batch answers 200 with "accepted" of 1 or more. A 403 names the reason, for example origin_not_allowed (the site must be added to the project's allowed websites) or localhost_live_key (use the test key). Events are sent in small batches: wait 5 seconds before you leave or close the page. A headless or automated browser (Playwright, Puppeteer) counts as a bot: its events are stored but left out of reports, so check the POST answers, not the reports. The datacub setup page turns green by itself when the first automatic event and then the first custom event arrive in a normal browser. Only report what you actually saw. Feature flags and A/B tests: skip this unless I ask for one. Then add right after the datacub snippet, and use await datacub.flag('key') (true or false) or await datacub.experiment('key') ('A' the original, 'B' the new version). datacub.experiment records that the user saw the version, so call it where that version is actually shown. Use the key of a flag or experiment created in datacub (Feature flags or Experiments); never invent one. A flag is never a permission check: keep those on the server. 13. Report briefly What you installed and where datacub.init lives, each event and where it fires, what you verified and what you could not, and anything I must do (allow a domain). ``` For a React Native or Expo app: ```text none You are connecting datacub to this mobile app. In short: 1. add datacub's SDK, 2. track the 3 to 5 actions that matter, for example signup_completed right after someone signs up, 3. check that a real session and one of those actions reach datacub. The numbered steps below say exactly how. datacub is privacy-first product analytics: it shows how people find the product, start using it (activation), keep using it (engagement), pay (conversion) and come back (retention). Do the whole setup yourself, from the code. Do not ask me to describe the business or to pick event names: work them out from the repository. Keep the change small and touch nothing unrelated. Project Public ingestion key: not filled in yet: ask me for it (it starts with pk_live_ or pk_test_; datacub shows it under Settings, Integrations) These keys are public: they can only send events, so they are safe in client code. Never put any other datacub credential (read keys rk_, MCP tokens datacub_mcp_) in code, and never print secrets from .env files. 1. Inspect the repository Read the README, the package manifests, the routes or screens, the data models and the main flows before changing anything. 2. Understand the business Say in one or two sentences what the product does and for whom, from the code. 3. Find the core customer journey Sign up, the first moment of value (activation), the action people repeat, and paying or subscribing, where each exists. 4. Discover the framework and architecture Entry points, client versus server code, the router or navigation, how login works. 5. Install the official datacub SDK React Native or Expo: datacub's React Native SDK is not published yet, so nothing can connect this app today. Do not install anything and do not fake a connection. Still do steps 1 to 4 and 9, so the event plan is ready, then stop and tell me that datacub's mobile SDK is in early access and that I should contact the datacub team. Swift, Kotlin, Flutter and other native stacks are not supported yet: say so plainly. Never install an npm package named @datacub/web, @datacub/react-native or anything else under @datacub: datacub has published nothing on npm yet. 6. Automatic analytics Screen views come from the navigation helper of the SDK; do not add your own. 7. Consent Nothing to add: datacub tracks from the first page view or screen. Do not add a consent banner or datacub.consent calls for datacub. 8. Identify signed-in users After login or signup succeeds, call datacub.identify(user.id) with the app's own stable internal user id. Never use an email address, phone number, national ID or name as the id. On logout call datacub.reset(), or the next person on the device inherits the last user's activity. 9. Choose 3 to 5 business events From the journey in step 3, pick the 3 to 5 actions that show the product is working for someone, for example signup_completed, project_created, checkout_completed, subscription_started, teammate_invited. Name them object_action in snake case. Decide yourself; do not wait for me. 10. Instrument them as custom events Track successful outcomes where the code knows the action succeeded (after the API call resolves, in the success branch), not the button click: datacub.track('signup_completed', { method: 'email' }). Add a few flat, low-cardinality properties (plan, step, count, true or false). Put each call next to the code that does the action. 11. Stay clean No passwords, OTPs, tokens, API keys, card data, IBANs, national or Iqama IDs, emails, phone numbers, names, addresses, free text a person typed, or IDs in event names or property values. No duplicate events: one call per outcome, check for existing analytics calls first, never inside code that re-runs on render. No unrelated refactors or formatting changes. 12. Verify for real Run the app, open a page or screen (an automatic event), then do one of the business actions (a custom event). Each must reach datacub: the POST to https://ingest.datacub.example/v1/batch answers 200 with "accepted" of 1 or more. A 403 names the reason, for example origin_not_allowed (the site must be added to the project's allowed websites) or localhost_live_key (use the test key). Events are sent in small batches: wait 5 seconds before you leave or close the page. A headless or automated browser (Playwright, Puppeteer) counts as a bot: its events are stored but left out of reports, so check the POST answers, not the reports. The datacub setup page turns green by itself when the first automatic event and then the first custom event arrive in a normal browser. Only report what you actually saw. 13. Report briefly What you installed and where datacub.init lives, each event and where it fires, what you verified and what you could not, and anything I must do (allow a domain). ``` ## MCP server datacub runs a Model Context Protocol server, so Claude Code, Cursor, Codex and other MCP tools can read your analytics and check your integration. It sees what your team role sees in the dashboard, in totals only. ### 1. Create a token Open [Settings, MCP and AI](https://datacub.to/en/settings?tab=ai) in the dashboard, then **Tokens**: - **Access**: read only (the default), or read and register events, which also lets the tool declare your events and their properties. Registering needs the analyst role or above. - **Projects**: this project only, or every project of your team. - **Expires in**: 7, 30 or 90 days, or 1 year. The token starts with `datacub_mcp_` and is shown once. Keep it like a password, never in client code. It belongs to you: it works with your current team role and stops when it expires, when you revoke it, or when you leave the team. ### 2. Connect your tool The server is your datacub address followed by `/mcp`. The settings page shows these with your address and token filled in. ```sh none tab="Claude Code" claude mcp add --transport http x https://docs.datacub.to/mcp \ --header "Authorization: Bearer datacub_mcp_YOUR_TOKEN" ``` ```json none tab=Cursor { "mcpServers": { "x": { "url": "https://docs.datacub.to/mcp", "headers": { "Authorization": "Bearer datacub_mcp_YOUR_TOKEN" } } } } ``` ```toml none tab=Codex # ~/.codex/config.toml, then: export DATACUB_MCP_TOKEN=datacub_mcp_YOUR_TOKEN [mcp_servers.x] url = "https://docs.datacub.to/mcp" bearer_token_env_var = "DATACUB_MCP_TOKEN" ``` ### ChatGPT and other apps that sign in with OAuth No token to paste: add datacub as a connector with the server address `https://docs.datacub.to/mcp` and OAuth sign-in. The app opens datacub, where you choose what it may do (read only unless you tick registering events, which needs the analyst role) and which projects, then you are sent back. It shows up in your token list as a connected app; revoking it there ends its access at once. Access tokens last an hour and renew themselves for up to 90 days. Right after creating a token, **Test connection** checks it. Later, **Last used** in the token list shows whether your tool is reaching datacub. ### What your tool can do | Tool | What it does | |---|---| | `list_projects`, `get_project` | your projects, their time zone, allowed websites and apps | | `get_sdk_setup`, `get_docs` | install steps for web or React Native, and short reference | | `get_integration_status` | the first and newest event, events in the last 24 hours, the SDK | | `list_event_definitions`, `get_event_schema` | events received, with counts, and the events your team declared | | `register_event_definition` | declare an event, what it means and its properties (write access) | | `list_flags`, `create_flag` | the project's feature flags and experiments; create one when you ask for it (write access) | | `query_analytics` | one question in the dashboard's [query model](https://datacub.to/openapi.json) | | `funnel`, `retention`, `feature_adoption` | the same numbers as the dashboard pages | | `investigate_event`, `investigate_users` | one event, or a group of users, in totals | Lists return `next_cursor` for the next page. A tool that cannot answer returns `{"error": "...", "message": "..."}`; arguments that do not fit a tool's input schema are refused by the MCP layer itself, with the standard invalid params error. A token can make 120 requests a minute. ### What it never does - It never lists individual people, event rows or sessions. Profiles stay in the dashboard, where every view is recorded. - It never gives an exact count. Every count is rounded to the nearest 10 (the answer says `"approx": true`); 1 to 9 comes back as `{"lt": 10}`, fewer than 10, and 0 stays 0. A count of events made by fewer than 10 people comes back as `null`. A rate needs 10 or more on both sides. Exact numbers are in your own dashboard. - It reads whole days in the project's time zone; a `timezone` argument does not move the window. - Values from your events are masked before they leave: an email becomes ``, a long number ``. - It never runs SQL. Every question goes through the same query engine as the dashboard, limited to your team's projects. ## Docs for AI tools These docs are also published for language models: - [/llms.txt](https://datacub.to/llms.txt): an index of every page, with a link to its markdown - [/llms-full.txt](https://datacub.to/llms-full.txt): every page in one file - any page as markdown: add `.md` to its address, for example [/docs/quickstart.md](https://datacub.to/docs/quickstart.md) - [/openapi.json](https://datacub.to/openapi.json): the HTTP API, including the MCP endpoint --- # Troubleshooting Most problems show up as a console warning on `localhost`. Start there. ## No events at all 1. **Does the project ask for consent first, or did the visitor opt out?** With "Ask for consent first" on, nothing is sent before `datacub.consent.grant()`. A visitor who called `datacub.consent.revoke()` stays opted out on that browser. On `localhost` the SDK warns `no consent yet`. 2. **Is the key right?** It starts with `pk_live_` or `pk_test_` followed by 24 to 48 letters and digits. The placeholder `pk_live_YOUR_PROJECT_KEY` is refused: `init: bad key`. 3. **Is your site allowed?** Check **Where data may come from** in [Settings, General](https://datacub.to/en/settings?tab=general). `localhost` works only with a `pk_test_` key. In the browser's network tab, a `403` from `/v1/batch` with `origin_not_allowed` means the site is not on the list. 4. **Is Global Privacy Control on?** Browsers with GPC count as an opt-out. See [consent](https://docs.datacub.to/consent#global-privacy-control). 5. **Is an ad blocker dropping the request?** Use a [first-party proxy](https://docs.datacub.to/install-web#first-party-proxy). Then use **Check the connection** in [Settings, Integrations](https://datacub.to/en/settings?tab=integrations): it waits for your next event and says when it lands. ## Warnings and what they mean | Warning | Fix | |---|---| | `init: bad key` | use a real `pk_` key; `apiHost` must be `https` (or `http://localhost`) | | `refused a secret key. Use a pk_ key.` | never put an `sk_` key in client code | | `bad name` | event names cannot start with `$` or look like IDs. See [names](https://docs.datacub.to/custom-events#names) | | `bad id` | the ID looks like an email, phone, national ID or placeholder. Send your internal user ID | | `no consent yet` | only with "Ask for consent first" on: expected until your consent flow grants | In React Native the same checks print as `track: invalid event name`, `identify: ID refused`, `init: expected a pk_live_ or pk_test_ key`, and `init: no app id` when `app` is missing. ## Responses from datacub | Status | Meaning | What the SDK does | |---|---|---| | `401 invalid_key` | the key does not exist or was revoked | stops for this page or launch | | `403 origin_not_allowed`, `403 app_not_allowed` | the site or app is not on the allowed list | stops for this page or launch | | `403 project_suspended`, `403 project_in_review` | the project is paused | stops for this page or launch | | `403 ingestion_paused` | the trial ended without a plan ([billing](https://docs.datacub.to/billing#when-a-trial-ends)) | stops for this page or launch | | `429 rate_limited` | too many events at once | retries after the time datacub asks for | | `5xx` or offline | datacub or the network is down | retries with backoff, keeps up to 1,000 events | ## Page views are missing or doubled - **Only the first page counts** in a single page app: your router may use the URL fragment. Set `hashRouting: true`. - **A page counts twice**: `init` is called with two different setups, or the script tag and the npm package are both loaded. Load the SDK once. - **Paths show `:id` or `:redacted`**: that is on purpose. IDs and personal data are removed from URLs. ## Users look duplicated or merged - **One person shows as many users**: call `identify` after every login, on every device. Safari users who stay away for 7 days return as new Guests until they sign in. - **Two people show as one**: call `reset()` at logout. ## Mobile - **Nothing survives a restart**: pass `storage` to `init`. - **Events from Expo Go are refused**: Expo Go works only with a `pk_test_` key. - **Nothing sent in tests**: `await datacub.flush()` before the test ends. --- # SDK reference Every public call of the web SDK 0.4.0 (the global `datacub` from the [script tag](https://docs.datacub.to/install-web.md), typed by [datacub.d.ts](https://docs.datacub.to/install-web#typescript)) and of `@datacub/react-native` 0.1.0. No call ever throws; a refused call does nothing. ## Web SDK ```ts types import type { InitOptions, Properties } from './datacub' const options: InitOptions = { apiHost: 'https://ingest.datacub.example', hashRouting: false, autocapture: true, release: '1.4.0' } datacub.init('pk_live_YOUR_PROJECT_KEY', options) const props: Properties = { plan: 'pro', seats: 3 } datacub.track('plan_changed', props) datacub.identify('user_8f3a2c', { account: 'ws_51', email: 'sara@example.sa', name: 'Sara', phone: '+966551234567' }) datacub.reset() datacub.consent.revoke() ``` | Call | Does | |---|---| | `datacub.init(publicKey, options?)` | starts the SDK once; later calls are ignored. Calls before it wait (up to 100) | | `datacub.track(event, properties?)` | a custom event. [Rules](https://docs.datacub.to/custom-events.md) | | `datacub.identify(userId, { account?, email?, name?, phone?, ...traits })` | after login: links this browser's activity to the user; traits describe them. [More](https://docs.datacub.to/identify.md) | | `datacub.reset()` | at logout: new Guest ID and session | | `datacub.consent.grant(options?)` | for [consent first](https://docs.datacub.to/consent.md): starts storing and sending. Options: `method`, `policyVersion`, `overrideGPC`. Also clears a stored opt-out | | `datacub.consent.revoke()` | works in every project: stops, deletes the SDK's other cookies and the queue, and remembers the opt-out on this browser | `init` options: `apiHost` (default `https://ingest.datacub.example`), `hashRouting` (default `false`), `autocapture` (default `true`), `release`, `requireConsent` (default `false`: see [asking for consent](https://docs.datacub.to/consent.md)). [Details](https://docs.datacub.to/install-web#options). HTML attributes: `data-datacub-name="..."` names a click or form; `class="datacub-no-capture"` or `data-datacub-no-capture` excludes an element and everything inside it. Script tag attributes: `data-key`, `data-api-host`, `data-require-consent`. Cookies, all first party: `datacub_id` (Guest ID, 400 days), `datacub_u` (user ID), `datacub_a` (account ID), `datacub_ss` (session, 30 minutes). Each name ends with `_` and the first eight characters after `pk_live_` or `pk_test_` in your key (`datacub_id_k7Qm2xPa`): every subdomain running the same key shares one visitor and session, and a second key on the same site gets its own. With `requireConsent` they are written only after `grant()`. After `revoke()` the only cookie is `datacub_optout` (400 days, no identifier). ### Feedback widget The questions you write in the dashboard's **Feedback** page show through a separate file, loaded only on sites that use it. Add it next to the SDK: ```html script ``` | Call or attribute | Does | |---|---| | `datacub.ask(questionId, { into? })` | shows a question whose trigger is "from my code"; `into` places it inline in an element or selector | | `
` | the same, inline, without code | | `datacub.feedback()`, or any element with `data-datacub-feedback` | opens the general "Send feedback" card | Both calls exist only once the widget has loaded. ## @datacub/react-native ```ts types import datacub, { type InitOptions, VERSION } from '@datacub/react-native' import { trackNavigation } from '@datacub/react-native/navigation' const options: InitOptions = { apiHost: 'https://ingest.datacub.example', storage: { getItem: () => null, setItem: () => {}, removeItem: () => {} }, app: { applicationId: 'sa.example.shop', nativeApplicationVersion: '2.3.0', nativeBuildVersion: '87' }, } datacub.init('pk_live_YOUR_PROJECT_KEY', options) datacub.track('order_placed', { items: 2 }) datacub.screen('Checkout', { step: 'payment' }) datacub.identify('user_8f3a2c', { account: 'ws_51' }) datacub.reset() datacub.consent.revoke() await datacub.flush() console.log(VERSION, typeof trackNavigation) ``` | Call | Does | |---|---| | `datacub.init(publicKey, options?)` | starts the SDK once. Options: `storage`, `app`, `apiHost`, `requireConsent` | | `datacub.track(event, properties?)` | a custom event | | `datacub.screen(name, properties?)` | a screen view; the same name twice in a row counts once | | `datacub.identify(userId, { account?, email?, name?, phone?, ...traits })` | after login, as on the web | | `datacub.reset()` | at logout | | `datacub.flush()` | sends what is queued; resolves when done or failed, never rejects | | `datacub.consent.grant(options?)`, `datacub.consent.revoke()` | as on the web; `grant` takes `method` and `policyVersion`. The opt-out is a flag in the SDK's stored value | | `trackNavigation(ref)` from `@datacub/react-native/navigation` | screen views from a React Navigation container ref; returns an unsubscribe function | ## Events datacub sends for you | Event | SDK | When | |---|---|---| | `$pageview`, `$pageleave` | web | [page views](https://docs.datacub.to/pageviews.md) | | `$click`, `$form_submit` | web | [clicks and submits](https://docs.datacub.to/pageviews#clicks) | | `$screen` | mobile | `datacub.screen` or `trackNavigation` | | `$consent` | both | `datacub.consent.grant()`, when the project asks for consent first | | `$identify` | both | `datacub.identify` with a new user, with any traits | | `$set` | both | `datacub.identify` with traits for the user already identified | Event names starting with `$` are reserved for these. ## HTTP Both SDKs send `POST {apiHost}/v1/batch` with a JSON body of up to 100 events. You do not need to call it yourself. If you proxy it, pass the body through unchanged and keep the response status, including `Retry-After`.