@daybook/analytics 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,439 +1,536 @@
1
- # `@daybook/analytics`
2
-
3
- Product analytics for the web, sent to Daybook's Analytics hub. Page views, sessions, where visitors came
4
- from, their browser and device — without a line of code — and your own events with `track`. A visitor's
5
- events before and after they sign in count as one person.
6
-
7
- Plain JavaScript, React (Next.js too) and Vue (Nuxt too). No dependencies; about 7 KB gzipped as a
8
- script tag. Safe to import in server-rendered code: on the server every call does nothing.
9
-
10
- - [Get a key](#get-a-key)
11
- - [Install](#install): [script tag](#script-tag) · [npm](#npm) · [React](#react) · [Next.js](#nextjs) · [Vue](#vue) · [Nuxt](#nuxt)
12
- - [Events](#events) · [Page views](#page-views) · [Users: identify and reset](#users-identify-and-reset) · [Properties on every event](#properties-on-every-event)
13
- - [Consent and privacy](#consent-and-privacy) · [Delivery](#delivery) · [Options](#options) · [Methods](#methods)
14
- - [What is sent](#what-is-sent) · [Troubleshooting](#troubleshooting)
15
-
16
- ## Get a key
17
-
18
- In Daybook, open the project's **Analytics → Settings** and issue an ingest key for the build that will send
19
- events — one for production, one for staging. Copy it when it is shown: only its first characters are kept.
20
-
21
- The key starts with `dak_`. It is public by design, like any analytics key: it only says which project
22
- events are for, so it is fine in a page's source. Revoking it in Settings stops it at once.
23
-
24
- The same page shows the snippets below with your key filled in.
25
-
26
- ## Install
27
-
28
- ### Script tag
29
-
30
- No build step. Put it in the `<head>`, with your key:
31
-
32
- ```html
33
- <script src="https://daybook.team/sdk/v1/daybook.js" data-key="dak_…"></script>
34
- ```
35
-
36
- That is all page views need. Your own events, anywhere after it:
37
-
38
- ```html
39
- <script>
40
- daybook.track('signed_up', { plan: 'pro' })
41
- </script>
42
- ```
43
-
44
- The script starts by itself from its `data-` attributes and is `window.daybook`. Every [option](#options)
45
- has one: `data-api-url`, `data-app-version`, `data-pageviews="false"`, `data-pageleave="false"`,
46
- `data-persistence="cookie"`, `data-cookie-domain=".example.com"`, `data-opt-out-by-default`,
47
- `data-respect-dnt`, `data-debug`.
48
-
49
- **Loading it async.** To keep it off the critical path, load it `async` and put this stub before it. Calls
50
- made before the script arrives are queued on the stub and played back in order:
51
-
52
- ```html
53
- <script>
54
- window.daybook = window.daybook || { q: [] };
55
- ['track', 'page', 'identify', 'reset', 'register', 'unregister', 'setPersonProperties', 'optIn', 'optOut']
56
- .forEach(function (m) { daybook[m] = daybook[m] || function () { daybook.q.push([m, [].slice.call(arguments)]) } })
57
- </script>
58
- <script async src="https://daybook.team/sdk/v1/daybook.js" data-key="dak_…"></script>
59
- ```
60
-
61
- Without `data-key`, start it yourself: `DaybookAnalytics.init({ key: 'dak_…', … })`, which also sets
62
- `window.daybook`.
63
-
64
- **A pinned version.** `daybook.team/sdk/v1/daybook.js` is always the newest build that speaks the v1 API.
65
- To pin one, load it from npm through a public CDN: `https://cdn.jsdelivr.net/npm/@daybook/analytics@0.2.0`
66
- or `https://unpkg.com/@daybook/analytics@0.2.0` serve the same file.
67
-
68
- ### npm
69
-
70
- ```sh
71
- npm install @daybook/analytics
72
- ```
73
-
74
- ```ts
75
- import { init } from '@daybook/analytics'
76
-
77
- const analytics = init({ key: 'dak_…' })
78
-
79
- analytics.track('signed_up', { plan: 'pro' })
80
- ```
81
-
82
- `init` starts one instance for the site and returns it on every later call, so it is safe to call from
83
- wherever is convenient. Anywhere else, `getAnalytics()` returns it. For a second project on the same
84
- page, `new DaybookAnalytics({ key })` makes an instance of its own.
85
-
86
- ### React
87
-
88
- ```tsx
89
- import { DaybookProvider } from '@daybook/analytics/react'
90
-
91
- root.render(
92
- <DaybookProvider options={{ key: 'dak_…' }}>
93
- <App />
94
- </DaybookProvider>,
95
- )
96
- ```
97
-
98
- ```tsx
99
- import { useAnalytics } from '@daybook/analytics/react'
100
-
101
- function UpgradeButton() {
102
- const analytics = useAnalytics()
103
- return <button onClick={() => analytics.track('upgrade_clicked', { from: 'header' })}>Upgrade</button>
104
- }
105
- ```
106
-
107
- The provider starts analytics once, however often it renders (StrictMode included). Page views follow the
108
- History API, so React Router, TanStack Router and the rest need nothing more. To use an instance you made
109
- yourself: `<DaybookProvider client={analytics}>`.
110
-
111
- ### Next.js
112
-
113
- App Router: the provider is a client component already (`'use client'` is in the package), so it can go
114
- straight into the root layout:
115
-
116
- ```tsx
117
- // app/layout.tsx
118
- import { DaybookProvider } from '@daybook/analytics/react'
119
-
120
- export default function RootLayout({ children }: { children: React.ReactNode }) {
121
- return (
122
- <html lang="en">
123
- <body>
124
- <DaybookProvider options={{ key: process.env.NEXT_PUBLIC_DAYBOOK_KEY! }}>
125
- {children}
126
- </DaybookProvider>
127
- </body>
128
- </html>
129
- )
130
- }
131
- ```
132
-
133
- `useAnalytics()` works in any client component (`'use client'`). In server components, route handlers and
134
- server actions there is no visitor: track from the client, or send events to the
135
- [ingest API](#what-is-sent) from your server.
136
-
137
- Pages Router: wrap `<Component {...pageProps} />` in `pages/_app.tsx` the same way.
138
-
139
- ### Vue
140
-
141
- ```ts
142
- // main.ts
143
- import { createApp } from 'vue'
144
- import { createAnalytics } from '@daybook/analytics/vue'
145
- import { router } from './router'
146
- import App from './App.vue'
147
-
148
- const app = createApp(App)
149
- app.use(router)
150
- app.use(createAnalytics({ key: 'dak_…', router }))
151
- app.mount('#app')
152
- ```
153
-
154
- ```vue
155
- <script setup lang="ts">
156
- import { useAnalytics } from '@daybook/analytics/vue'
157
-
158
- const analytics = useAnalytics()
159
- </script>
160
-
161
- <template>
162
- <button @click="analytics.track('upgrade_clicked')">Upgrade</button>
163
- <!-- or, without the import: $daybook.track('upgrade_clicked') -->
164
- </template>
165
- ```
166
-
167
- With `router`, a page view is sent after each finished navigation to a new path, once the new route has
168
- rendered — a navigation a guard cancels, or one that only changes the query, is not a page. Without it,
169
- page views follow the History API like everywhere else.
170
-
171
- ### Nuxt
172
-
173
- A client-only plugin, with the key in runtime config:
174
-
175
- ```ts
176
- // plugins/daybook.client.ts
177
- import { createAnalytics } from '@daybook/analytics/vue'
178
-
179
- export default defineNuxtPlugin((nuxtApp) => {
180
- const { daybookKey } = useRuntimeConfig().public
181
- nuxtApp.vueApp.use(createAnalytics({ key: daybookKey as string, router: useRouter() }))
182
- })
183
- ```
184
-
185
- ```ts
186
- // nuxt.config.ts
187
- export default defineNuxtConfig({
188
- runtimeConfig: { public: { daybookKey: '' } }, // set NUXT_PUBLIC_DAYBOOK_KEY
189
- })
190
- ```
191
-
192
- ## Events
193
-
194
- ```ts
195
- analytics.track('checkout_completed', {
196
- plan: 'pro',
197
- seats: 3,
198
- total: 49.0,
199
- coupon: null,
200
- renews_at: new Date('2027-01-01'),
201
- })
202
- ```
203
-
204
- - **Names** are what someone will pick from a list in a chart: an object and a past-tense verb in
205
- `snake_case` (`project_created`, `invite_sent`). Keep them few and stable, and put the variety in
206
- properties: `button_clicked { button: 'upgrade' }`, not one event per button. Names starting with `$` are
207
- Daybook's own and are refused.
208
- - **Properties** are strings, numbers, booleans, `null`, dates (sent as ISO 8601), lists and objects.
209
- A number is filtered and summed as a number, so send `49`, not `'49'`. At most 255 per event and 32 KB.
210
- - In Daybook, **Analytics → Catalog** lists every event and property the project has sent, with a place to
211
- describe each one.
212
-
213
- ## Page views
214
-
215
- On by default: a `$pageview` on load, and one on every navigation of a single-page app (`pushState`,
216
- `replaceState`, the back button, and `#/` routes). A change of the query string alone is not a new page.
217
- Each one carries the URL, path, title, referrer, campaign parameters and screen size.
218
-
219
- When a page is left — a navigation inside the app, or the tab closing — a `$pageleave` says how long it
220
- was open (`$duration_ms`).
221
-
222
- To send them yourself instead — after your router has rendered, say:
223
-
224
- ```ts
225
- const analytics = init({ key: 'dak_…', autoPageviews: false })
226
- // on each route change:
227
- analytics.page()
228
- analytics.page({ section: 'docs' }) // with properties of your own
229
- ```
230
-
231
- ## Sessions
232
-
233
- A session is one visit: it starts with the first event, and a new one starts after 30 minutes without an
234
- event (`sessionTimeoutMinutes`), after 24 hours however busy, and on `reset()`. Every tab of the site shares
235
- the same session. Each one opens with `$session_start`, which carries the page it began on, the referrer
236
- and the campaign, so Daybook can count sessions, measure how long they last and break them down by entry
237
- page and source. A session ends at its last event: nothing waits for the tab to close.
238
-
239
- ## Users: identify and reset
240
-
241
- Every browser gets an anonymous id on its first visit. When the visitor signs in, say who they are:
242
-
243
- ```ts
244
- analytics.identify(user.id, { email: user.email, plan: user.plan })
245
- ```
246
-
247
- From then on their events carry the user id, and **everything this browser sent before** counts as theirs
248
- too — nothing is sent again, Daybook links the two ids. Call it after sign-in and on every page load while
249
- they are signed in; a repeat costs nothing.
250
-
251
- When they sign out:
252
-
253
- ```ts
254
- analytics.reset()
255
- ```
256
-
257
- That starts a new anonymous id and session and forgets registered properties, so whoever uses the browser
258
- next is somebody new. Daybook joins one anonymous id to one user only, so another user signing in on the
259
- same browser without a `reset()` in between gets a fresh anonymous id automatically.
260
-
261
- **Person properties** describe the person rather than one event, and filters and breakdowns can use them:
262
-
263
- ```ts
264
- analytics.setPersonProperties({ plan: 'team', company: 'Acme' })
265
- analytics.setPersonProperties({}, ['trial_ends_at']) // unset
266
- analytics.setPersonPropertiesOnce({ first_plan: 'free', signed_up_at: new Date() })
267
- ```
268
-
269
- `setPersonPropertiesOnce` writes a property only where the person has no value for it yet — under this
270
- browser's ids or any other they signed in with — so the first value stays; a later `setPersonProperties`
271
- still changes it. Properties set before sign-in belong to the person after `identify`.
272
-
273
- Where the browser first came from — `$initial_referrer`, `$initial_referring_domain` and `$initial_utm_*` —
274
- is set once on the person by itself, with the browser's first event, so a signup weeks later can be broken
275
- down by the campaign that first brought the visitor.
276
-
277
- Use the same user id everywhere you identify the person — the web app, the mobile app, your server — and
278
- their events from all of them are one person's.
279
-
280
- ## Properties on every event
281
-
282
- ```ts
283
- analytics.register({ app_section: 'admin', experiment: 'new-pricing-b' })
284
- analytics.unregister('experiment')
285
- ```
286
-
287
- Registered properties are kept across visits until `reset()`. Options can set some from the start:
288
- `init({ key, properties: { site: 'docs' } })`.
289
-
290
- ## Consent and privacy
291
-
292
- | You want | Do |
293
- |---|---|
294
- | Nothing sent or stored until the visitor agrees | `optOutByDefault: true`, then `analytics.optIn()` from your consent banner |
295
- | The visitor declined | `analytics.optOut()` — remembered on their next visit |
296
- | To honour Do Not Track and Global Privacy Control | `respectDoNotTrack: true` (an explicit `optIn()` still wins) |
297
- | To keep something out of what is sent | `beforeSend` (below) |
298
-
299
- With `optOutByDefault`, nothing is written to the browser either — not even the anonymous id — until
300
- `optIn()`, which then counts the page the visitor is on. After `optOut()` only the choice itself is kept.
301
-
302
- ```ts
303
- init({
304
- key: 'dak_…',
305
- beforeSend(event) {
306
- // Take a reset token out of the URL, and drop internal traffic.
307
- event.properties.$url = String(event.properties.$url).replace(/token=[^&]+/, 'token=…')
308
- if (event.properties.$host === 'admin.example.com') return null
309
- return event
310
- },
311
- })
312
- ```
313
-
314
- What the SDK keeps in the browser:
315
-
316
- - `localStorage` → `dbk_<first letters of the key>`: the anonymous id, the user id after `identify`, the
317
- session, registered properties, where the browser first came from, and the consent choice. With
318
- `persistence: 'cookie'` this is a first-party cookie of the same name instead (set `cookieDomain:
319
- '.example.com'` so `www.` and `app.` share one visitor); with `persistence: 'memory'`, nothing.
320
- - `sessionStorage` → `dbk_<…>_queue`: events not yet sent, so a reload or a dropped connection loses none.
321
-
322
- Requests to Daybook carry no cookies and no credentials. Daybook keeps the visitor's country from the
323
- request and never their IP address.
324
-
325
- ## Delivery
326
-
327
- Events wait about two seconds (`flushIntervalMs`) and go together, up to 50 a request (`batchSize`).
328
-
329
- - **Offline, a server error, a 429:** the same batch is tried again — 1 s, 2 s, 4 s, up to five minutes, and
330
- at once when the browser is back online — with the same event ids, so Daybook stores each event once.
331
- - **Reload:** what was not sent is still in the tab's `sessionStorage` and goes on the next page.
332
- - **Leaving the page:** when the page is hidden, what is waiting is handed to `navigator.sendBeacon`, which
333
- the browser delivers after the page is gone.
334
- - **Refused:** an event Daybook refuses (a `$` name, too many properties…) is named in a console warning,
335
- and the rest of its batch is kept. A refused key stops the page sending.
336
- - **A wrong clock:** every request says when it left (`sent_at`, by the visitor's clock), and Daybook moves
337
- each event by how far that is from when the request arrived. An event from a computer whose clock is
338
- two hours slow, or one that waited offline all afternoon, is still placed at the time it happened.
339
-
340
- `await analytics.flush()` sends everything now — before a redirect to another site, for example.
341
-
342
- ## Options
343
-
344
- | Option | Default | |
345
- |---|---|---|
346
- | `key` | — | **Required.** The ingest key, `dak_…`. |
347
- | `apiUrl` | `https://api.daybook.team` | A self-hosted Daybook, or a proxy of your own (see [Troubleshooting](#troubleshooting)). |
348
- | `appVersion` | — | Your site's version or build, kept as the event's `app_version`. |
349
- | `autoPageviews` | `true` | Page views on load and on every navigation. `false` to call `page()` yourself. |
350
- | `pageleave` | `true` | A `$pageleave` with the time on the page. |
351
- | `persistence` | `'localStorage'` | `'cookie'` to share the visitor across subdomains, `'memory'` to keep nothing. |
352
- | `cookieDomain` | — | With cookies: `.example.com`. |
353
- | `sessionTimeoutMinutes` | `30` | Idle minutes after which the next event starts a new session; a session also ends after 24 hours. |
354
- | `flushIntervalMs` | `2000` | How long events wait to go together. |
355
- | `batchSize` | `50` | Events per request, at most 1,000. |
356
- | `properties` | — | Registered from the start, as `register()`. |
357
- | `optOutByDefault` | `false` | Send and store nothing until `optIn()`. |
358
- | `respectDoNotTrack` | `false` | Send nothing when the browser asks not to be tracked. |
359
- | `ignoreBots` | `true` | Send nothing from crawlers and link previews. |
360
- | `beforeSend` | — | `(event) => event \| null`: change or drop any event. |
361
- | `debug` | `false` | Log every event queued and every request. |
362
-
363
- ## Methods
364
-
365
- | | |
366
- |---|---|
367
- | `track(event, properties?)` | An event. |
368
- | `page(properties?)` | A page view, when `autoPageviews` is off or for a page of your own. |
369
- | `identify(userId, properties?)` | The visitor signed in. |
370
- | `reset()` | The visitor signed out. |
371
- | `setPersonProperties(set, unset?)` | Properties of the person. |
372
- | `setPersonPropertiesOnce(properties)` | Properties of the person, only where they have none yet. |
373
- | `register(properties)` / `unregister(name)` | Properties on every event. |
374
- | `optIn()` / `optOut()` | The visitor's consent. `optedOut` says where it stands. |
375
- | `flush()` | Send what is waiting now; resolves when it is sent or Daybook cannot be reached. |
376
- | `distinctId`, `userId`, `sessionId` | Who and which session events are sent as. |
377
- | `destroy()` | Stop listening and sending (tests, hot reload). |
378
-
379
- ## What is sent
380
-
381
- Each event, as `POST https://api.daybook.team/analytics/v1/batch?key=dak_…&sdk=js` with a `text/plain` JSON
382
- body, so the browser sends it without a CORS preflight:
383
-
384
- ```json
385
- {
386
- "sent_at": "2026-10-23T10:15:02.120Z",
387
- "events": [{
388
- "event": "signed_up",
389
- "event_id": "0b8f2c4e-…",
390
- "distinct_id": "5d1c…",
391
- "user_id": "user-42",
392
- "timestamp": "2026-10-23T10:15:00.000Z",
393
- "session_id": "a71e…",
394
- "properties": { "plan": "pro", "$url": "https://example.com/signup", "$path": "/signup", "…": "…" },
395
- "context": { "browser": "Chrome", "os": "macOS", "os_version": "10.15.7", "device_type": "desktop", "locale": "en-GB" }
396
- }]
397
- }
398
- ```
399
-
400
- Properties the SDK adds, all starting with `$`:
401
-
402
- | On | Properties |
403
- |---|---|
404
- | every event | `$url`, `$path`, `$host`, `$browser_version`, `$lib_version`, and where the browser first came from: `$initial_referrer`, `$initial_referring_domain`, `$initial_utm_source`, `$initial_utm_medium`, `$initial_utm_campaign`, `$initial_utm_term`, `$initial_utm_content`, `$initial_gclid`, `$initial_fbclid` |
405
- | `$pageview` | `$title`, `$referrer`, `$referring_domain` (`$direct` for none), `$utm_source` … `$utm_content`, `$gclid`, `$fbclid`, `$screen_width`, `$screen_height`, `$viewport_width`, `$viewport_height` |
406
- | `$pageleave` | `$duration_ms` |
407
- | `$session_start` | a session's first event: `$referrer`, `$referring_domain` (`$direct` for none), `$utm_source` … `$utm_content` |
408
- | the browser's first event | `$set_once`: the `$initial_*` values, which Daybook sets once on the person and keeps off the event |
409
-
410
- The `context` fields are columns of their own in Daybook — `browser`, `os`, `os_version`, `device_type`,
411
- `locale`, `app_version` — so a breakdown by them is fast. `country` is added by Daybook from the request.
412
-
413
- `identify` goes to `/analytics/v1/identify` and person properties to `/analytics/v1/people`. A server can
414
- call the same three endpoints with the key in an `X-Daybook-Key` header.
415
-
416
- ## Troubleshooting
417
-
418
- **Nothing on the Events page.** Turn on `debug: true` (or `data-debug`) and look at the console: every
419
- event queued and every answer is logged. Then check **Analytics → Settings → Data health**, which shows the
420
- last event received and anything refused, by reason.
421
-
422
- **A warning names a refused event.** The reason says why: `reserved_event` for a `$` name,
423
- `too_many_properties`, `properties_too_large`, `invalid_event` for a name over 200 characters.
424
-
425
- **`the ingest key was refused`.** The key is wrong or revoked. Issue a new one in Settings.
426
-
427
- **`identify was refused`.** That anonymous id already belongs to another user — two users signed in on
428
- one browser without `reset()` between them, in two tabs at once. Call `reset()` on sign-out.
429
-
430
- **Ad blockers.** The script is `daybook.js`, not `analytics.js`, so blockers that drop analytics scripts by
431
- name pass it; some also block requests to analytics services. For the most complete numbers, install from
432
- npm (bundled code has no script URL to block) and send through a path on your own domain that forwards to
433
- `https://api.daybook.team/analytics/v1/`, then set `apiUrl` to your domain.
434
-
435
- **Content Security Policy.** Allow `connect-src https://api.daybook.team` and, for the script tag,
436
- `script-src https://daybook.team`.
437
-
438
- **Local development.** Use a Development key so test traffic stays apart, and with a local Daybook point
439
- `apiUrl` at it (`http://localhost:5099`).
1
+ # `@daybook/analytics`
2
+
3
+ Product analytics for the web, sent to Daybook's Analytics hub. Page views, sessions, where visitors came
4
+ from, their browser and device — without a line of code — and your own events with `track`. A visitor's
5
+ events before and after they sign in count as one person.
6
+
7
+ Plain JavaScript, React (Next.js too) and Vue (Nuxt too). Its one dependency is `@daybook/core`, which
8
+ has none; about 11 KB gzipped as a script tag, the core included. Safe to import in server-rendered
9
+ code: on the server every call does nothing.
10
+
11
+ It is a module of Daybook's SDK family for the web: the site starts `@daybook/core` once, with one key,
12
+ and analytics is `daybook.analytics`. Started by itself with `init({ key })`, the way before the family,
13
+ it works as it always has.
14
+
15
+ - [Start with Daybook](#start-with-daybook) · [Get a key](#get-a-key)
16
+ - [By itself, the way before](#install): [script tag](#script-tag) · [npm](#npm) · [React](#react) · [Next.js](#nextjs) · [Vue](#vue) · [Nuxt](#nuxt)
17
+ - [Events](#events) · [Page views](#page-views) · [Users: identify and reset](#users-identify-and-reset) · [Properties on every event](#properties-on-every-event)
18
+ - [Consent and privacy](#consent-and-privacy) · [Delivery](#delivery) · [Options](#options) · [Methods](#methods)
19
+ - [What is sent](#what-is-sent) · [Troubleshooting](#troubleshooting)
20
+
21
+ ## Start with Daybook
22
+
23
+ ```sh
24
+ npm install @daybook/core @daybook/analytics
25
+ ```
26
+
27
+ ```ts
28
+ import { Daybook } from '@daybook/core'
29
+ import '@daybook/analytics' // registers itself on import
30
+
31
+ const daybook = await Daybook.initialize('dbk_…')
32
+
33
+ daybook.analytics.track('signed_up', { plan: 'pro' })
34
+ ```
35
+
36
+ Page views, sessions and attribution need nothing more. `daybook.analytics` is the same object `init`
37
+ answers, so everything below about [events](#events), [page views](#page-views) and
38
+ [properties](#properties-on-every-event) is called on it.
39
+
40
+ **The key** is the site's own, `dbk_…`: in Daybook, open the project's settings, find the site under
41
+ **App key** and issue one per environment. It is not a secret: it is in the page's source and only says
42
+ which site, of which project, in which environment. It goes in the code where Daybook is started, never
43
+ in server configuration. The same key starts every Daybook module on the site.
44
+
45
+ **The user**, said once for every module:
46
+
47
+ ```ts
48
+ daybook.identify(user.id, { email: user.email, name: user.name }) // at sign-in
49
+ daybook.reset() // at sign-out
50
+ ```
51
+
52
+ `email` and `name` become the person's `$email` and `$name`. For more of the person's properties, call
53
+ `daybook.analytics.setPersonProperties({ plan: 'pro' })`.
54
+
55
+ **Consent**:
56
+
57
+ ```ts
58
+ const daybook = await Daybook.initialize('dbk_…', { trackingConsent: false }) // off until the visitor agrees
59
+ daybook.setTrackingConsent(true) // from your consent banner
60
+ ```
61
+
62
+ While it is off nothing is sent and nothing is written to the browser, not even the anonymous id. The
63
+ visitor's answer is kept by the core and wins over what `initialize` is given from then on.
64
+ `daybook.analytics.optIn()` and `optOut()` give the same answer.
65
+
66
+ **Analytics' own options** go under `analytics`; every [option](#options) but `key` and
67
+ `optOutByDefault`:
68
+
69
+ ```ts
70
+ await Daybook.initialize('dbk_…', { analytics: { appVersion: '2.1.0', cookieDomain: '.example.com' } })
71
+ ```
72
+
73
+ **React and Vue** take the started instance:
74
+
75
+ ```tsx
76
+ <DaybookProvider client={daybook.analytics}><App /></DaybookProvider>
77
+ ```
78
+
79
+ ```ts
80
+ app.use(createAnalytics({ client: daybook.analytics }))
81
+ ```
82
+
83
+ **By script tag**, one tag for every module:
84
+
85
+ ```html
86
+ <script src="https://daybook.team/sdk/v1/daybook.js" data-key="dbk_…" data-modules="analytics"></script>
87
+ <script>
88
+ daybook.analytics.track('signed_up', { plan: 'pro' })
89
+ </script>
90
+ ```
91
+
92
+ `window.daybook` is the started Daybook: `daybook.identify(…)`, `daybook.analytics.track(…)`. Add
93
+ `feedback` to `data-modules` for the feedback widget with the same key. The attributes and the stub for
94
+ loading it `async` are in [`@daybook/core`'s README](https://www.npmjs.com/package/@daybook/core).
95
+
96
+ **A site that already runs analytics by itself** keeps its visitors when it moves: the anonymous id, the
97
+ session, the registered properties and where each visitor first came from are carried over from what the
98
+ hub key kept, and a visitor who opted out stays opted out. Nothing is counted twice.
99
+
100
+ The rest of this page first describes analytics started by itself, with its hub key, which keeps working.
101
+
102
+ ## Get a key
103
+
104
+ In Daybook, open the project's **Analytics → Settings** and issue an ingest key for the build that will send
105
+ events — one for production, one for staging. Copy it when it is shown: only its first characters are kept.
106
+
107
+ The key starts with `dak_`. It is public by design, like any analytics key: it only says which project
108
+ events are for, so it is fine in a page's source. Revoking it in Settings stops it at once.
109
+
110
+ The same page shows the snippets below with your key filled in.
111
+
112
+ ## Install
113
+
114
+ ### Script tag
115
+
116
+ No build step. Put it in the `<head>`, with your key:
117
+
118
+ ```html
119
+ <script src="https://daybook.team/sdk/v1/daybook.js" data-key="dak_…"></script>
120
+ ```
121
+
122
+ That is all page views need. Your own events, anywhere after it:
123
+
124
+ ```html
125
+ <script>
126
+ daybook.track('signed_up', { plan: 'pro' })
127
+ </script>
128
+ ```
129
+
130
+ The script starts by itself from its `data-` attributes and is `window.daybook`. Every [option](#options)
131
+ has one: `data-api-url`, `data-app-version`, `data-pageviews="false"`, `data-pageleave="false"`,
132
+ `data-persistence="cookie"`, `data-cookie-domain=".example.com"`, `data-opt-out-by-default`,
133
+ `data-respect-dnt`, `data-debug`.
134
+
135
+ **Loading it async.** To keep it off the critical path, load it `async` and put this stub before it. Calls
136
+ made before the script arrives are queued on the stub and played back in order:
137
+
138
+ ```html
139
+ <script>
140
+ window.daybook = window.daybook || { q: [] };
141
+ ['track', 'page', 'identify', 'reset', 'register', 'unregister', 'setPersonProperties', 'optIn', 'optOut']
142
+ .forEach(function (m) { daybook[m] = daybook[m] || function () { daybook.q.push([m, [].slice.call(arguments)]) } })
143
+ </script>
144
+ <script async src="https://daybook.team/sdk/v1/daybook.js" data-key="dak_…"></script>
145
+ ```
146
+
147
+ Without `data-key`, start it yourself: `DaybookAnalytics.init({ key: 'dak_…', … })`, which also sets
148
+ `window.daybook`.
149
+
150
+ **A pinned version.** `daybook.team/sdk/v1/daybook.js` is always the newest build that speaks the v1 API.
151
+ To pin one, load it from npm through a public CDN: `https://cdn.jsdelivr.net/npm/@daybook/analytics@0.4.0`
152
+ or `https://unpkg.com/@daybook/analytics@0.4.0` serve the same file.
153
+
154
+ ### npm
155
+
156
+ ```sh
157
+ npm install @daybook/analytics
158
+ ```
159
+
160
+ ```ts
161
+ import { init } from '@daybook/analytics'
162
+
163
+ const analytics = init({ key: 'dak_…' })
164
+
165
+ analytics.track('signed_up', { plan: 'pro' })
166
+ ```
167
+
168
+ `init` starts one instance for the site and returns it on every later call, so it is safe to call from
169
+ wherever is convenient. Anywhere else, `getAnalytics()` returns it. For a second project on the same
170
+ page, `new DaybookAnalytics({ key })` makes an instance of its own.
171
+
172
+ ### React
173
+
174
+ ```tsx
175
+ import { DaybookProvider } from '@daybook/analytics/react'
176
+
177
+ root.render(
178
+ <DaybookProvider options={{ key: 'dak_…' }}>
179
+ <App />
180
+ </DaybookProvider>,
181
+ )
182
+ ```
183
+
184
+ ```tsx
185
+ import { useAnalytics } from '@daybook/analytics/react'
186
+
187
+ function UpgradeButton() {
188
+ const analytics = useAnalytics()
189
+ return <button onClick={() => analytics.track('upgrade_clicked', { from: 'header' })}>Upgrade</button>
190
+ }
191
+ ```
192
+
193
+ The provider starts analytics once, however often it renders (StrictMode included). Page views follow the
194
+ History API, so React Router, TanStack Router and the rest need nothing more. To use an instance you made
195
+ yourself: `<DaybookProvider client={analytics}>`.
196
+
197
+ ### Next.js
198
+
199
+ App Router: the provider is a client component already (`'use client'` is in the package), so it can go
200
+ straight into the root layout:
201
+
202
+ ```tsx
203
+ // app/layout.tsx
204
+ import { DaybookProvider } from '@daybook/analytics/react'
205
+
206
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
207
+ return (
208
+ <html lang="en">
209
+ <body>
210
+ <DaybookProvider options={{ key: process.env.NEXT_PUBLIC_DAYBOOK_KEY! }}>
211
+ {children}
212
+ </DaybookProvider>
213
+ </body>
214
+ </html>
215
+ )
216
+ }
217
+ ```
218
+
219
+ `useAnalytics()` works in any client component (`'use client'`). In server components, route handlers and
220
+ server actions there is no visitor: track from the client, or send events to the
221
+ [ingest API](#what-is-sent) from your server.
222
+
223
+ Pages Router: wrap `<Component {...pageProps} />` in `pages/_app.tsx` the same way.
224
+
225
+ ### Vue
226
+
227
+ ```ts
228
+ // main.ts
229
+ import { createApp } from 'vue'
230
+ import { createAnalytics } from '@daybook/analytics/vue'
231
+ import { router } from './router'
232
+ import App from './App.vue'
233
+
234
+ const app = createApp(App)
235
+ app.use(router)
236
+ app.use(createAnalytics({ key: 'dak_…', router }))
237
+ app.mount('#app')
238
+ ```
239
+
240
+ ```vue
241
+ <script setup lang="ts">
242
+ import { useAnalytics } from '@daybook/analytics/vue'
243
+
244
+ const analytics = useAnalytics()
245
+ </script>
246
+
247
+ <template>
248
+ <button @click="analytics.track('upgrade_clicked')">Upgrade</button>
249
+ <!-- or, without the import: $daybook.track('upgrade_clicked') -->
250
+ </template>
251
+ ```
252
+
253
+ With `router`, a page view is sent after each finished navigation to a new path, once the new route has
254
+ rendered — a navigation a guard cancels, or one that only changes the query, is not a page. Without it,
255
+ page views follow the History API like everywhere else.
256
+
257
+ ### Nuxt
258
+
259
+ A client-only plugin, with the key in runtime config:
260
+
261
+ ```ts
262
+ // plugins/daybook.client.ts
263
+ import { createAnalytics } from '@daybook/analytics/vue'
264
+
265
+ export default defineNuxtPlugin((nuxtApp) => {
266
+ const { daybookKey } = useRuntimeConfig().public
267
+ nuxtApp.vueApp.use(createAnalytics({ key: daybookKey as string, router: useRouter() }))
268
+ })
269
+ ```
270
+
271
+ ```ts
272
+ // nuxt.config.ts
273
+ export default defineNuxtConfig({
274
+ runtimeConfig: { public: { daybookKey: '' } }, // set NUXT_PUBLIC_DAYBOOK_KEY
275
+ })
276
+ ```
277
+
278
+ ## Events
279
+
280
+ ```ts
281
+ analytics.track('checkout_completed', {
282
+ plan: 'pro',
283
+ seats: 3,
284
+ total: 49.0,
285
+ coupon: null,
286
+ renews_at: new Date('2027-01-01'),
287
+ })
288
+ ```
289
+
290
+ - **Names** are what someone will pick from a list in a chart: an object and a past-tense verb in
291
+ `snake_case` (`project_created`, `invite_sent`). Keep them few and stable, and put the variety in
292
+ properties: `button_clicked { button: 'upgrade' }`, not one event per button. Names starting with `$` are
293
+ Daybook's own and are refused.
294
+ - **Properties** are strings, numbers, booleans, `null`, dates (sent as ISO 8601), lists and objects.
295
+ A number is filtered and summed as a number, so send `49`, not `'49'`. At most 255 per event and 32 KB.
296
+ - In Daybook, **Analytics → Catalog** lists every event and property the project has sent, with a place to
297
+ describe each one.
298
+
299
+ ## Page views
300
+
301
+ On by default: a `$pageview` on load, and one on every navigation of a single-page app (`pushState`,
302
+ `replaceState`, the back button, and `#/` routes). A change of the query string alone is not a new page.
303
+ Each one carries the URL, path, title, referrer, campaign parameters and screen size.
304
+
305
+ When a page is left — a navigation inside the app, or the tab closing — a `$pageleave` says how long it
306
+ was open (`$duration_ms`).
307
+
308
+ To send them yourself instead — after your router has rendered, say:
309
+
310
+ ```ts
311
+ const analytics = init({ key: 'dak_…', autoPageviews: false })
312
+ // on each route change:
313
+ analytics.page()
314
+ analytics.page({ section: 'docs' }) // with properties of your own
315
+ ```
316
+
317
+ ## Sessions
318
+
319
+ A session is one visit: it starts with the first event, and a new one starts after 30 minutes without an
320
+ event (`sessionTimeoutMinutes`), after 24 hours however busy, and on `reset()`. Every tab of the site shares
321
+ the same session. Each one opens with `$session_start`, which carries the page it began on, the referrer
322
+ and the campaign, so Daybook can count sessions, measure how long they last and break them down by entry
323
+ page and source. A session ends at its last event: nothing waits for the tab to close.
324
+
325
+ ## Users: identify and reset
326
+
327
+ Every browser gets an anonymous id on its first visit. When the visitor signs in, say who they are:
328
+
329
+ ```ts
330
+ analytics.identify(user.id, { email: user.email, plan: user.plan })
331
+ ```
332
+
333
+ From then on their events carry the user id, and **everything this browser sent before** counts as theirs
334
+ too — nothing is sent again, Daybook links the two ids. Call it after sign-in and on every page load while
335
+ they are signed in; a repeat costs nothing.
336
+
337
+ When they sign out:
338
+
339
+ ```ts
340
+ analytics.reset()
341
+ ```
342
+
343
+ That starts a new anonymous id and session and forgets registered properties, so whoever uses the browser
344
+ next is somebody new. Daybook joins one anonymous id to one user only, so another user signing in on the
345
+ same browser without a `reset()` in between gets a fresh anonymous id automatically.
346
+
347
+ **Person properties** describe the person rather than one event, and filters and breakdowns can use them:
348
+
349
+ ```ts
350
+ analytics.setPersonProperties({ plan: 'team', company: 'Acme' })
351
+ analytics.setPersonProperties({}, ['trial_ends_at']) // unset
352
+ analytics.setPersonPropertiesOnce({ first_plan: 'free', signed_up_at: new Date() })
353
+ ```
354
+
355
+ `setPersonPropertiesOnce` writes a property only where the person has no value for it yet — under this
356
+ browser's ids or any other they signed in with — so the first value stays; a later `setPersonProperties`
357
+ still changes it. Properties set before sign-in belong to the person after `identify`.
358
+
359
+ Where the browser first came from — `$initial_referrer`, `$initial_referring_domain` and `$initial_utm_*` —
360
+ is set once on the person by itself, with the browser's first event, so a signup weeks later can be broken
361
+ down by the campaign that first brought the visitor.
362
+
363
+ Use the same user id everywhere you identify the person — the web app, the mobile app, your server — and
364
+ their events from all of them are one person's.
365
+
366
+ ## Properties on every event
367
+
368
+ ```ts
369
+ analytics.register({ app_section: 'admin', experiment: 'new-pricing-b' })
370
+ analytics.unregister('experiment')
371
+ ```
372
+
373
+ Registered properties are kept across visits until `reset()`. Options can set some from the start:
374
+ `init({ key, properties: { site: 'docs' } })`.
375
+
376
+ ## Consent and privacy
377
+
378
+ | You want | Do |
379
+ |---|---|
380
+ | Nothing sent or stored until the visitor agrees | `optOutByDefault: true`, then `analytics.optIn()` from your consent banner |
381
+ | The visitor declined | `analytics.optOut()` — remembered on their next visit |
382
+ | To honour Do Not Track and Global Privacy Control | `respectDoNotTrack: true` (an explicit `optIn()` still wins) |
383
+ | To keep something out of what is sent | `beforeSend` (below) |
384
+
385
+ With `optOutByDefault`, nothing is written to the browser either — not even the anonymous id — until
386
+ `optIn()`, which then counts the page the visitor is on. After `optOut()` only the choice itself is kept.
387
+
388
+ ```ts
389
+ init({
390
+ key: 'dak_…',
391
+ beforeSend(event) {
392
+ // Take a reset token out of the URL, and drop internal traffic.
393
+ event.properties.$url = String(event.properties.$url).replace(/token=[^&]+/, 'token=…')
394
+ if (event.properties.$host === 'admin.example.com') return null
395
+ return event
396
+ },
397
+ })
398
+ ```
399
+
400
+ What the SDK keeps in the browser:
401
+
402
+ - `localStorage` → `dbk_<first letters of the key>`: the anonymous id, the user id after `identify`, the
403
+ session, registered properties, where the browser first came from, and the consent choice. With
404
+ `persistence: 'cookie'` this is a first-party cookie of the same name instead (set `cookieDomain:
405
+ '.example.com'` so `www.` and `app.` share one visitor); with `persistence: 'memory'`, nothing.
406
+ - `sessionStorage` → `dbk_<…>_queue`: events not yet sent, so a reload or a dropped connection loses none.
407
+
408
+ Started with Daybook's core, the consent choice is the core's (`localStorage` → `daybook`, with the
409
+ visitor id and who is signed in), and with consent off analytics keeps nothing at all.
410
+
411
+ Requests to Daybook carry no cookies and no credentials. Daybook keeps the visitor's country from the
412
+ request and never their IP address.
413
+
414
+ ## Delivery
415
+
416
+ Events wait about two seconds (`flushIntervalMs`) and go together, up to 50 a request (`batchSize`).
417
+
418
+ - **Offline, a server error, a 429:** the same batch is tried again — 1 s, 2 s, 4 s, up to five minutes, and
419
+ at once when the browser is back online — with the same event ids, so Daybook stores each event once.
420
+ - **Reload:** what was not sent is still in the tab's `sessionStorage` and goes on the next page.
421
+ - **Leaving the page:** when the page is hidden, what is waiting is handed to `navigator.sendBeacon`, which
422
+ the browser delivers after the page is gone.
423
+ - **Refused:** an event Daybook refuses (a `$` name, too many properties…) is named in a console warning,
424
+ and the rest of its batch is kept. A refused key stops the page sending.
425
+ - **A wrong clock:** every request says when it left (`sent_at`, by the visitor's clock), and Daybook moves
426
+ each event by how far that is from when the request arrived. An event from a computer whose clock is
427
+ two hours slow, or one that waited offline all afternoon, is still placed at the time it happened.
428
+
429
+ `await analytics.flush()` sends everything now — before a redirect to another site, for example.
430
+
431
+ ## Options
432
+
433
+ | Option | Default | |
434
+ |---|---|---|
435
+ | `key` | — | **Required.** The ingest key, `dak_…`, or the site's key, `dbk_…`. With Daybook's core the key is the core's. |
436
+ | `apiUrl` | `https://api.daybook.team` | A self-hosted Daybook, or a proxy of your own (see [Troubleshooting](#troubleshooting)). |
437
+ | `appVersion` | — | Your site's version or build, kept as the event's `app_version`. |
438
+ | `autoPageviews` | `true` | Page views on load and on every navigation. `false` to call `page()` yourself. |
439
+ | `pageleave` | `true` | A `$pageleave` with the time on the page. |
440
+ | `persistence` | `'localStorage'` | `'cookie'` to share the visitor across subdomains, `'memory'` to keep nothing. |
441
+ | `cookieDomain` | — | With cookies: `.example.com`. |
442
+ | `sessionTimeoutMinutes` | `30` | Idle minutes after which the next event starts a new session; a session also ends after 24 hours. |
443
+ | `flushIntervalMs` | `2000` | How long events wait to go together. |
444
+ | `batchSize` | `50` | Events per request, at most 1,000. |
445
+ | `properties` | — | Registered from the start, as `register()`. |
446
+ | `optOutByDefault` | `false` | Send and store nothing until `optIn()`. |
447
+ | `respectDoNotTrack` | `false` | Send nothing when the browser asks not to be tracked. |
448
+ | `ignoreBots` | `true` | Send nothing from crawlers and link previews. |
449
+ | `beforeSend` | — | `(event) => event \| null`: change or drop any event. |
450
+ | `debug` | `false` | Log every event queued and every request. |
451
+
452
+ ## Methods
453
+
454
+ | | |
455
+ |---|---|
456
+ | `track(event, properties?)` | An event. |
457
+ | `page(properties?)` | A page view, when `autoPageviews` is off or for a page of your own. |
458
+ | `identify(userId, properties?)` | The visitor signed in. |
459
+ | `reset()` | The visitor signed out. |
460
+ | `setPersonProperties(set, unset?)` | Properties of the person. |
461
+ | `setPersonPropertiesOnce(properties)` | Properties of the person, only where they have none yet. |
462
+ | `register(properties)` / `unregister(name)` | Properties on every event. |
463
+ | `optIn()` / `optOut()` | The visitor's consent. `optedOut` says where it stands. |
464
+ | `flush()` | Send what is waiting now; resolves when it is sent or Daybook cannot be reached. |
465
+ | `distinctId`, `userId`, `sessionId` | Who and which session events are sent as. |
466
+ | `destroy()` | Stop listening and sending (tests, hot reload). |
467
+
468
+ ## What is sent
469
+
470
+ Each event, as `POST https://api.daybook.team/analytics/v1/batch?key=dak_…&sdk=js` with a `text/plain` JSON
471
+ body, so the browser sends it without a CORS preflight:
472
+
473
+ ```json
474
+ {
475
+ "sent_at": "2026-10-23T10:15:02.120Z",
476
+ "events": [{
477
+ "event": "signed_up",
478
+ "event_id": "0b8f2c4e-…",
479
+ "distinct_id": "5d1c…",
480
+ "user_id": "user-42",
481
+ "timestamp": "2026-10-23T10:15:00.000Z",
482
+ "session_id": "a71e…",
483
+ "properties": { "plan": "pro", "$url": "https://example.com/signup", "$path": "/signup", "…": "…" },
484
+ "context": { "browser": "Chrome", "os": "macOS", "os_version": "10.15.7", "device_type": "desktop", "locale": "en-GB" }
485
+ }]
486
+ }
487
+ ```
488
+
489
+ Properties the SDK adds, all starting with `$`:
490
+
491
+ | On | Properties |
492
+ |---|---|
493
+ | every event | `$url`, `$path`, `$host`, `$browser_version`, `$lib_version`, and where the browser first came from: `$initial_referrer`, `$initial_referring_domain`, `$initial_utm_source`, `$initial_utm_medium`, `$initial_utm_campaign`, `$initial_utm_term`, `$initial_utm_content`, `$initial_gclid`, `$initial_fbclid` |
494
+ | `$pageview` | `$title`, `$referrer`, `$referring_domain` (`$direct` for none), `$utm_source` … `$utm_content`, `$gclid`, `$fbclid`, `$screen_width`, `$screen_height`, `$viewport_width`, `$viewport_height` |
495
+ | `$pageleave` | `$duration_ms` |
496
+ | `$session_start` | a session's first event: `$referrer`, `$referring_domain` (`$direct` for none), `$utm_source` … `$utm_content` |
497
+ | the browser's first event | `$set_once`: the `$initial_*` values, which Daybook sets once on the person and keeps off the event |
498
+
499
+ The `context` fields are columns of their own in Daybook, so a breakdown by them is fast:
500
+
501
+ - From the user agent: `browser`, `os`, `os_version`, `device_type`, `locale`, `app_version`. Where Chromium
502
+ answers its client hints, `device_model` (an Android phone's) and the real `os_version`.
503
+ - The person's settings: `timezone`, `languages`, `calendar`, `numbering_system`, `hour_cycle`.
504
+ - The screen and connection: `screen_width`, `screen_height`, `pixel_ratio`, `color_scheme`, `network`.
505
+
506
+ Daybook adds where the request came from, as its edge resolved it: `country`, and with location headers on,
507
+ `continent`, `region`, `region_code`, `city`, `postal_code`, `latitude`, `longitude` (and `timezone` when the
508
+ device sent none). The address itself is never stored — only a keyed hash of it, `ip_hash`.
509
+
510
+ `identify` goes to `/analytics/v1/identify` and person properties to `/analytics/v1/people`. A server can
511
+ call the same three endpoints with the key in an `X-Daybook-Key` header.
512
+
513
+ ## Troubleshooting
514
+
515
+ **Nothing on the Events page.** Turn on `debug: true` (or `data-debug`) and look at the console: every
516
+ event queued and every answer is logged. Then check **Analytics → Settings → Data health**, which shows the
517
+ last event received and anything refused, by reason.
518
+
519
+ **A warning names a refused event.** The reason says why: `reserved_event` for a `$` name,
520
+ `too_many_properties`, `properties_too_large`, `invalid_event` for a name over 200 characters.
521
+
522
+ **`the ingest key was refused`.** The key is wrong or revoked. Issue a new one in Settings.
523
+
524
+ **`identify was refused`.** That anonymous id already belongs to another user — two users signed in on
525
+ one browser without `reset()` between them, in two tabs at once. Call `reset()` on sign-out.
526
+
527
+ **Ad blockers.** The script is `daybook.js`, not `analytics.js`, so blockers that drop analytics scripts by
528
+ name pass it; some also block requests to analytics services. For the most complete numbers, install from
529
+ npm (bundled code has no script URL to block) and send through a path on your own domain that forwards to
530
+ `https://api.daybook.team/analytics/v1/`, then set `apiUrl` to your domain.
531
+
532
+ **Content Security Policy.** Allow `connect-src https://api.daybook.team` and, for the script tag,
533
+ `script-src https://daybook.team`.
534
+
535
+ **Local development.** Use a Development key so test traffic stays apart, and with a local Daybook point
536
+ `apiUrl` at it (`http://localhost:5099`).