# Web SDK

One script, about 10 KB with gzip, served by datacub. It works with any site or framework. Bundled apps that prefer a package can [install it from npm](#from-npm) instead.

## Install

One line in your HTML `<head>`, before your app's own scripts. The SDK sends events to the host it loads from, so it needs only your key:

```html script
<script src="https://in.datacub.to/v1/sdk.js" data-id="YOUR_PROJECT_ID" defer></script>
```

Use `datacub` only in client code (event handlers, effects), never in code that runs on the server. If an ad blocker stops the file, `datacub` is not defined: write `window.datacub?.track(...)` where that must not break your app.

### Where the snippet goes

| Framework | Where |
|---|---|
| Vite (React, Vue), TanStack Router, plain sites | `index.html`, inside `<head>` |
| Next.js App Router | `app/layout.tsx`: `next/script` with the same `src` and `data-id` and `strategy="beforeInteractive"` |
| TanStack Start | the root route's `head` scripts |
| SvelteKit | `src/app.html`, inside `<head>` |

The SDK follows route changes through the History API, so React Router, Next.js, Vue Router and SvelteKit report one page view per route without extra code. Routers that keep the route in the fragment (`/#/orders/12`) need `hashRouting: true`.

### TypeScript

Save the type definitions; they type the global `datacub` and export the option types:

```sh none
curl -o src/datacub.d.ts https://in.datacub.to/v1/sdk.d.ts
```

### From npm

The script tag is the default. A bundled app (Vite, Next.js, any build step) that prefers a package can install `@datacub/web` instead. Use one or the other, never both.

```sh none
npm install @datacub/web
```

Start it once in your client entry (`src/main.tsx` in Vite, a client component in Next.js), never in code that runs on the server, and import `datacub` wherever you call it:

```ts web
import datacub from '@datacub/web'

datacub.init('YOUR_PROJECT_ID')
```

The package sends to `https://in.datacub.to`. Pass `{ apiHost }` only for a first-party proxy or another deployment. The package carries its own types, so you do not need the `.d.ts` file above. The only datacub packages on npm are `@datacub/web` and `@datacub/react-native`: do not install any other name under `@datacub`.

### Check that it works

| Where | What you should see |
|---|---|
| browser console, on `localhost` | nothing, unless a call was refused: then a line saying why |
| network tab | a `POST` to `/v1/batch` that answers `200`, about 5 seconds after the page loads, or when you leave it |
| datacub, **Realtime** | you, within seconds |
| datacub, Settings, Connect and AI | no refusal warning; if there is one, it names the site and offers to add it |

## What it tracks on its own

| Event | When |
|---|---|
| `$pageview` | first load, every route change, and a page restored from the back and forward cache |
| `$pageleave` | leaving the page or hiding the tab, with foreground time and scroll depth |
| `$click` | links, buttons and elements with a button, link, menu item or tab role, with their visible text (scrubbed, at most 100 characters) |
| `$form_submit` | a form was submitted: its name, action path and number of fields, never values |

It also collects page titles, URL query values that read as codes (`?sort=price_desc`, never what someone typed), JavaScript errors, failed and slow requests (method, templated path, status), form interaction timing, device and browser context, and Web Vitals. Each can be turned off with the `capture` option below.

Give an important button a readable name in reports:

```html none
<button data-datacub-name="upgrade_plan">ترقية الباقة</button>
```

Add `data-datacub-no-capture` (or the `datacub-no-capture` class) to an element and nothing inside it is captured.

## Track, identify, reset

```ts web
// a custom event, after the action succeeded
datacub.track('checkout_completed', { plan: 'growth', currency: 'SAR' })

// after login: your own stable internal user ID
datacub.identify('user_8f3a2c', { email: 'sara@example.sa', name: 'Sara' })

// at logout: a new Guest ID and session
datacub.reset()
```

Rules for names, properties and traits: [events and users](https://docs.datacub.to/guides/events-and-users.md).

## Options

| Option | Default | What it does |
|---|---|---|
| `apiHost` | the host the script came from; from npm, `https://in.datacub.to` | your first-party proxy, if you use one (`data-api-host` on the tag). Must be `https` (or `http://localhost`) |
| `hashRouting` | `false` | treat `#/route` fragments as pages |
| `autocapture` | `true` | clicks and form submits. Page views are always on |
| `release` | none | your app version, sent with every event |
| `requireConsent` | `false` | send nothing until `datacub.consent.grant()`. See [privacy and consent](https://docs.datacub.to/guides/privacy.md) |
| `capture` | all on | `{ text, title, query, errors, network, forms }`: set any to `false` |
| `insights` | `true` | `false` skips the Web Vitals and device module |
| `feedback` | `true` | `false` never loads the feedback widget (`data-feedback="off"` on the tag). From SDK 0.6.0, `{ look }` styles the card: see [the card's look](#the-feedback-cards-look-from-sdk-060) |

```ts web
datacub.init('YOUR_PROJECT_ID', {
  release: '2026.11.1',
  capture: { query: false },
})
```

`init` runs once; later calls are ignored. No call ever throws: a refused call does nothing, and on `localhost` the SDK says why in the console.

## Calls

| Call | Does |
|---|---|
| `datacub.init(publicKey, options?)` | starts the SDK once |
| `datacub.track(event, properties?)` | a custom event |
| `datacub.identify(userId, traits?)` | links this browser to a signed-in user; traits `account`, `email`, `name`, `phone` and your own |
| `datacub.reset()` | at logout |
| `datacub.consent.grant(options?)`, `datacub.consent.revoke()` | consent and opt-out, in every project |

Script tag attributes: `data-id`, `data-api-host`, `data-require-consent`, `data-feedback`. Cookies are first party: `datacub_id` (Guest ID, 400 days), `datacub_u`, `datacub_a`, `datacub_ss` (session, 30 minutes), each ending in `_` and your project ID, and `datacub_optout` after a revoke.

## Feedback, flags and experiments

Feedback needs no extra tag. The SDK loads the feedback widget by itself, only while it tracks, and only when the project has a published question in **Feedback** or the page opens the "Send feedback" card. A site without feedback downloads nothing more. A `feedback.js` tag from an older install still works, and the page still gets one widget. You can remove the tag.

Flags and experiments load as a separate file, only on sites that use them, next to the snippet:

```html script
<script src="https://in.datacub.to/v1/flags.js"></script>
```

| Call | Does |
|---|---|
| `datacub.ask(questionId, { into? })` or `<div data-datacub-ask="questionId">` | shows a question you wrote in **Feedback** whose trigger is "from my code" |
| `datacub.feedback()`, or an element with `data-datacub-feedback` | opens the "Send feedback" card |
| `datacub.feedback.shown(id)`, `.send(answer)`, `.dismissed(id)` | your own feedback UI instead of the card: see [your own feedback UI](#your-own-feedback-ui-from-sdk-080) |
| `await datacub.flag('key')` | `true` or `false` for a flag created in **Feature control** |
| `await datacub.experiment('key')` | `'A'` (original) or `'B'`; records that this visitor saw it, so call it where that version shows |

A flag is never a permission check: keep those on your server.

From npm, there is no extra tag: `import { flag, experiment } from '@datacub/web/flags'`, then `await flag('new_checkout')`.

### Your own feedback UI (from SDK 0.8.0)

Draw the question your way (your own popup, form or chat bubble) and let datacub store it. Write the question in **Feedback** with the trigger "from my code"; its ID and answer IDs are on the question, and an agent reads them with `list_feedback`. Answers, shown, closed and ignored count in its results and on each person's journey, the same as datacub's card.

```ts web
// the question's ID from Feedback, with the trigger "from my code"
const QUESTION = '6f1c1c52-5b7e-4a52-9d0f-0c5d6c3a1b2e'

// before you show your popup: false means not now (limits, audience, paused, no consent yet)
export async function maybeAsk(show: () => void) {
  if (await datacub.feedback?.shown(QUESTION)) show()
}

// their answer: one of the question's answer IDs ('yes', 'no', '0' to '10'), and what they wrote
export function answered(choice: string, text: string) {
  return datacub.feedback?.send({ question: QUESTION, choice, text })
}

// closed without answering: not offered to them again
export function closed() {
  datacub.feedback?.dismissed(QUESTION)
}

// general feedback, no question: text required, choice optional ('idea', 'problem', 'confusing')
datacub.feedback?.send({ text: 'Please add Excel export', choice: 'idea' })
```

`send` resolves `true` once stored, `false` when refused (a choice the question does not have, words after an answer that has no follow-up, a second answer from the same person) or offline. The rules stay the same as the card's: one answer per person, IDs, card numbers and phone numbers in written answers masked, nothing before consent.

### The feedback card's look (from SDK 0.6.0)

The card keeps its layout and behaviour; its look is yours. Set it in **Feedback**, **Customise look** under the card (font, background colour, button colour and button text; it applies to every question in the project), or in code, which wins field by field:

```ts web
datacub.init('YOUR_PROJECT_ID', {
  feedback: { look: { accent: '#0f766e', font: 'site', radius: 'small', theme: 'auto' } },
})
```

| Field | Values | Default |
|---|---|---|
| `accent` | your brand colour, `#rrggbb` | `#1f1f1f` |
| `theme` | `light`, `dark`, `auto` (follows the visitor's system) | `light` |
| `background`, `text` | card and text colours, `#rrggbb`, in place of the theme's | the theme's |
| `font` | `system`, `site` (your page's font, read automatically), `serif`, `rounded` | `system` (from SDK 0.7.0 `site`) |
| `radius` | `none`, `small`, `medium`, `large` | `large` (from SDK 0.7.0 `medium`) |
| `size` | `small`, `medium`, `large` | `medium` |
| `position` | `end` (bottom right), `start` (bottom left) | `end` |

From SDK 0.7.0 the card takes the rest of its look too (older SDKs ignore these fields):

| Field | Values | Default |
|---|---|---|
| `sendLabel` | the send button's words in place of Send, plain text, 1 to 20 characters | Send / إرسال |
| `title`, `option`, `optionText`, `optionBorder`, `selected`, `button`, `buttonText`, `close`, `border` | the question, the answer buttons (fill, words, edge), the chosen answer, the send button and its words, the close icon and the card's edge, `#rrggbb` | the theme's; the brand colour for `selected` and `button` |
| `dark` | with `theme: 'auto'`, the colours for visitors in dark mode: `accent` and the colour fields above (the others are then for light mode) | none: the theme's dark card, your brand colour |
| `font: 'custom'`, `fontName` | a font your page already loads, by name (letters, digits, spaces, hyphens); the card never downloads fonts | |
| `borderWidth` | the card's edge, 0 to 4 px | a hairline |
| `shadow` | `none`, `soft` (faint), `medium`, `strong` | `soft` |
| `width` | 280 to 480 px, in place of the size's | the size's |
| `density` | `compact`, `regular`, `roomy` | `regular` |
| `titleSize`, `titleWeight`, `bodyWeight` | `small`, `regular`, `large`; `regular`, `medium`, `semibold`, `bold` | `regular`, `semibold`, `regular` |
| `align` | `start`, `center` (the question) | `start` |
| `icons` | the yes and no buttons: `thumbs`, `faces`, `emoji`, `words` | `thumbs` |
| `scale` | `traffic` colours 0 to 10 scores red (0 to 6), amber (7, 8) and green (9, 10) | `plain` |
| `animation` | `rise`, `fade`, `slide`, `none` | `rise` |
| `offsetX`, `offsetY` | px from the side and the bottom of the window, 0 to 160; phones keep 12 px at the sides | `16` |
| `layer` | `top`, `high`, `normal` (under your own popups and chat) | `top` |

Anything else is ignored, and the card never takes CSS. A text colour that is hard to read on the card (contrast under 4.5) is replaced by a readable one, and the text on buttons is white or near black, whichever reads better on your brand colour. With the script tag, start the SDK with the queue instead of `data-id` to pass a look: `<script>window.datacub = [['init', 'YOUR_PROJECT_ID', { feedback: { look: { … } } }]]</script>` before the tag.

## Subdomains and other domains

A project accepts the website it was made for and every subdomain of it. `www.example.sa` and `app.example.sa` share one Guest and session on their own: install the same key on both. Separate domains (`example.sa` and `example.com`) link when the user signs in on each with the same ID. datacub never passes IDs in URLs.

## First-party proxy

Some blockers drop requests to analytics hosts. Forward `POST /v1/batch` from a path on your domain to datacub's ingestion host, pass the request body, the response status and the response body through unchanged, and add `data-api-host` with that path to the tag, such as `data-api-host="https://www.example.sa/datacub"`.

## Content Security Policy

Allow your ingestion host in `script-src` (the SDK, its insights module and the feedback widget load from there) and in `connect-src`.
