# Agent setup
Source: https://docs.wendung.app/agents
Add the SDK to your app, or connect your agent to Wendung analytics and documentation tools.
Choose the setup for your task:
| Your task | Start here |
| - | - |
| Add tracking to an app | The [project setup prompt](/setup) installs the SDK and adds tracking calls. |
| Query analytics from your agent | The [connection prompt](/prompt) registers MCP servers and installs the SDK skill. It does not add tracking to your app. |
SDK setup needs a Wendung project, its publishable key, and allowed app origins. MCP setup needs an agent that supports remote HTTP MCP servers and a Wendung account for OAuth sign-in. The documentation server is public.
## Add Wendung to a project
Drop this prompt into your agent and let it guide you through the setup:
```text Prompt theme={null}
Read https://docs.wendung.app/setup.md and follow it to set up Wendung in this project.
```
It checks your account, proposes funnel steps, and waits for your approval before it edits code. [Read the full setup prompt](/setup).
## Install the skill
The `wendung-sdk` skill teaches your agent the SDK API (install, init options, identity rules, batching, framework patterns) so it does not guess at method names or options. The setup prompt above installs it for you. To install it on its own, use the [skills CLI](https://github.com/vercel-labs/skills), which supports Claude Code, Cursor, Codex, Windsurf, and most other agents:
```bash theme={null}
npx skills add wendung/skills
```
The skill also tells your agent when to use the MCP servers and how to register them with your permission.
## Add the MCP servers
The SDK works without MCP. Add one or both servers depending on what you want your agent to reach. Merge the JSON examples into existing configuration, preserving other servers. For Windsurf, OpenCode, and host-specific connection steps, see the [connection prompt](/prompt).
### wendung: your workspaces, funnels, sites, and analytics
Connects your agent to your real data at `https://api.wendung.app/mcp`: funnels, users, dashboards, and pageview analytics for your sites. You sign in through OAuth, so there are no API keys to paste.
```bash Claude Code theme={null}
claude mcp add --transport http wendung https://api.wendung.app/mcp
```
```bash Codex theme={null}
codex mcp add wendung --url https://api.wendung.app/mcp
codex mcp login wendung
```
```json Cursor: .cursor/mcp.json theme={null}
{
"mcpServers": {
"wendung": { "url": "https://api.wendung.app/mcp" }
}
}
```
```json VS Code: .vscode/mcp.json theme={null}
{
"servers": {
"wendung": { "type": "http", "url": "https://api.wendung.app/mcp" }
}
}
```
### wendung-docs: search these docs
Lets your agent search the Wendung documentation at `https://docs.wendung.app/mcp`. It is public and needs no sign-in.
```bash Claude Code theme={null}
claude mcp add --transport http wendung-docs https://docs.wendung.app/mcp
```
```bash Codex theme={null}
codex mcp add wendung-docs --url https://docs.wendung.app/mcp
```
```json Cursor: .cursor/mcp.json theme={null}
{
"mcpServers": {
"wendung-docs": { "url": "https://docs.wendung.app/mcp" }
}
}
```
```json VS Code: .vscode/mcp.json theme={null}
{
"servers": {
"wendung-docs": { "type": "http", "url": "https://docs.wendung.app/mcp" }
}
}
```
Wendung defaults new client registrations to read access. Write tools require the client to request `mcp:write` and you to grant it during sign-in. The **Make changes** option appears only when that scope was requested. Your workspace role still controls which changes you can make.
## Connect the tools with one prompt
Use the connection prompt to install the skill and register both servers:
1. Click the button below. It copies the connection prompt to your clipboard.
2. Paste the prompt into your agent.
3. Complete Wendung sign-in through your host's OAuth controls. Reconnect the servers or restart the agent if its instructions require it.
4. Once the tools are available, the agent verifies workspace access and a documentation search. Any remaining sign-in or restart step stays pending until it is complete.
Want to read the prompt before you paste it? It is plain markdown and covers Claude Code, Codex, Cursor, Windsurf, OpenCode, and GitHub Copilot. [Read it here](/prompt).
# Wendung.destroy(): Fully shut down the SDK instance
Source: https://docs.wendung.app/api-reference/destroy
Stop the flush timer, remove lifecycle listeners, and attempt a final flush. After destroy(), call init() again before using any other SDK method.
Call `Wendung.destroy()` to shut down the SDK. It stops the flush timer, removes the `visibilitychange` and `pagehide` listeners, and, if the queue is non-empty, fires one final fire-and-forget flush of at most one batch; any remaining events are lost. Afterwards every SDK method throws `[Wendung] Call .init() first` until [`init()`](/api-reference/init) runs again. Most useful for test cleanup and micro-frontends that mount and unmount the SDK repeatedly.
```typescript theme={null}
Wendung.destroy(): void
```
## Parameters
None.
## Returns
`void`
## Examples
### React cleanup in useEffect
```typescript theme={null}
useEffect(() => {
Wendung.init({
apiKey: 'pk_your_publishable_key',
})
return () => {
Wendung.destroy()
}
}, [])
```
### Test suite teardown
```typescript theme={null}
afterEach(() => {
Wendung.destroy()
})
```
The final flush is not awaited and sends at most one batch. To reliably drain the whole queue first, call [`sendBeacon()`](/api-reference/send-beacon):
```ts theme={null}
await Wendung.sendBeacon()
Wendung.destroy()
```
# Wendung.flush(): Send queued events now
Source: https://docs.wendung.app/api-reference/flush
Send one batch of queued events via fetch. Returns a Promise that resolves when the request settles. Server errors re-queue; client errors are dropped.
Call `Wendung.flush()` when you want a send attempt to settle before a specific action, such as navigating to an external URL or asserting in a test. Each call sends at most one batch (up to the effective batch size); events beyond that stay queued for later flushes. Normally you never need this: the SDK flushes automatically on a timer, on batch fill, and on page hide or unload.
Throws if called before [`init()`](/api-reference/init).
```typescript theme={null}
Wendung.flush(): Promise
```
## Parameters
None.
## Returns
Resolves when the HTTP request has settled; it never rejects. Resolves immediately without a network request if the queue is empty or `fetch` is unavailable.
## Error handling
* **4xx responses**: the batch is dropped permanently and a `[Wendung - Warning]` is logged. These typically indicate a malformed payload or invalid API key.
* **5xx responses and network errors**: the batch is re-queued at the front with the same `batchId` and retried on the next flush. There is no backoff and no retry cap.
## Examples
### Flush before external navigation
```typescript theme={null}
async function handleExternalLink(url: string) {
await Wendung.flush()
window.location.href = url
}
```
### Flush in a test
```typescript theme={null}
it('tracks checkout_completed', async () => {
Wendung.step('checkout_completed', { plan: 'pro' })
await Wendung.flush()
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/v1/events'),
expect.objectContaining({ method: 'POST' }),
)
})
```
`flush()` sends one batch per call. To drain the entire queue in one call, use [`sendBeacon()`](/api-reference/send-beacon), which is also the better choice in unload handlers because it sends with `keepalive`.
# Wendung.getConsent(): Read the current analytics consent state
Source: https://docs.wendung.app/api-reference/get-consent
Return the consent state set by init() or the latest setConsent() call, for settings toggles and debugging.
`Wendung.getConsent()` returns the state passed to [`init()`](/api-reference/init) or the latest [`setConsent()`](/api-reference/set-consent) call. It does not read browser storage or your consent manager; it reports what the SDK is doing right now.
Returns `granted` before `init()` is called, which is the default state.
```typescript theme={null}
Wendung.getConsent(): ConsentState
```
## Parameters
None.
## Returns
`'pending' | 'granted' | 'denied'`
## Examples
### A settings toggle
```typescript theme={null}
toggle.checked = Wendung.getConsent() === 'granted'
```
### Flushing queued events
```typescript theme={null}
await Wendung.flush()
```
No consent guard is needed. With `trackPageviews: 'auto'`, `flush()` can send aggregate pageviews while pending. With no active collection, it does nothing.
# Wendung.identify(): Associate all events with a user
Source: https://docs.wendung.app/api-reference/identify
Associate a user ID and optional traits with all subsequent events. Call after login or whenever the current user's identity becomes known to your app.
Call `Wendung.identify()` after a user logs in or whenever their identity becomes available. Every event tracked afterwards carries the provided `userId` and `traits`. Each call replaces the previous identity wholesale; traits are not merged. Events snapshot the identity at the moment `step()` is called, so events already queued keep the identity they were tracked with.
Throws if called before [`init()`](/api-reference/init).
```typescript theme={null}
Wendung.identify(userId: string, traits?: Record): void
```
## Parameters
A unique, stable identifier for the user, such as a database primary key or UUID. Sent in every subsequent event payload as `identity.userId`.
Optional key-value metadata describing the user, for example `email`, `name`, or `plan`. Deep-cloned at call time. Replaces any previously set traits entirely, so include every trait you want to keep. Defaults to `{}`.
## Returns
`void`
## Examples
### After login
```typescript theme={null}
Wendung.identify('usr_01HXYZ', {
email: 'ada@example.com',
name: 'Ada Lovelace',
plan: 'pro',
})
```
### Updating traits on plan change
Because `identify()` replaces traits rather than merging them, spread the existing traits when updating one:
```typescript theme={null}
Wendung.identify(currentUser.id, {
...currentUser.traits,
plan: 'enterprise',
})
```
Traits are sent to your ingest endpoint as-is. Avoid including sensitive values such as passwords or payment card numbers.
Call [`reset()`](/api-reference/reset) on logout so later events are not attributed to the previous user.
# Wendung.init(): Initialize and configure the Wendung SDK
Source: https://docs.wendung.app/api-reference/init
Configure and start the Wendung SDK. Call once from client-side app startup before using any other method.
Call `Wendung.init()` once when your application starts, before any other SDK method. The `consent` and `trackPageviews` options determine whether collection starts. When collection is active, the SDK starts the auto-flush timer and registers `visibilitychange` and `pagehide` listeners to send queued events. Calling `init()` again tears down the previous instance first, so it is safe under React Strict Mode and Next.js Fast Refresh.
```typescript theme={null}
Wendung.init(config: InitConfig): void
```
## Parameters
Your publishable API key, safe to include in browser code. Sent with every request as the `X-API-Key` header. A missing or empty value makes `init()` throw.
Ingest URL. If you override it, it must use `https://`; plain `http://` is only allowed for `localhost`, `127.0.0.1`, or `[::1]`. An invalid or insecure URL makes `init()` throw synchronously.
Milliseconds between automatic flushes. The timer does not start on the server.
Events per request. When the queue reaches this size, a flush is triggered immediately regardless of the timer. The effective value is clamped to 1–100; values above 100 log a one-time warning.
Automatic pageviews are off by default. `true` records full pageviews only with granted consent. `'auto'` records aggregate pageviews while consent is pending, then full pageviews after consent is granted. `denied` stops collection in either mode.
When enabled, the SDK records the initial load and navigation through `pushState`, `replaceState`, and `popstate`. Aggregate collection ignores changes to only the query string or fragment. Pageviews count against your plan's pageview allowance and appear in reports for registered [sites](/help/sites). See [`page()`](/api-reference/page) for manual capture.
The visitor's analytics choice at startup. `pending` allows only aggregate pageviews when `trackPageviews` is `'auto'`; otherwise it stops collection. `granted` enables full analytics. `denied` stops all collection, discards queued events, and removes stored SDK identifiers.
Pass the saved choice on every load. The SDK does not store it. Use [`setConsent()`](/api-reference/set-consent) when the choice changes. See the [consent guide](/guides/consent) for the setup and data limits.
When `true`, the SDK emits `[Wendung]` log messages to the console. Warnings (`[Wendung - Warning]`) fire regardless of this setting. See [Debugging](/configuration/debugging).
## Returns
`void`
## Examples
### Minimal setup
```typescript theme={null}
import { Wendung } from '@wendung/sdk'
Wendung.init({
apiKey: 'pk_your_publishable_key',
})
```
### Script tag
On a site without a build step, the CDN build initializes itself from data attributes and exposes `Wendung` on `window`. See the [script tag guide](/guides/script-tag) for the attribute list.
```html theme={null}
```
### Next.js App Router
See the [Next.js guide](/guides/nextjs) for the recommended `` pattern. A minimal version:
```tsx theme={null}
'use client'
import { useEffect } from 'react'
import { Wendung } from '@wendung/sdk'
export function WendungProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
Wendung.init({ apiKey: process.env.NEXT_PUBLIC_WENDUNG_KEY! })
return () => Wendung.destroy()
}, [])
return <>{children}>
}
```
`Wendung.init()` is browser-only. The package has no import-time side effects, but call `init()` and tracking methods from client-side code. Server runtimes skip the flush timer and page-lifecycle listeners; in runtimes with `fetch`, manual flushes can still attempt network requests.
# Wendung.page(): Record a pageview for the current URL
Source: https://docs.wendung.app/api-reference/page
Queue a pageview for the current page. Only needed when trackPageviews is off or your router bypasses the history API.
Call `Wendung.page()` to record a pageview for the current URL. With `trackPageviews: true` or `'auto'` in [`init()`](/api-reference/init) the SDK calls it for you on the initial load and on every `pushState`, `replaceState`, and `popstate`, so most apps never call it directly. Use it when tracking is off and you want to record specific pages, or when your router changes the URL without the history API.
With granted consent, the first pageview of a page load carries `document.referrer`. Every later pageview carries the previous pageview's URL as its referrer, so entry pages and internal navigation are told apart in reports.
While consent is pending, `page()` records an aggregate pageview only with `trackPageviews: 'auto'`. It omits identifiers, query parameters, fragments, title, and screen size, and restricts referrers to their origin. Otherwise pending or denied consent drops the call.
Throws if called before [`init()`](/api-reference/init).
```typescript theme={null}
Wendung.page(): void
```
## Parameters
None. The SDK reads the page context at call time. The fields depend on the consent state, as described above.
## Returns
`void`
## Examples
### Manual pageviews with tracking off
```typescript theme={null}
Wendung.init({ apiKey: 'pk_your_publishable_key' })
router.afterEach(() => {
Wendung.page()
})
```
### A router that bypasses the history API
```typescript theme={null}
Wendung.init({ apiKey: 'pk_your_publishable_key', trackPageviews: true })
customRouter.on('navigate', () => {
Wendung.page()
})
```
Each collected pageview queues one `$pageview` event that counts against your monthly pageview allowance. Calling `page()` on a navigation the SDK already observed records the page twice.
# Wendung.reset(): Clear user identity and session state
Source: https://docs.wendung.app/api-reference/reset
Attempt to send queued events, clear the stored user ID and traits, and generate new session and anonymous IDs. Call on logout.
Call `Wendung.reset()` when the current user logs out. It attempts to send queued events through [`sendBeacon()`](/api-reference/send-beacon), then clears the stored user ID and traits and generates new session and anonymous IDs. It returns immediately without waiting for the requests to settle.
Queued events keep the identity and session captured when they were recorded, including events re-queued after a failed send. The SDK stays initialized: the flush timer and lifecycle listeners keep running, and subsequent `step()` calls are attributed to a fresh anonymous session.
Throws if called before [`init()`](/api-reference/init).
```typescript theme={null}
Wendung.reset(): void
```
## Parameters
None.
## Returns
`void`
## Examples
### Logout handler
```typescript theme={null}
async function handleLogout() {
await signOut()
Wendung.reset()
}
```
### Account switching
```typescript theme={null}
function switchAccount(newUser: User) {
Wendung.reset()
Wendung.identify(newUser.id, { email: newUser.email, plan: newUser.plan })
}
```
To wait for a send attempt across the whole queue, call `await Wendung.sendBeacon()` before `reset()`. This does not guarantee delivery: network and server failures are re-queued, while `4xx` responses drop the affected batch. If `fetch` is unavailable, events stay queued.
# Wendung.sendBeacon(): Drain the queue with keepalive requests
Source: https://docs.wendung.app/api-reference/send-beacon
Drain the entire event queue as parallel fetch requests with keepalive, so delivery can continue while the page unloads.
Call `Wendung.sendBeacon()` to send everything in the queue at once. It splits the queue into batches and sends them all in parallel as `fetch` requests with `keepalive: true`, which lets the browser finish the requests even while the page is unloading. Despite the name, it does not use `navigator.sendBeacon`; requests carry the same JSON body and headers (including `X-API-Key`) as [`flush()`](/api-reference/flush).
The SDK already calls this automatically on `visibilitychange` (when the page becomes hidden) and `pagehide`. Call it manually only in a custom unload flow, or when you want to drain the whole queue rather than the single batch `flush()` sends.
Throws if called before [`init()`](/api-reference/init).
```typescript theme={null}
Wendung.sendBeacon(): Promise
```
## Parameters
None.
## Returns
Resolves after all batch requests have settled; it never rejects. Failed batches follow the normal [retry rules](/api-reference/flush#error-handling). Resolves immediately if the queue is empty, or if `fetch` is unavailable (events are retained). During a real unload the page may terminate before the promise resolves; `keepalive` lets the requests themselves complete regardless.
## Examples
### Draining the queue before teardown
```typescript theme={null}
async function shutdown() {
await Wendung.sendBeacon()
Wendung.destroy()
}
```
# Wendung.setConsent(): Apply the visitor's analytics choice
Source: https://docs.wendung.app/api-reference/set-consent
Start collection when analytics is allowed, or stop it, drop queued events, and remove the SDK's browser identifiers when it is denied.
Call `Wendung.setConsent()` when the visitor makes or changes their analytics choice. It moves the SDK between the three states described in the [consent guide](/guides/consent). Calling it with the current state does nothing.
Throws if called before [`init()`](/api-reference/init) or with a value other than the three states.
```typescript theme={null}
Wendung.setConsent(state: ConsentState): void
```
## Parameters
`granted` creates the anonymous ID and session, restores a saved identity, and starts collecting from this moment on. With `trackPageviews: true`, the SDK records the current page. If aggregate collection was active, it sends the queued aggregate batch and starts full collection without recounting that page. The next recorded pageview starts the consented web session. Earlier aggregate pageviews stay unlinked.
`denied` stops the flush timer and navigation tracking, discards queued events without sending them, and removes the anonymous ID, session, and identity from browser storage. Later analytics calls are dropped while the state remains `denied`.
`pending` discards the current queue and leaves browser storage untouched. With `trackPageviews: 'auto'`, the SDK collects aggregate pageviews without reading or writing identifiers. Otherwise it stops collection. Custom events and `identify()` calls are dropped while pending.
## Returns
`void`
## Examples
### From a banner
```typescript theme={null}
allowButton.addEventListener('click', () => {
localStorage.setItem('analytics-consent', 'granted')
Wendung.setConsent('granted')
Wendung.identify(currentUser.id)
})
declineButton.addEventListener('click', () => {
localStorage.setItem('analytics-consent', 'denied')
Wendung.setConsent('denied')
})
```
### From a settings toggle
```typescript theme={null}
toggle.addEventListener('change', () => {
Wendung.setConsent(toggle.checked ? 'granted' : 'denied')
})
```
The SDK does not persist the state. Store it yourself and pass it back through the `consent` option of [`init()`](/api-reference/init) on the next page load.
# Wendung.step(): Record and queue a named user event
Source: https://docs.wendung.app/api-reference/step
Queue a named event with optional properties. Events are batched and sent automatically on a timer, on batch fill, or when the page is hidden or unloaded.
Call `Wendung.step()` anywhere in your application to record a named event. The event is queued and flushed automatically: on the next timer tick, when the queue reaches the effective batch size, or when the page hides or unloads. Each event gets a unique `id` (`crypto.randomUUID()`), an ISO 8601 `timestamp` taken at call time, and a snapshot of the current session ID, [identity](/api-reference/identify), and page context.
Throws if called before [`init()`](/api-reference/init).
```typescript theme={null}
Wendung.step(name: string, properties?: Record): void
```
## Parameters
The event name, 1–100 characters. Use a consistent convention, for example `snake_case` pairs like `page_view` or `checkout_completed`. If the name is empty or too long, the call is ignored and a `[Wendung - Warning]` is logged; nothing is thrown.
Optional metadata, sent as `events[].properties`. Must be a plain object with JSON-serializable values; it is deep-cloned at call time. If a non-plain value is passed (array, class instance, `Map`), the call is ignored and a warning is logged. To include array data, nest it under a key.
## Returns
`void`
## Examples
### Simple event
```typescript theme={null}
Wendung.step('page_view')
```
### Event with properties
```typescript theme={null}
Wendung.step('export_clicked', {
format: 'csv',
rowCount: selectedRows.length,
})
```
You do not need to call [`flush()`](/api-reference/flush) after `step()`. The SDK batches and sends automatically; manual flushing is only useful when you want a send attempt to settle before something like an external redirect.
# TypeScript types exported by the Wendung SDK reference
Source: https://docs.wendung.app/api-reference/types
Complete reference for every exported TypeScript type in the Wendung SDK, including configuration, identity, event, and ingest payload shapes.
The Wendung SDK is written in TypeScript and exports its public types from `@wendung/sdk`.
```ts theme={null}
import type {
AggregatePageviewPayload,
Config,
ConsentState,
EventContext,
EventRequestPayload,
Identity,
InitConfig,
Payload,
StepEvent,
} from '@wendung/sdk'
```
## InitConfig
The configuration object accepted by [`Wendung.init()`](/api-reference/init). Only `apiKey` is required; the rest fall back to defaults.
```typescript theme={null}
export type InitConfig = Pick &
Partial<
Pick
> & {
consent?: ConsentState
}
```
## ConsentState
The analytics consent states accepted by `init()` and [`setConsent()`](/api-reference/set-consent) and returned by [`getConsent()`](/api-reference/get-consent). See the [consent guide](/guides/consent) for what each state does.
```typescript theme={null}
export type ConsentState = 'pending' | 'granted' | 'denied'
```
## Config
The full resolved configuration after defaults are applied. Applications normally pass `InitConfig` instead.
```typescript theme={null}
export type Config = {
apiKey: string
endpoint: string
flushInterval: number
maxBatchSize: number
trackPageviews: boolean | 'auto'
debug?: boolean
}
```
Your publishable API key. Sent with every request as the `X-API-Key` header; it does not appear in the request body.
The resolved ingest endpoint. Defaults to `https://ingest.wendung.app/v1/events`. `http://` is only permitted for localhost addresses.
Milliseconds between automatic flushes. Defaults to `5000`.
Maximum events per outbound batch. Defaults to `50`; the effective value is clamped to 1–100.
Defaults to `false`. `true` enables full pageviews with granted consent. `'auto'` also enables aggregate pageviews while pending. Denied consent stops both. See [options](/configuration/options).
When `true`, verbose `[Wendung]` messages are written to the console. Defaults to `false`.
***
## Identity
The user context attached to events. Set by [`Wendung.identify()`](/api-reference/identify), cleared by [`Wendung.reset()`](/api-reference/reset).
```typescript theme={null}
export type Identity = {
userId: string | null
anonymousId?: string
traits?: Record
}
```
The identifier of the current user, or `null` for an anonymous session.
The SDK's random visitor identifier for full analytics. Aggregate pageviews omit identity entirely.
Key-value metadata about the user. Replaced wholesale by each `identify()` call.
***
## EventContext
Environment metadata captured when an event is tracked.
```typescript theme={null}
export type EventContext = {
sdkName: '@wendung/sdk'
sdkVersion: string
pageUrl?: string
referrer?: string
pageTitle?: string
screenWidth?: number
screenHeight?: number
}
```
The literal package name.
The SDK version, also sent as the `X-Wendung-SDK-Version` request header.
The full URL for consented events, or origin and pathname for aggregate pageviews. Absent outside the browser.
For the first pageview, `document.referrer`; for later pageviews, the previous pageview's URL. Aggregate pageviews restrict it to the origin. Absent when empty or outside the browser.
***
## StepEvent
A single tracked event, as queued and as sent in the `events` array of a payload. All snapshot fields are captured at the moment [`Wendung.step()`](/api-reference/step) is called.
```typescript theme={null}
export type StepEvent = {
id: string
name: string
properties?: Record
timestamp: string
sessionId?: string
identity?: Identity
context?: EventContext
}
```
Unique event ID, generated with `crypto.randomUUID()`.
The event name passed to `step()`, 1–100 characters.
Deep-cloned copy of the properties passed to `step()`. Present only when supplied.
ISO 8601 UTC timestamp (`new Date().toISOString()`) recorded at call time.
The session ID active when the event was tracked.
Snapshot of the identity at track time. Later `identify()` calls do not backfill earlier events.
Snapshot of the [event context](#eventcontext) at track time.
***
## EventRequestPayload
The JSON body for full analytics requests. `Payload` is an alias for this type. Pending aggregate pageviews use [`AggregatePageviewPayload`](#aggregatepageviewpayload) instead. Requests carry the headers `Content-Type: application/json`, `X-API-Key`, and `X-Wendung-SDK-Version`.
```typescript theme={null}
export type EventRequestPayload = {
type: 'identity' | 'event'
batchId: string
sessionId: string
identity: Identity
events: StepEvent[]
sentAt: string
context: EventContext
}
export type Payload = EventRequestPayload
```
Payload discriminant. The SDK currently always sends `'event'`.
Random UUID identifying the batch. Stable across retries of the same batch.
The session ID of the first event in the batch, or the current session if the batch is empty.
The identity snapshot of the first event in the batch, or the current identity.
The events being delivered, at most the effective batch size (1–100).
ISO 8601 UTC timestamp taken when the payload is serialized, distinct from the per-event `timestamp` fields.
The context snapshot of the first event in the batch, or the current context.
## AggregatePageviewPayload
The request body for pageviews collected with `trackPageviews: 'auto'` while consent is pending.
```typescript theme={null}
export type AggregatePageviewPayload = {
type: 'event'
collection: 'aggregate'
batchId: string
events: Pick[]
sentAt: string
}
```
Every event has the name `$pageview`. The body and its events contain no visitor identity or session ID. Event and batch IDs support delivery deduplication. The [pageview field reference](/concepts/pageviews#aggregate-pageviews) describes the restricted context.
# Batching and flushing
Source: https://docs.wendung.app/concepts/batching
Events are queued in memory and sent in batches. The flush triggers, the retry rules, and when to flush by hand.
Each `step()` call, and each pageview when `trackPageviews` is on, pushes an event onto an in-memory queue. The queue drains in batches, so a busy page makes a handful of requests instead of one per event. Every request goes through `fetch`; `navigator.sendBeacon` is never used.
## Automatic flush triggers
A timer fires every `flushInterval` milliseconds (default: **5000 ms**) and sends one batch. The timer only runs in the browser.
```ts theme={null}
Wendung.init({
apiKey: 'pk_live_xxxx',
flushInterval: 3000, // flush every 3 seconds instead of 5
})
```
If the queue reaches `maxBatchSize` events before the timer fires, the SDK flushes immediately. The default is **50 events per batch**; the hard maximum per request is **100 events**. Requests must also fit within the [payload limits](#payload-limits).
```ts theme={null}
Wendung.init({
apiKey: 'pk_live_xxxx',
maxBatchSize: 25, // flush sooner on high-traffic pages
})
```
On `visibilitychange` to hidden and on `pagehide`, the SDK drains the entire queue with parallel `fetch` requests using `keepalive: true`, so the browser completes them even as the page unloads.
`destroy()` also sends one last batch after it removes the timer and listeners.
## Payload limits
The ingest endpoint accepts request bodies up to **51,200 bytes (50 KiB)**. Each event's `properties` object can contain at most **20 top-level keys**. Properties and traits must be JSON-serializable and fit within the request body limit.
The SDK batches by event count and does not split oversized request bodies. A request over the byte limit receives `413`; an event with too many properties causes the request to receive `400`. The SDK drops both kinds of rejected batch. Reduce `maxBatchSize` or the data sent with each event to stay within these limits.
## The internal queue
The queue holds at most **1000 events**. When a new `step()` call overflows it, the **oldest** events are dropped to make room. When a failed batch is re-queued at the front and overflows it, the **newest** events are dropped instead.
With a flush every few seconds the queue stays far below this limit. If your users go offline for long stretches, lower `flushInterval` and `maxBatchSize` so the backlog drains in smaller, more frequent batches once they reconnect.
## Retry behavior
| Response | Behavior |
| - | - |
| `2xx` | Batch delivered and removed from the queue. |
| `4xx` | Client error (bad API key, malformed payload). The batch is **dropped**; retrying would produce the same result. |
| `5xx` | Server error. The batch is **re-queued** at the front and retried, with the same `batchId`, on the next flush trigger. |
| Network failure | Same as `5xx`: re-queued for retry. |
There is no backoff and no retry cap; a failing batch is retried on every flush trigger until it succeeds, is dropped by a `4xx`, or is pushed out of the queue.
## Manual flush methods
### `flush()`
Sends at most **one batch** (up to `maxBatchSize` events) per call using `fetch`. Returns a `Promise` that resolves once the request settles; it never rejects, and failed batches are re-queued.
```ts theme={null}
await Wendung.flush()
```
You rarely need `flush()`. The one real use is a send attempt that has to settle before something else happens, like a redirect to an external checkout page.
### `sendBeacon()`
Drains the **entire queue** in parallel `fetch` requests with `keepalive: true`, one per batch of up to `maxBatchSize` events (capped at 100). The name is historical: it never calls `navigator.sendBeacon`, because keepalive `fetch` can carry the API key header and still outlive the page. Returns a `Promise` that resolves when all requests settle; failures are re-queued. If `fetch` is unavailable, events are retained.
```ts theme={null}
await Wendung.sendBeacon()
```
`visibilitychange` and `pagehide` are hooked for you. Call `sendBeacon()` yourself only if a custom unload flow bypasses those events.
## Summary
| Mechanism | Trigger | Sends |
| - | - | - |
| Timer | Every `flushInterval` ms (default 5000) | One batch |
| Batch size | Queue reaches `maxBatchSize` (default 50, max 100) | One batch |
| Page hide | `visibilitychange` / `pagehide` | Whole queue (keepalive) |
| `flush()` | On demand | One batch |
| `sendBeacon()` | On demand | Whole queue (keepalive) |
# Events
Source: https://docs.wendung.app/concepts/events
Events, called steps, are named, timestamped records of user actions. How to track them, what the payload looks like, and how to name them.
An **event** is one thing a user did: a name, optional properties, and a timestamp taken the moment you call `step()`. Pageviews are events too, named `$pageview` and recorded for you when tracking is on; [Pageviews and sessions](/concepts/pageviews) covers those. Events queue in memory and leave in batches, so tracking costs the page a few requests a minute at most.
## Tracking an event
Call `step()` with a name and an optional properties object:
```ts theme={null}
Wendung.step('checkout_started', {
cart_total: 149.99,
item_count: 3,
currency: 'USD',
})
```
The method signature is:
```ts theme={null}
Wendung.step(name: string, properties?: Record)
```
* **`name`**: a string between 1 and 100 characters that identifies the action.
* **`properties`**: an optional plain object with key-value metadata. Every value must be JSON-serializable.
Event names must be **1–100 characters** and properties a plain object (class instances and top-level arrays are rejected). Invalid calls log a `[Wendung - Warning]` and are ignored; nothing throws. Circular references surface later, at serialization time: the whole batch is dropped with a `Failed to serialize batch` warning.
## Event payload structure
Each `step()` call snapshots the current session ID, identity, and page context at track time. The queued event takes this shape:
```json theme={null}
{
"id": "0f8e2c1a-5b7d-4e3f-9a2b-6c1d8e4f0a3b",
"name": "checkout_started",
"timestamp": "2026-04-17T10:23:45.123Z",
"sessionId": "9b2f4d6e-1a3c-4f5b-8d7e-2c4a6b8d0e1f",
"identity": {
"userId": "user_42",
"traits": { "plan": "pro" }
},
"context": {
"sdkName": "@wendung/sdk",
"sdkVersion": "0.1.0",
"pageUrl": "https://app.example.com/checkout",
"referrer": "https://app.example.com/cart"
},
"properties": {
"cart_total": 149.99,
"item_count": 3,
"currency": "USD"
}
}
```
## Full request payload
When a batch is flushed, the SDK POSTs an `EventRequestPayload` to the ingest endpoint. Your API key is sent in the `X-API-Key` header, not in the body:
```json theme={null}
{
"type": "event",
"batchId": "3c5e7a9b-2d4f-4a6c-8e0b-1f3d5c7e9a2b",
"sessionId": "9b2f4d6e-1a3c-4f5b-8d7e-2c4a6b8d0e1f",
"identity": {
"userId": "user_42",
"traits": { "plan": "pro" }
},
"events": [ /* events as shown above */ ],
"sentAt": "2026-04-17T10:23:50.000Z",
"context": { /* context of the first event in the batch */ }
}
```
`sentAt` reflects when the batch was dispatched. Per-event timing is preserved in each event's own `timestamp`, and each event carries its own identity and context snapshots.
## Naming events
Names are the contract between your code and your funnels, so pick a convention and stick to it:
Lowercase words joined by underscores are the most portable format across analytics tools and databases.
```
signup_completed ✓
SignupCompleted ✗
signup-completed ✗
```
Events describe things that already happened, so the name should reflect that.
```
checkout_started ✓
checkout_completed ✓
start_checkout ✗
```
Avoid generic names that are hard to distinguish in dashboards.
```
plan_upgraded ✓
button_clicked ✗ (too vague)
```
## Using properties
Properties are key-value metadata on one event, and they are what you filter and slice by later. Put things there that are specific to that moment. Anything true of the user in general belongs in `identify()` traits instead.
```ts Good: event-specific context theme={null}
Wendung.step('video_played', {
video_id: 'vid_789',
duration_seconds: 312,
autoplay: false,
})
```
```ts Avoid: user-level data belongs in traits theme={null}
// Don't repeat user-level data on every event.
// Call Wendung.identify() once instead.
Wendung.step('video_played', {
user_email: 'alice@example.com', // ✗
user_plan: 'pro', // ✗
video_id: 'vid_789', // ✓
})
```
All property values must be JSON-serializable. Strings, numbers, booleans, arrays, and nested plain objects are all valid. Class instances and functions are not.
# Identity: identify() and reset()
Source: https://docs.wendung.app/concepts/identity
How identify() ties events to a user, what traits ride along on every event, and how sessions and reset() fit together.
Until you say otherwise, events are anonymous and carry only a generated session ID. Once you know who the user is, call `identify()` and every event after that carries their user ID and traits. The session's earlier anonymous events are linked to that user at query time too, so a funnel counts the whole journey as one person. The identity is saved in `localStorage` and restored by `init()`, which means a returning visitor is still identified until you call `reset()` on logout.
## Identifying a user
```ts theme={null}
Wendung.identify(userId: string, traits: Record = {})
```
* **`userId`**: a string that uniquely identifies the user in your system. Use a stable, non-PII identifier like a database ID or UUID.
* **`traits`**: an optional `Record` of attributes that describe the user. Traits are sent with every event after this call.
Each call replaces the identity wholesale. Traits are never merged: calling `identify('user_42', {})` wipes previously set traits, so pass the complete trait set every time. Traits are deep-cloned at call time, so mutating the object afterwards has no effect.
```ts theme={null}
Wendung.identify('user_42', {
email: 'alice@example.com',
name: 'Alice Nguyen',
plan: 'pro',
source: 'google_ads',
})
```
Traits are included in **every event payload**, not just at the moment you call `identify()`. Avoid putting sensitive PII (passwords, card numbers, government IDs) in traits.
## The identity object shape
The identity is stored internally as an `Identity` type and embedded in each request payload:
```ts theme={null}
type Identity = {
userId: string | null
traits?: Record
}
```
Before `identify()` is called, `userId` is `null` and `traits` is an empty object `{}`. After calling `identify()`, both fields reflect the values you provided.
## When to call identify()
Call `identify()` as soon as the user's identity becomes known to your app:
The user just authenticated. You now have a stable user ID to associate with future events.
```ts theme={null}
async function handleLogin(credentials) {
const user = await authService.login(credentials)
Wendung.identify(user.id, { email: user.email, plan: user.plan })
}
```
A new account was just created. Identifying immediately links the first events (onboarding steps, feature tours) to the new user.
```ts theme={null}
async function handleSignup(form) {
const user = await authService.signup(form)
Wendung.identify(user.id, { email: user.email, source: form.referral })
}
```
`init()` restores the saved identity, so a returning visitor is already identified. Re-identifying after you check your auth session is still worth it. It keeps traits fresh and covers users whose browser storage was cleared.
```ts theme={null}
Wendung.init({ apiKey: '...' })
const session = await getSession()
if (session?.user) {
Wendung.identify(session.user.id, { plan: session.user.plan })
}
```
## Sessions
Identity and session are separate. The **session ID** is a UUID generated for you and kept in `sessionStorage` under `@wendung/sdk/session/v1`, so it survives reloads in the same tab. Every event carries it; you never manage it yourself.
A session ends, and a new ID starts, after 30 minutes without activity, after 24 hours in total, when you call `reset()`, or when `identify()` names a different user than the current one (an account switch without a logout). The first `identify()` in an anonymous session keeps the session. That is what makes the earlier anonymous events attributable to the user.
## Resetting identity on logout
Call `reset()` when the user logs out. It does five things:
1. Flushes any pending events. They are delivered with the identity they were tracked under, never dropped.
2. Clears the `userId` (sets it back to `null`)
3. Clears all traits (resets to `{}`)
4. Removes the persisted identity from `localStorage`
5. Generates a new session ID
```ts theme={null}
async function handleLogout() {
await authService.logout()
Wendung.reset()
}
```
After `reset()`, any new events you track are anonymous until you call `identify()` again. They carry the new session ID but no user.
They are sent with `userId: null` and linked at query time to the first user identified in that session. Funnels, user stats, and journeys count the anonymous prefix and the identified tail as one person, with nothing for you to stitch. Events in sessions where nobody ever identifies stay anonymous.
Yes. Each call replaces the current `userId` and `traits` entirely. Re-identifying the same user (for example after a plan upgrade) keeps the session; identifying a different user starts a new session so the two users' events stay separate. Include all traits on every call.
# Pageviews and sessions
Source: https://docs.wendung.app/concepts/pageviews
What a pageview carries, how pageviews become sessions, how path normalization works, and what is never collected.
A pageview is an event named `$pageview` that the SDK records on every page load and, in single-page apps, on every client-side navigation. Automatic pageviews are off by default. `trackPageviews: true` enables full pageviews with granted consent. `trackPageviews: 'auto'` also enables aggregate pageviews while consent is pending. Pageviews use the SDK's queue and batching, but they are metered separately and feed the web analytics pages only. They do not appear in funnels, user journeys, or the Users page.
## What a pageview carries
With granted consent, the SDK sends the full page URL, the page title, the referrer, and the screen size. The ingest endpoint adds request-level context and splits the URL before storing it.
| Field | Where it comes from | Notes |
| - | - | - |
| Hostname | Page URL | Must match a registered site to appear in site reports. |
| Path | Page URL | Stored raw and as a normalized path (see below). |
| Query parameters | Page URL | Dropped unless the parameter is on the site's allowlist. `utm_*` parameters are always captured, as campaign fields. |
| Page title | `document.title` | |
| Referrer | `document.referrer` on the first pageview, the previous page URL on later ones | Also stored as referrer domain and channel type (direct, search, social, email, referral, internal). |
| Browser, OS, device type | `User-Agent` header | |
| Country, city | Request metadata at the edge | Coarse. The IP address itself is not stored. |
| Screen width and height | `window.screen` | |
| Anonymous ID | Generated by the SDK | A random ID kept in the visitor's browser storage so repeat visits count as one visitor. |
| Session ID | Generated by the SDK | See [sessions](#sessions). |
Requests whose `User-Agent` identifies a bot are stored with a bot flag and excluded from every report.
## Aggregate pageviews
With `trackPageviews: 'auto'` and pending consent, the SDK sends the page origin and pathname, an origin-only referrer, timestamps, and SDK version. It excludes query parameters, fragments, titles, screen dimensions, and visitor or session identifiers. Event and batch IDs deduplicate delivery; they do not identify visitors.
The SDK does not read or write browser storage in this state. Requests omit credentials and suppress the transport referrer. Ingest retains country and parsed browser, OS, and device type, but removes city and the full user-agent value from the queued analytics data. It creates no IP-based visitor identifier.
Aggregate pageviews contribute to pageview totals and breakdowns. They cannot count unique visitors, sessions, or repeat visitors. They also carry no campaign tags, even if the site's query parameter allowlist includes those fields.
Pathnames can still contain personal information. Query stripping does not remove names or record identifiers embedded in a path, and dashboard path normalization happens after transmission. Review the routes you track. The collection mode does not establish a consent exemption. See [consent setup and transitions](/guides/consent).
## Sessions
Visitor and session metrics cover consented traffic only. Aggregate pageviews do not enter these calculations.
There is one session ID per browser tab, kept in `sessionStorage`. A session ends after 30 minutes without activity or 24 hours after it started, whichever comes first. The pageviews that share a session ID are folded into one session row:
* **Entry page** and **exit page** are the first and last pageview in the session.
* **Session duration** is the time between the first and the last pageview. A session with one pageview has a duration of zero.
* **Bounce** means the session had exactly one pageview.
* **Views per session** is the consented pageview count divided by the session count over the selected range.
Unique visitors count distinct anonymous IDs in the range, so a visitor with three sessions on three days is one visitor and three sessions.
Session rows are rebuilt once an hour from the events received in the last 48 hours. Visitors and pageviews update as soon as an event lands; bounce rate, session duration, views per session, and entry and exit pages can trail them by up to an hour.
## Campaign parameters
For full pageviews, the ingest endpoint reads campaign tags from the page URL. Aggregate pageviews omit all query parameters and cannot carry these tags. Put the standard parameters on the links you share:
```
https://example.com/pricing?utm_source=newsletter&utm_medium=email&utm_campaign=spring_launch
```
| Parameter | Typical value | Where it shows |
| - | - | - |
| `utm_source` | `newsletter`, `google`, `producthunt` | Sources → Campaigns, UTM source tab |
| `utm_medium` | `email`, `cpc`, `social` | Sources → Campaigns, UTM medium tab |
| `utm_campaign` | `spring_launch` | Sources → Campaigns, Campaign tab |
| `utm_term`, `utm_content` | keyword, variant | Stored on the pageview; not broken down in the panels |
For full pageviews, these five are captured whether or not they are on the site's query parameter allowlist. A session takes its campaign fields from its first pageview, so a visitor who lands on a tagged link and then browses untagged pages counts once for that campaign. All five are filters on the site page.
## Path normalization
Paths with IDs in them fragment your reports: `/users/123` and `/users/456` are the same page to a human but two rows in a table. Both the raw path and a normalized path are stored, and the reports use the normalized one.
Two built-in rules run on every path segment:
| Segment looks like | Becomes |
| - | - |
| Digits only, or a 24-character hex string | `:id` |
| A UUID | `:uuid` |
You can add up to 20 custom rules per site. Each rule is a pattern and a replacement, tested against one path segment at a time. Rules run in order, the first matching rule wins, and a segment that matched a custom rule skips the built-in rules.
| Path | Rule | Normalized path |
| - | - | - |
| `/orders/8f2a1c/receipt` | `^[a-z0-9]{6}$` → `:order` | `/orders/:order/receipt` |
| `/docs/getting-started` | `^getting-started$` → `intro` | `/docs/intro` |
| `/users/123/settings` | none needed | `/users/:id/settings` |
Rules apply to pageviews collected after you save them. Existing data keeps the path it was stored with.
## What is not collected
* No cookies. The anonymous ID lives in the visitor's browser storage and is not readable by other sites. Browser storage still counts as storing information on the visitor's device, so where consent is required, start the SDK with `consent: 'pending'`. See the [consent guide](/guides/consent).
* No IP addresses in any stored row. The edge uses the IP to derive country and city and then discards it.
* Aggregate pageviews send no query parameters. Full pageviews send the URL to ingest, which retains only allowlisted parameters and `utm_*` fields. Those fields and pathnames can still contain personal information.
* Nothing from bots, which are filtered before reporting.
The [privacy policy](https://wendung.app/privacy) lists the same fields for your own privacy notice.
# Debugging
Source: https://docs.wendung.app/configuration/debugging
Enable verbose logging, interpret [Wendung - Warning] messages, and troubleshoot the most common SDK integration issues.
The SDK writes two kinds of console output:
* **Debug logs** (`[Wendung] ...`): opt-in via `debug: true`, trace normal SDK activity.
* **Warnings** (`[Wendung - Warning] ...`): always on, emitted when the SDK hits something unexpected.
## Enable debug mode
```ts theme={null}
Wendung.init({
apiKey: 'pk_your_publishable_key',
debug: import.meta.env.DEV, // or: process.env.NODE_ENV !== 'production'
})
```
With `debug: true`, the SDK logs:
| Log | When |
| - | - |
| `Initialized with endpoint: , flushInterval: , maxBatchSize: ` | On `init()` |
| `queued event eventId=` | On each `step()` |
| `flushing batch batchId= events=` | When a batch is sent |
| `ingest accepted batch batchId=` (plus ` requestId=` when the response carries one) | On a successful response |
| `Tracker reset` | On `reset()` |
## Warning messages
Warnings are emitted regardless of the `debug` setting. This is the complete list.
| Warning | Cause and fix |
| - | - |
| `track() requires an event name between 1 and 100 characters` | Event name is empty, not a string, or over 100 characters. The event is dropped. |
| `track() properties must be a plain object` | `properties` is an array, class instance, or other non-plain value. The event is dropped. |
| `fetch is unavailable; retaining queued events` | The runtime has no `fetch`. Events stay queued until one is available. |
| `fetch is unavailable; retaining queued events because authenticated keepalive delivery is not possible` | Same condition during the page-hide drain. |
| `maxBatchSize exceeds 100; capping payload batches to 100` | Emitted once at init. The ingest endpoint accepts at most 100 events per request; batches are capped to that. |
| `Failed to serialize batch (circular reference or unserializable value); dropping events` | Make properties and traits JSON-serializable. The batch is dropped. |
| `Endpoint rejected batch batchId= with status ; dropping events` | 4xx response. The batch is dropped, never retried. Check your API key and payload. |
| `Endpoint returned status ; re-queuing batch batchId=` | 5xx response. The batch is re-queued and retried on the next flush. |
| `Failed to send payload batchId=, re-queuing batch` | Network error. The batch is re-queued and retried on the next flush. |
Invalid configuration makes `init()` throw instead of warning; see [init() options](/configuration/options#errors).
## Verifying your integration
After your first `step()` call, confirm events are flowing:
1. **Network tab.** Filter for `events` in DevTools. A `POST` to the ingest endpoint appears within 5 seconds (sooner if the batch fills). A 2xx response means the batch was accepted.
2. **Dashboard.** Your user appears in the **Recent identities** card on the Overview within a minute.
3. **Debug mode.** `debug: true` shows the init log, queued events, and flushes in the console.
4. **Pageviews.** With `trackPageviews: true`, the site appears on the **Sites** page within a minute of the first pageview, and the green badge next to its name counts visitors from the last five minutes.
## Common issues
Most common causes, in order:
1. `init()` wasn't called, or ran after the first `step()`. Initialize at app startup.
2. The `apiKey` is wrong or deactivated. Check [Settings → API Keys](/help/settings#api-keys) in your dashboard.
3. A 4xx response is dropping your batches. Look for `[Wendung - Warning] Endpoint rejected batch batchId=... with status 401; dropping events`.
4. The origin isn't allowed. A `403` means the page's origin is missing from [Settings → Allowed origins](/help/settings#allowed-origins). A new project rejects every origin until you add one.
5. An ad-blocker or privacy extension is blocking the request. Blocked requests show as `(blocked)` in the Network tab.
6. Check `Wendung.getConsent()` in the console. `denied` stops all collection. `pending` drops custom events and identification; it sends only aggregate pageviews when `trackPageviews` is `'auto'`. See the [consent guide](/guides/consent).
Every method except `init()` and `getConsent()` throws `[Wendung] Call .init() first` when the SDK isn't initialized. Usual causes:
* A module calls an SDK method at import time, before your entry file runs `init()`.
* In Next.js, a Server Component or Route Handler used the SDK. It is browser-only; move the call into a Client Component.
On `visibilitychange` (hidden) and `pagehide`, the SDK drains the whole queue with parallel `fetch` requests using `keepalive`, so unload delivery normally needs no extra work. If events still go missing:
* A custom unload flow in your app may preempt the SDK's listeners. Call `sendBeacon()` from your own handler to drain the queue.
* Mobile Safari is aggressive about killing background tabs. Some event loss on mobile is unavoidable.
The SDK drops the batch on any 4xx response and never retries it. Check:
* `401 Unauthorized`: the `apiKey` is wrong, disabled, or belongs to a different project.
* `403 Forbidden`: the request's origin isn't on the project's allowed origins list.
* `429 Too Many Requests`: the monthly event quota is used up, or you've hit your plan's rate limit. Check usage in the dashboard.
* `400 Bad Request`: the payload is invalid, for example because an event has more than 20 top-level properties. Check the [payload limits](/concepts/batching#payload-limits).
* `413 Payload Too Large`: the request body exceeds 51,200 bytes (50 KiB). Reduce `maxBatchSize` or the data sent with each event.
Only origins on the allowed origins list can send events, so `http://localhost:3000` is rejected unless you added it. The ingest endpoint answers `403` and the SDK logs `Endpoint rejected batch batchId=... with status 403; dropping events`.
Turn on **Dev mode** in [Settings → Allowed origins](/help/settings#dev-mode). For the next 24 hours the project also accepts loopback origins (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, on any port). It switches itself off after that.
The change can take a few minutes to reach the ingest endpoint. Private network addresses such as `192.168.1.42` are not covered, so testing from a phone on the same Wi-Fi still needs that origin on the allowed list. Requests without an `Origin` header, such as curl or server-side scripts, are always rejected.
`init()` is safe to call twice: each call tears down the previous instance, so Strict Mode won't duplicate timers or listeners.
Duplicate `step()` events usually come from calling `step()` in a `useEffect`, which Strict Mode runs twice in development. Either move the call into an event handler, or guard with a ref:
```tsx theme={null}
const tracked = useRef(false)
useEffect(() => {
if (tracked.current) return
tracked.current = true
Wendung.step('onboarding_viewed')
}, [])
```
* `trackPageviews` is off. Use `true` for pageviews after consent, or `'auto'` for aggregate pageviews while pending and full pageviews after consent. `denied` stops both. See [consent](/guides/consent).
* The hostname is not registered. Pageviews are stored for every hostname, but the reports are per site: add it under **Sites** in the dashboard, or open **All sites**.
* The workspace is on the free plan, which has no pageview allowance. Web analytics needs a paid plan.
* The monthly pageview allowance is used up. The ingest endpoint still answers `202` but reports the pageviews as `dropped`, and the Sites page shows the quota state. Your `step()` events keep flowing.
* The request was rejected entirely. A `403` means the origin is not on the allowed origins list; see the issue above.
With `trackPageviews: 'auto'` and pending consent, this is expected. Aggregate pageviews contain no visitor or session identifiers. They increase pageview totals without increasing unique visitors, current visitors, or sessions. Bounce rate and other session metrics describe consented traffic only.
Changing the configuration does not remove earlier consented visitors from the selected date range. Check the new request body for `collection: 'aggregate'` and no `identity` or `sessionId`. See [aggregate pageviews](/concepts/pageviews#aggregate-pageviews).
* Call `reset()` on logout. The SDK persists identity in `localStorage`, so omitting it can attribute later activity to the previous user.
* Call `identify()` when the user becomes known. Switching between identified user IDs starts a new session. The first `identify()` in an anonymous session keeps that session.
* Each `identify()` replaces the traits object, including clearing it when you omit traits. Already queued events keep their original identity, traits, and session.
## Still stuck?
Reach out to support with:
* Your project ID (dashboard, **Settings → API Keys**)
* A console dump with `debug: true` enabled
* The request/response from your Network tab for a failing event
[Contact support →](mailto:support@wendung.app)
# init() options
Source: https://docs.wendung.app/configuration/options
Reference for every option accepted by Wendung.init(): apiKey, endpoint, flushInterval, maxBatchSize, trackPageviews, consent, and debug, with defaults, types, and constraints.
`init()` accepts a single configuration object. Call it once at application startup, before any other SDK method. Calling `init()` a second time is safe: it tears down the previous instance and starts a fresh one, which makes the SDK compatible with React Strict Mode and Next.js Fast Refresh.
## Options
Your publishable API key. It is safe to include in browser code and is sent as the `X-API-Key` header on every ingest request. Find or create keys under [Settings → API Keys](/help/settings#api-keys) in the dashboard.
The ingest URL. Set it only if you route through your own CDN or run a self-hosted ingest service.
Must use `https://`. `http://` is allowed only when the hostname is `localhost`, `127.0.0.1`, or `[::1]`.
Enable SDK lifecycle logging in the browser console, prefixed with `[Wendung]`. Intended for development; disable in production. See [Debugging](/configuration/debugging) for the full list of messages. Warnings are emitted regardless of this setting.
Milliseconds between automatic event flushes. While collection is active, the SDK sends queued events each time the timer fires. The value is used as-is, without validation or clamping. Flushing also happens when `maxBatchSize` is reached and on page hide, regardless of this interval.
Maximum number of events in a single HTTP request. If the queue reaches this threshold before the flush timer fires, the SDK flushes immediately.
Effective range is `1` to `100`: fractional values are floored, values below `1` are treated as `1`, and values above `100` (the ingest endpoint's per-request limit) are capped with a one-time warning. Your configured value is not mutated.
Automatic pageviews are off by default. `true` records full pageviews only with granted consent. `'auto'` records aggregate pageviews while consent is pending, then full pageviews after consent is granted. `denied` stops collection in either mode.
When enabled, the SDK records the initial load and navigation through `pushState`, `replaceState`, and `popstate`. Aggregate collection ignores changes to only the query string or fragment. Pageviews count against your plan's pageview allowance and appear in reports for registered [sites](/help/sites). See [`page()`](/api-reference/page) for manual capture.
The visitor's analytics choice at startup. `pending` allows only aggregate pageviews when `trackPageviews` is `'auto'`; otherwise it stops collection. `granted` enables full analytics. `denied` stops all collection, discards queued events, and removes stored SDK identifiers.
Pass the saved choice on every load. The SDK does not store it. Use [`setConsent()`](/api-reference/set-consent) when the choice changes. See the [consent guide](/guides/consent) for the setup and data limits.
## Errors
`init()` throws synchronously if the configuration is invalid:
| Error message | Cause |
| - | - |
| `Missing required configuration` | `apiKey` was missing or empty |
| `Invalid endpoint URL` | `endpoint` could not be parsed as a URL |
| `Endpoint must use https:// (http:// allowed for localhost)` | `endpoint` uses `http://` with a non-local hostname |
| `trackPageviews must be true, false, or "auto"` | `trackPageviews` was set to another value |
| `consent must be "pending", "granted", or "denied"` | `consent` was set to another value |
## Complete example
The snippet below shows every option. Only `apiKey` is required.
```ts theme={null}
Wendung.init({
apiKey: 'pk_your_publishable_key',
debug: import.meta.env.DEV, // or: process.env.NODE_ENV !== 'production'
flushInterval: 10000,
maxBatchSize: 25,
trackPageviews: 'auto',
consent: 'pending',
})
```
## See also
* [Quickstart](/quickstart): the minimal setup, in context.
* [Debugging](/configuration/debugging): what `debug: true` logs and how to interpret warnings.
* [`step()`](/api-reference/step) and [`identify()`](/api-reference/identify): the methods you'll call after `init()`.
# Analytics consent
Source: https://docs.wendung.app/guides/consent
Choose whether to collect aggregate pageviews while consent is pending, start full analytics after consent, and stop on withdrawal.
Full analytics uses a random anonymous ID and a session ID in the visitor's browser storage. You can wait for consent before collecting anything, or use `trackPageviews: 'auto'` to collect aggregate pageviews while the choice is pending. Aggregate pageviews contain no visitor or session identifiers.
Your consent manager supplies the visitor's choice. The SDK shows no banner and does not store that choice.
This page describes what the SDK does in each state. Whether your deployment needs consent, and which exemptions apply, is a question for your own legal review.
## The three states
| State | Browser storage | `step()`, `page()`, `identify()` | Network |
| - | - | - | - |
| `pending`, with `trackPageviews: 'auto'` | Nothing is read or written. | Only pageviews are collected. `identify()` and custom `step()` events are dropped. | Aggregate pageview batches are sent. |
| `pending`, with `trackPageviews: true`, `false`, or omitted | Nothing is read or written. | Dropped without queuing for later. | No requests. |
| `granted` | Anonymous ID, session, and identity as usual. | Collected from this moment on. Earlier activity is not replayed. | Batches are sent. |
| `denied` | The SDK's identifiers are removed and not recreated. | Dropped. | Queued events are discarded without being sent. |
Consent defaults to `granted`. Pass the current choice on every page load, using `pending` when the visitor has not chosen. Automatic pageviews are off by default. Set `trackPageviews: true` to wait for consent, or `'auto'` to collect aggregate pageviews while pending.
## Setup
Read the visitor's earlier choice from wherever you keep it and pass it to `init()`. With no saved choice, start pending.
```ts theme={null}
import { Wendung, type ConsentState } from '@wendung/sdk'
const saved = localStorage.getItem('analytics-consent') as ConsentState | null
Wendung.init({
apiKey: 'pk_your_publishable_key',
trackPageviews: 'auto',
consent: saved ?? 'pending',
})
```
This enables aggregate pageviews while pending and full analytics after consent. Use `trackPageviews: true` if you want no collection before consent.
With the [script tag](/guides/script-tag), use `data-track-pageviews="auto"` and `data-consent="pending"`.
Call `setConsent()` from your banner or consent manager. Granting consent starts full analytics for subsequent activity. If aggregate collection was active, the SDK sends the pending aggregate batch without recounting the current page. The next recorded pageview starts the consented web session. With `trackPageviews: true`, granting consent records the current page.
If the visitor is already signed in, call `identify()` again. Calls made while pending were dropped, and earlier aggregate pageviews stay unlinked.
```ts theme={null}
function onAnalyticsChoice(allowed: boolean) {
localStorage.setItem('analytics-consent', allowed ? 'granted' : 'denied')
Wendung.setConsent(allowed ? 'granted' : 'denied')
if (allowed && currentUser) Wendung.identify(currentUser.id)
}
```
Keep a control in your settings that calls `setConsent('denied')`. It stops collection, discards anything still queued, and removes the SDK's identifiers from the browser. Events that were already delivered stay in your project; use the data deletion controls in the dashboard for those.
`getConsent()` returns the current state, which is what a settings toggle reads.
## What aggregate pageviews can measure
Aggregate pageviews contribute to pageview totals and pageview breakdowns. They do not count as unique visitors, current visitors, or sessions. Bounce rate, session duration, views per session, and entry and exit pages describe consented traffic only.
The SDK omits query parameters, fragments, titles, screen dimensions, and visitor identifiers from aggregate pageviews. Pathnames can still contain personal information. See [pageview fields and limitations](/concepts/pageviews#aggregate-pageviews). This option does not establish a consent exemption for your deployment.
## With a consent manager
Connect the manager's callbacks to `setConsent()` and let the manager remain the source of truth. The example uses [CookieConsent](https://cookieconsent.orestbida.com/) with an `analytics` category; other managers expose equivalent hooks.
```ts theme={null}
import * as CookieConsent from 'vanilla-cookieconsent'
import { Wendung } from '@wendung/sdk'
Wendung.init({ apiKey: 'pk_your_publishable_key', consent: 'pending' })
const apply = () =>
Wendung.setConsent(
CookieConsent.acceptedCategory('analytics') ? 'granted' : 'denied',
)
CookieConsent.run({
categories: { necessary: { enabled: true, readOnly: true }, analytics: {} },
onFirstConsent: apply,
onConsent: apply,
onChange: apply,
})
```
`onConsent` also applies the saved choice on later visits. This example leaves automatic pageviews off. Add `trackPageviews: 'auto'` to `init()` if you also want aggregate pageviews while pending and full pageviews after consent.
## In React
A small hook keeps the SDK, your storage, and the UI in one place.
```tsx theme={null}
import { useState } from 'react'
import { Wendung, type ConsentState } from '@wendung/sdk'
const STORAGE_KEY = 'analytics-consent'
export function useAnalyticsConsent() {
const [consent, setConsent] = useState(Wendung.getConsent())
const choose = (choice: 'granted' | 'denied') => {
localStorage.setItem(STORAGE_KEY, choice)
Wendung.setConsent(choice)
setConsent(choice)
}
return { consent, choose }
}
```
Render your notice while `consent === 'pending'` and a switch in settings bound to `consent === 'granted'`. The Wendung dashboard itself works this way: it asks once after sign-in and keeps the switch under **Account**.
## What the SDK does not do
* It does not store the choice. Pass it to `init()` on every page load.
* It does not replay activity from before consent, and it does not record which notice the visitor saw. Keep that record in your consent manager if you need to demonstrate consent.
* It does not retract batches that were already delivered.
* It does not collect aggregate pageviews after denial. `denied` stops all analytics, including with `trackPageviews: 'auto'`.
# Funnel tracking
Source: https://docs.wendung.app/guides/funnels
Model a user journey as named step events, attach traits with identify(), and read conversion and drop-off per stage in the dashboard.
A funnel is an ordered list of named steps, for example `signup_completed → profile_filled → first_project_created → invited_teammate → activated`. You emit those steps from your code with `step()` and define the same list in the dashboard. Events are matched to the funnel by name, and each stage shows its conversion rate, drop-off, and time to complete.
## How it works
A funnel has two sides, joined by name:
1. **In your code:** you call `step(name)` at each point where a user reaches a milestone. Names are plain strings of 1 to 100 characters, with no schema and no predefined vocabulary.
2. **In the dashboard:** you create the funnel and put those step names in order.
Start with the code. Step names are collected as events arrive, so by the time you create the funnel they are waiting in a dropdown. The dropdown lists names in the order users typically perform them, so picking top to bottom reproduces the real journey, and each name shows its usage count, which makes a typo with three events easy to spot.
If you build the funnel in the dashboard first, the names you type there become the contract. Every `step()` call has to match them character for character, or the step stays empty.
Each `step()` call records one event with a timestamp, the identified user if there is one, and any properties you attach. The server orders those events per user and builds the funnel from them.
You don't need to call steps in order, and you don't need to call every step. Users who skip steps show up as drop-offs in the funnel between the last step they hit and the next one they didn't.
## Traits vs properties
You attach metadata to events in two places, and the distinction matters for how you analyze your funnel later.
* **Traits** go on the user via `identify()`. Use them for things that are true about the user across all events: plan, acquisition source, email, name. Traits ride on every event that follows until you call `identify()` again or `reset()`. Each `identify()` call replaces the identity and traits wholesale; nothing is merged.
* **Properties** go on a single event via the second argument to `step()`. Use them for things specific to that one moment: which plan the user selected *at this step*, the button variant they clicked, a referrer from the current page.
As a rule of thumb: if you'd have to pass the same value to every `step()` call, it belongs in `identify()`.
```ts theme={null}
// Set once; attached to every event that follows
Wendung.identify('user_0042', {
email: 'alice@example.com',
plan: 'trial',
source: 'product_hunt',
})
// Per-event properties only; plan and source come from traits
Wendung.step('signup_completed')
Wendung.step('plan_selected', { selected_plan: 'pro' })
```
## A typical onboarding funnel
Here's what a five-step onboarding funnel looks like when instrumented across a real application. Each call happens in the context where the milestone actually occurs, not all in one block.
```ts theme={null}
// After signup form submits successfully, in your signup component
Wendung.identify(user.id, {
email: user.email,
plan: user.plan,
source: user.source,
})
Wendung.step('signup_completed')
```
```ts theme={null}
// After the user saves their profile, in your profile form handler
Wendung.step('profile_filled')
```
```ts theme={null}
// After the first project is created, in your project creation flow
Wendung.step('first_project_created', { template: 'blank' })
```
```ts theme={null}
// After a teammate invite is sent, in your team invite component
Wendung.step('invited_teammate', { invite_method: 'email' })
```
```ts theme={null}
// Once the user has met your activation criteria, usually triggered server-side
// from your own logic and signaled to the client
Wendung.step('activated')
```
Once these events are flowing, create a funnel in the dashboard with these five step names in order. Conversion, drop-off, and timing show up for every user who enters, including the ones already tracked.
## Naming best practices
Consistent names make funnels easier to read and compare over time.
* **Use `snake_case`.** `signup_completed`, not `SignupCompleted` or `signup-completed`.
* **Use past-tense verbs.** Events describe something that already happened. `profile_filled`, not `fill_profile`.
* **Be specific.** `first_project_created` is more useful than `project_event` when you want to segment later.
* **Keep names stable.** Renaming a step in your code without updating the funnel in your dashboard will break the match. Treat step names like API contracts.
## FAQ
No. You can send `step()` events first and create the funnel afterward; every event is stored regardless. You just won't see conversion numbers until the funnel and its step order exist in the dashboard.
Steps are independent events. Order is not enforced and no step is required. If a user never reaches `invited_teammate`, no event is recorded for it, and the funnel shows the drop-off between the last step they hit and this one.
Yes. Each `step()` call creates a new event with its own timestamp. If a user completes `first_project_created` twice, two events are recorded. The funnel counts each user once per step, using their first occurrence by default.
You can call `step()` before `identify()`. Events are recorded with `userId: null` and the current session ID. Once you call `identify()`, later events belong to that user, and the session's earlier anonymous events are linked to them at query time, so the funnel counts the whole journey as one person. Anonymous events stay anonymous only when nobody identifies in that session.
Yes. Step names are strings; they have no owning funnel. If `signup_completed` is the first step in your onboarding funnel and also appears in a separate "trial-to-paid" funnel, a single `step('signup_completed')` call feeds both.
## What's next
How `identify()`, `reset()`, and sessions tie events to users.
Full reference for the `step()` method, including property constraints.
# Next.js (App Router)
Source: https://docs.wendung.app/guides/nextjs
Add the SDK to a Next.js App Router project: initialize it in a client provider, track funnel steps, identify users, and turn on pageviews.
The SDK runs entirely in the browser, so in Next.js you initialize it inside a client component and wrap your app in a provider. This guide covers the App Router setup. If you're on Pages Router, see the note at the bottom.
## Setup
Add `@wendung/sdk` to your project.
```bash npm theme={null}
npm install @wendung/sdk
```
```bash pnpm theme={null}
pnpm add @wendung/sdk
```
```bash yarn theme={null}
yarn add @wendung/sdk
```
Then add your publishable key to `.env.local`:
```bash .env.local theme={null}
NEXT_PUBLIC_WENDUNG_KEY=pk_...
```
Your key is under [Settings → API Keys](/help/settings#api-keys) in the dashboard.
Create `app/providers/wendung-provider.tsx`. It initializes the SDK once on mount and tears it down on unmount.
```tsx app/providers/wendung-provider.tsx theme={null}
'use client'
import { useEffect } from 'react'
import { Wendung } from '@wendung/sdk'
export function WendungProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
Wendung.init({
apiKey: process.env.NEXT_PUBLIC_WENDUNG_KEY!,
})
return () => {
Wendung.destroy()
}
}, [])
return <>{children}>
}
```
`init()` is idempotent. If an instance is already running, as happens under React Strict Mode or Fast Refresh, it is torn down before the new one starts, so there are no duplicate flushes or listeners.
Wrap your app's `children` with `` in `app/layout.tsx`.
```tsx app/layout.tsx theme={null}
import { WendungProvider } from './providers/wendung-provider'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
{children}
)
}
```
`layout.tsx` can remain a server component. Only `WendungProvider` itself needs `'use client'`.
Call `step()` from any client component to record an event. The name should match a step in one of your funnels. The optional second argument is a plain object of properties.
```tsx app/components/signup-form.tsx theme={null}
'use client'
import { Wendung } from '@wendung/sdk'
export function SignupForm() {
async function handleSubmit() {
// ...your signup logic
Wendung.step('signup_completed', {
plan: 'pro',
source: 'google_ads',
})
}
return
}
```
Identify a user as soon as you know who they are, usually right after login. The cleanest pattern is a small client component that reads the session and calls `identify()` once:
```tsx app/providers/wendung-identity.tsx theme={null}
'use client'
import { useEffect } from 'react'
import { Wendung } from '@wendung/sdk'
import { useSession } from '@/lib/auth'
export function WendungIdentity() {
const { data: session } = useSession()
useEffect(() => {
if (!session?.user) return
Wendung.identify(session.user.id, {
email: session.user.email,
plan: session.user.plan,
})
}, [session?.user?.id])
return null
}
```
Drop `` inside `` in your layout. It runs once the session is available and re-identifies if the user changes.
If your auth flow is fully client-side, you can also call `identify()` from your login handler. Use whichever fits your stack.
Next.js App Router does not trigger a full page load between routes. With `trackPageviews: true` the SDK records the initial load and every client-side navigation, so route tracking needs no code of your own:
```tsx app/providers/wendung-provider.tsx theme={null}
Wendung.init({
apiKey: process.env.NEXT_PUBLIC_WENDUNG_KEY!,
trackPageviews: true,
})
```
For aggregate pageviews while consent is pending, use `trackPageviews: 'auto'` and pass the current `consent` state. Call `Wendung.setConsent('granted')` to switch to full analytics, or `'denied'` to stop collection. See the [consent guide](/guides/consent) for saving and restoring the choice.
Register the hostname under **Sites** in the dashboard to see the traffic. Pageviews use a separate monthly allowance from events; see the [web analytics guide](/guides/web-analytics).
Keep funnel steps and pageviews apart. `step()` is for actions like `signup_completed` or `checkout_started`; pageviews are collected for you and reported per site.
Call `reset()` when the user signs out. It flushes pending events under the old identity, clears the user ID and traits, and starts a new session.
```tsx app/components/logout-button.tsx theme={null}
'use client'
import { Wendung } from '@wendung/sdk'
export function LogoutButton() {
async function handleLogout() {
// ...your sign-out logic
Wendung.reset()
}
return
}
```
## Server Components and Server Actions
The SDK is browser-only. Don't call it from Server Components, Route Handlers, or Server Actions. Importing it there is harmless, but calling it is not a supported path: the browser lifecycle hooks never run, and a server runtime with `fetch` may still fire network requests. To record an event that results from a server action, either:
* Return a signal from the action and call `step()` in the client component that invoked it, or
* Call `step()` optimistically before invoking the action.
## Using Pages Router?
The setup is similar: initialize in `pages/_app.tsx` inside a `useEffect`, and use `router.events` from `next/router` for route-change tracking. A dedicated Pages Router guide is coming; for now, the [Quickstart](/quickstart) covers the core flow.
## What's next
Turn your tracked step names into a funnel in the dashboard.
Every option accepted by `init()`, `identify()`, `step()`, and `reset()`.
# Static sites and the script tag
Source: https://docs.wendung.app/guides/script-tag
Add Wendung to a site without a build step: one script tag from cdn.wendung.app initializes the SDK, tracks pageviews, and exposes Wendung for step calls.
If your site has no bundler (plain HTML, Hugo, Jekyll, Webflow, WordPress, or any page without an npm build), load the SDK from `cdn.wendung.app` instead of installing `@wendung/sdk`. The script initializes itself from the tag's data attributes and exposes `Wendung` as a global, so you can track steps from inline handlers or a plain `
```
Each attribute maps to an [`init()` option](/configuration/options):
| Attribute | Option | Notes |
| - | - | - |
| `data-api-key` | `apiKey` | Required for automatic initialization. Leave it out to call `Wendung.init()` yourself. |
| `data-track-pageviews` | `trackPageviews` | A bare attribute or `"true"` enables full pageviews with granted consent. `"auto"` enables aggregate pageviews while pending, then full pageviews after consent. Omitted or `"false"` disables automatic pageviews. |
| `data-debug` | `debug: true` | Presence turns SDK lifecycle logging on. |
| `data-endpoint` | `endpoint` | Only when you route ingest through your own domain. |
| `data-consent` | `consent` | `pending` allows aggregate pageviews only with `data-track-pageviews="auto"`. `granted` enables full analytics; `denied` stops all collection. See the [consent guide](/guides/consent). |
`flushInterval` and `maxBatchSize` have no attribute. To set them, omit `data-api-key` and call `Wendung.init()` from your own script with the full options object.
Do not use `async`. An async script can run after the inline code that calls `Wendung`, and those calls throw `[Wendung] Call .init() first`.
With pageview tracking enabled, the SDK records page loads according to the visitor's consent state. Open **Sites** in the dashboard and add your hostname so the pageviews show up as visitors, pages, and sources. The [web analytics guide](/guides/web-analytics) covers path rules and the site dashboard.
Pageviews count against your plan's monthly pageview allowance, separate from events. The free plan has none. See [Plans and limits](/help/plans#monthly-pageviews).
`Wendung` is available on `window` once the script has run. Inline handlers work because they fire after `DOMContentLoaded`:
```html theme={null}
```
Scripts of your own that call `Wendung` must run after it. Give them `defer` too (deferred scripts run in document order), or wait for `DOMContentLoaded`:
```html theme={null}
```
Every method from the [API reference](/api-reference/init) is available on the global with the same signature.
## Versions and caching
The CDN serves three paths for the current release:
| Path | What it serves | Cache |
| - | - | - |
| `/sdk/latest/wendung.js` | The latest published release, including new major versions | 5 minutes, with stale responses allowed for up to 24 hours while revalidating |
| `/sdk/v0/wendung.js` | The latest 0.x release | 5 minutes, with stale responses allowed for up to 24 hours while revalidating |
| `/sdk/0.2.0/wendung.js` | The pinned 0.2.0 release | One year, immutable |
Use `latest` to receive every SDK release automatically. Use `v0` to stay on the 0.x series, or pin an exact version to control when you update. Both `latest` and the major channel can change behavior when a new release is published.
To use the latest release, change the script's `src`:
```html theme={null}
```
This example collects aggregate pageviews while pending. Calling `Wendung.setConsent('granted')` switches to full analytics; calling `Wendung.setConsent('denied')` stops collection. Use a bare `data-track-pageviews` attribute if you want to wait for consent before collecting anything. See the [consent guide](/guides/consent) to save and restore the visitor's choice.
## Content Security Policy
If your site sets a CSP, allow the script host and the ingest host:
```
script-src https://cdn.wendung.app;
connect-src https://ingest.wendung.app;
```
## What differs from the npm package
* You use the `Wendung` global instead of `import { Wendung } from '@wendung/sdk'`. The methods are identical.
* Initialization happens in the tag. Calling `Wendung.init()` again afterwards is safe and replaces the configuration, the same as in the package.
* There are no TypeScript types on the global. If you type-check inline scripts, declare `Wendung` yourself or move to the package.
# React SPA (Vite, CRA, React Router)
Source: https://docs.wendung.app/guides/spa
Add the SDK to a React single-page app: initialize once at startup, identify users after login, and turn on pageviews for React Router navigations.
In a single-page app the page never fully reloads, so you initialize the SDK once at startup and keep that instance alive for the whole visit. Logins and logouts become SDK calls; route changes are picked up for you once pageview tracking is on.
This guide uses React with Vite and React Router as the primary example. The same patterns apply to Create React App or any other React setup; only the environment variable prefix changes (`VITE_` vs `REACT_APP_`).
## Setup
Add `@wendung/sdk` to your project.
```bash npm theme={null}
npm install @wendung/sdk
```
```bash pnpm theme={null}
pnpm add @wendung/sdk
```
```bash yarn theme={null}
yarn add @wendung/sdk
```
Then add your publishable key to `.env`:
```bash .env theme={null}
VITE_WENDUNG_KEY=pk_...
```
Your key is under [Settings → API Keys](/help/settings#api-keys) in the dashboard.
Call `init()` at your entry point, before rendering. This starts the flush loop and registers the page-unload listeners.
```tsx src/main.tsx theme={null}
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { Wendung } from '@wendung/sdk'
import { App } from './App'
Wendung.init({
apiKey: import.meta.env.VITE_WENDUNG_KEY,
})
createRoot(document.getElementById('root')!).render(
,
)
```
`init()` is idempotent. React Strict Mode double-invokes effects in development, and Vite's hot module replacement can re-run your entry file. Both are handled, with no duplicate listeners or flushes.
Call `step()` whenever a user completes a step in one of your funnels. The name should match a step defined in the dashboard. The second argument is an optional object of properties.
```tsx src/components/SignupForm.tsx theme={null}
import { Wendung } from '@wendung/sdk'
export function SignupForm() {
async function handleSubmit() {
// ...your signup logic
Wendung.step('signup_completed', {
plan: 'pro',
source: 'google_ads',
})
}
return
}
```
Once you know who the user is, call `identify()` with a stable user ID and any traits you want on the events that follow.
```ts theme={null}
import { Wendung } from '@wendung/sdk'
async function onLoginSuccess(user: {
id: string
email: string
plan: string
}) {
Wendung.identify(user.id, {
email: user.email,
plan: user.plan,
})
}
```
The identity is saved in `localStorage` and restored by `init()`, so a reload keeps the user identified. Each `identify()` call replaces the identity and traits wholesale, with no merging, and `reset()` clears it. Re-identify anyway once your app has checked its own session, so traits stay current.
SPAs do not fire page loads on navigation, and you do not need to emit anything yourself: with `trackPageviews: true` the SDK records the initial load and every React Router navigation.
```ts src/main.tsx theme={null}
Wendung.init({
apiKey: import.meta.env.VITE_WENDUNG_KEY,
trackPageviews: true,
})
```
For aggregate pageviews while consent is pending, use `trackPageviews: 'auto'` and pass the current `consent` state. Call `Wendung.setConsent('granted')` to switch to full analytics, or `'denied'` to stop collection. See the [consent guide](/guides/consent) for saving and restoring the choice.
Register the hostname under **Sites** in the dashboard to see the traffic. If your router changes the URL without the history API, call `page()` after each navigation instead. Pageviews use a separate monthly allowance from events; see the [web analytics guide](/guides/web-analytics).
Keep funnel steps and pageviews apart. `step()` is for actions like `signup_completed` or `checkout_started`; pageviews are collected for you and reported per site.
Call `reset()` when the user signs out. It flushes pending events under the old identity, clears the user ID and traits, and starts a new session.
```ts theme={null}
import { Wendung } from '@wendung/sdk'
async function onLogout() {
// ...your sign-out logic
Wendung.reset()
}
```
## Advanced: teardown in micro-frontends
Most SPAs never call `destroy()`. The SDK lives as long as the page does, and the queue drain on page hide handles the final send.
The exception is a micro-frontend shell that loads and unloads sub-applications at runtime. There, call `destroy()` in your cleanup hook to stop the flush loop, remove the listeners, and send one last batch:
```tsx theme={null}
import { Wendung } from '@wendung/sdk'
Wendung.init({ apiKey: import.meta.env.VITE_WENDUNG_KEY })
const root = createRoot(document.getElementById('root')!)
root.render()
export function unmount() {
Wendung.destroy()
root.unmount()
}
```
After `destroy()`, call `init()` again before using any other method.
## What's next
Turn your tracked step names into a funnel in the dashboard.
Every option accepted by `init()`, `identify()`, `step()`, and `reset()`.
# Web analytics setup
Source: https://docs.wendung.app/guides/web-analytics
Turn on pageview tracking, register your site, clean up paths, and read the site dashboard.
Web analytics answers traffic questions for a site: how many people came, from where, which pages they read, and how long they stayed. It runs on the same SDK install as your funnels. This guide takes you from a fresh project to a site dashboard with clean paths.
## Setup
Automatic pageviews are off by default. Set `trackPageviews: 'auto'` to collect aggregate pageviews while consent is pending and full pageviews after consent. Pass the visitor's current consent choice on every load.
```ts theme={null}
Wendung.init({
apiKey: 'pk_your_publishable_key',
trackPageviews: 'auto',
consent: 'pending',
})
```
Call `Wendung.setConsent('granted')` or `Wendung.setConsent('denied')` from your consent manager. If you want to wait for consent before collecting anything, use `trackPageviews: true`. See the [consent guide](/guides/consent) for saving and restoring the choice.
The SDK observes `pushState`, `replaceState`, and `popstate`. Aggregate collection ignores changes to only the query string or fragment.
If your router changes the URL without touching the history API, call `page()` yourself after each navigation. It records a pageview for the current URL.
Pageviews count against your plan's monthly pageview allowance, separate from events. The free plan has no allowance, so web analytics is available on paid plans only. See [Plans and limits](/help/plans#monthly-pageviews).
Pageviews are stored per project, but the reports are per hostname. Open **Sites** in the sidebar and click **Add site**. The hostname picker lists your project's [allowed origins](/help/settings#allowed-origins); pick the one you want to report on.
If you deploy the same app on several hostnames, register each one. The **All sites** row on the Sites page combines them.
Open the site's settings to add path rules and a query parameter allowlist. Built-in rules already collapse numeric IDs and UUIDs to `:id` and `:uuid`; add your own for anything else that fragments a page, such as slugs or short codes.
Paste a real URL into **Preview** to see the normalized result before you save. Rules affect pageviews collected from then on. See [Pageviews and sessions](/concepts/pageviews#path-normalization) for how matching works.
Click the site to open it. The metric rail shows unique visitors, pageviews, sessions, views per session, bounce rate, and session duration; click any of them to chart it. The panels below rank pages, sources, locations, and devices. Click a row to filter the whole page by that value, and hover a row for copy and filter actions.
Pageviews include aggregate and consented traffic. Visitors, sessions, engagement metrics, and the current-visitors badge cover consented traffic only. Aggregate pageviews do not create visitors or sessions. See [metric coverage](/concepts/pageviews#sessions).
To see where a campaign's traffic goes, add the standard parameters to the links you send out. The ingest endpoint reads them from full pageviews. Aggregate pageviews omit query parameters, so they cannot carry campaign tags.
```
https://example.com/?utm_source=newsletter&utm_medium=email&utm_campaign=spring_launch
```
The visits show up under **Sources → Campaigns**, split by campaign, UTM source, or UTM medium, and each value is a filter. See [campaign parameters](/concepts/pageviews#campaign-parameters) for what is captured.
Open **Overview** and switch to the **Web** tab. It shows the **All sites** card and one card per pinned site, each with a 24-hour sparkline and a visitor count. Use the **+** card to pin more sites, and the card menu to unpin them. The Overview remembers which tab you looked at last.
Dashboards have three web block types: **Web summary**, **Web trend**, and **Web breakdown**. Each block can be scoped to one site or to all sites, and each has its own period. Shared dashboards include them.
## Filtering
Every panel row is a filter. Clicking `/pricing` in **Top pages** filters the report to that path; clicking again removes the filter. The filter bar accepts **is** and **is not** for every dimension, so "Country is not United States" is one click away from the row action. Filters and the date range are part of the URL, so a filtered view can be shared as a link.
## What's next
What each pageview carries and how sessions and normalized paths are derived.
Every panel and control on the site dashboard.
# Billing
Source: https://docs.wendung.app/help/billing
Find your current subscription, manage your plan and payment details, cancel renewal, and download invoices.
Manage your subscription from **Workspace settings → Billing**. Each workspace has its own plan, shared by all projects in that workspace.
Only the workspace owner can open **Billing** and manage the subscription. If
you do not see **Billing**, ask the workspace owner to make the change.
## Open Billing
1. Sign in to the [Wendung dashboard](https://dashboard.wendung.app).
2. Open the workspace selector at the top of the sidebar and select the workspace you want to manage. If you do not have one, choose **New workspace**, or **Create workspace** on the Workspaces page, and finish creating it.
3. Open the selector again and choose **Workspace settings**.
4. Select **Billing** in the workspace sidebar.
Selecting a different workspace takes you back to the project list. Open **Workspace settings → Billing** again to manage that workspace's subscription.
## View your current subscription
The **Subscription** section shows your **Current plan** and its status. The next row shows the relevant date:
* **Renewal** shows when an active subscription renews.
* **Subscription ends** shows the end date when renewal has been canceled.
* **Trial ends** shows when a trial finishes.
* **Payment retry** appears when a payment needs attention.
A workspace on the Free plan shows **Free forever, nothing renews**. A trial without a card moves to Free when it ends, with nothing to cancel. See [Plans and limits](/help/plans) for what each plan includes.
## Manage your subscription
Select **Manage subscription** in the Subscription section to open the billing portal for the selected workspace. Follow the portal's options to manage your subscription and payment details, and review the amount and effective date before confirming a change.
The button changes with your subscription's status:
| Button | What it opens |
| - | - |
| **Upgrade plan** | The plan picker, when the workspace has no paid subscription. |
| **Manage subscription** | The billing portal for an existing subscription. |
| **Reactivate plan** | The billing portal when renewal has already been canceled. Opening it does not reactivate the plan by itself. |
| **Update payment** | The billing portal when a payment needs attention. |
## Cancel a subscription
1. Open **Workspace settings → Billing** for the workspace whose subscription you want to cancel.
2. Select **Manage subscription**.
3. In the billing portal, choose the cancellation option, review the effective date, and complete the confirmation.
4. Return to **Billing** to check the subscription status and end date.
When cancellation is scheduled for the end of the billing period, Billing shows **Canceling** and **Subscription ends**. The workspace moves to the Free plan when the subscription ends. To keep the subscription, select **Reactivate plan** and follow the portal's instructions before the end date.
You can also use the public [Cancel subscription form](https://wendung.app/cancel-subscription) without signing in. It records your declaration and provides a downloadable receipt and email confirmation. Wendung processes the request manually and confirms the outcome separately.
## Download invoices
The **Invoices** section below Subscription lists previous invoices with their date, amount, and payment status. Select **PDF** to download an available invoice or **View** to open its hosted page.
## Consumer withdrawal
To exercise your right of withdrawal as a consumer, use the [withdrawal form](https://wendung.app/legal/withdrawal#withdraw-contract). It is also linked beneath the Subscription description in Billing. The [Withdrawal / Widerruf page](https://wendung.app/legal/withdrawal) explains the right and includes the model withdrawal form.
# Dashboards
Source: https://docs.wendung.app/help/dashboards
Compose funnel charts, metrics, and lists into custom views, and share them with a public link.
Dashboards let you compose the pieces you care about into a single view: funnel charts, metric trends, breakdowns, and lists. Build one per team, per launch, or per question you keep asking.
## Creating a dashboard
Go to **Dashboards** in the sidebar and click **New dashboard**. Give it a name and an optional description, then click **Create dashboard**.
The dashboards list shows every dashboard with its block count and when it was last updated. The row menu lets you **Rename**, **Share**, or **Delete** a dashboard.
Creating and editing dashboards requires the owner or admin role. Members can
view dashboards and use saved views, but not change the layout.
## Blocks
A dashboard is a grid of blocks. Each block is one visualization, configured independently, and a dashboard can hold up to 24 of them.
| Block | What it shows |
| - | - |
| **Funnel flow** | Conversion and drop-off across every funnel step. |
| **Conversion trend** | One funnel step's conversion rate over time. |
| **Step drop-off** | Drop-offs and conversion time between steps. |
| **Time to convert** | How long conversion takes between two funnel steps. |
| **Metric trend** | One project metric over time. |
| **Metric** | A metric value and its change from the prior period. |
| **Segment breakdown** | Identities by country, OS, or another dimension. |
| **Top funnels** | Which funnels have the largest drop-off this period. |
| **Recent identities** | The people and visitors seen most recently. |
| **Recent events** | The latest events and their delivery status. |
| **Web summary** | Visitors, pageviews, bounce rate, and other site metrics for one site or all sites. |
| **Web trend** | One site metric over time, from visitors to session duration. |
| **Web breakdown** | Top pages, sources, countries, or devices for a site. |
## Editing the layout
Click the pencil button at the bottom of the dashboard to enter edit mode. The dock expands to **Add block**, **Page width**, **Cancel**, and **Save**.
### Adding a block
Click **Add block** and pick a block type. Funnel blocks are only available once your project has at least one funnel.
* Funnel blocks ask for the **funnel**, and depending on the type a **step**, a **from step** and **to step**, or a **metric**.
* Metric blocks ask for the **metric**: active identities, total events, events per identity (avg or median), or single-event rate.
* Segment breakdown blocks ask for the **dimension**.
* Web blocks ask for the **site** (one hostname or all sites), plus a **metric** for the trend block or a **dimension** for the breakdown block. They need a plan with a pageview allowance.
* Every block has a **Period** setting. **Dashboard period** follows the date range picker at the top of the dashboard. Alternatively, pin the block to a fixed range like **Last 90 days**. Blocks with a fixed period show a clock badge in their header.
### Arranging blocks
While in edit mode:
* **Move** blocks by dragging the grip handle in their header.
* **Resize** blocks by dragging their edges. Each block type has a sensible minimum size.
* **Configure** or **Remove** an existing block from the menu in its header.
* **Page width** switches between **Contained**, which keeps the dashboard centered at a readable width, and **Full width**.
Click **Save** to persist the layout, or **Cancel** to discard your changes.
## Filters, date range, and saved views
Dashboards have the same filter bar and date range picker as the rest of the app, applied to every block that follows the dashboard period. Filters cover **Plan**, **Source**, **Country**, **Device type**, **Browser**, **OS**, plus custom user traits and event properties.
Like funnels, dashboards support up to 15 [saved views](/help/funnel-details#saved-views) via the bookmark icon. Dashboard views are shared: they are visible to everyone in the workspace, and the default view applies for everyone who opens the dashboard.
## Sharing a dashboard
Click the share icon at the top right to publish a read-only version of the dashboard that anyone with the link can view.
Once the **Public link** toggle is on, you can:
* **Require a password**. Workspace members can always view without one.
* **Allow filtering**, so visitors can filter the dashboard data.
* **Share saved views**, so visitors can switch between the dashboard's saved views.
Recent identities and Recent events blocks contain user-level data and stay
hidden on the public page. Disabling the public link breaks the current URL
permanently.
# Events
Source: https://docs.wendung.app/help/events
Inspect every request your SDK sends and debug why events were delivered, rejected, or quarantined.
The Events page is the delivery log for your project. Every request your SDK sends shows up here with its status, so when a number looks wrong somewhere else in the app, this is where you find out whether the data ever arrived.
## The request log
Each row is one request from the SDK, which can contain several events in a batch. The columns show the status, when the request arrived, how many events it carried, the origin it was sent from, a human-readable reason, and the request ID with a copy button.
A request can have one of these statuses:
| Status | Meaning |
| - | - |
| **Delivered** | Everything in the request was accepted and stored. |
| **Queued** | The request was received and is waiting to be processed. |
| **Retrying** | Processing failed and Wendung is retrying automatically. |
| **Partial failure** | Some events were stored, others were quarantined. The reason column tells you why, for example "Some rows were quarantined". |
| **Rejected** | The whole request was turned away, for example from an origin that isn't allowed. |
| **Failed final** | Processing failed and no more retries will happen. |
## Finding the right request
The toolbar gives you a few ways to narrow the log down:
* **Search** across request logs
* The **status select** limits the list to one status, which makes "show me everything that failed" a one-click question
* **Filters** opens advanced filters for exact lookups: **Request ID**, **Batch ID**, **Session ID**, **User ID hash**, **Origin**, and **SDK version**
* The **date range picker** works like everywhere else in the app
* **Columns** lets you hide columns you don't need
Debugging a specific user's session? Grab the session ID from their profile
on the Users page and paste it into the Session ID filter to see exactly
which of their requests arrived.
## Request details
Click a row to open the full request log. This is the fastest way to answer "why didn't this event show up".
The drawer is split into three sections:
* **Request**: the request and batch IDs, status, when the request was received and delivered, and how many events it contained.
* **Client**: the origin the request came from, the SDK version, and the browser, OS, device type, and location when known.
* **Payload summary**: the session and user the events belong to, and what the batch contained.
For anything other than Delivered, the drawer also shows the reason, so you can tell the difference between a misconfigured origin, a quarantined payload, and a temporary processing issue. Rejections with the reasons `rate_limited` or `event_quota_exceeded` mean the project hit a [plan limit](/help/plans) rather than a technical problem.
Requests from an origin that isn't on your allowed origins list are rejected.
If you see rejections right after a deploy, check **Settings** and add the
new domain to allowed origins. When the rejected origin is `localhost`, turn
on [Dev mode](/help/settings#dev-mode) instead of adding it to the list.
# Funnel details
Source: https://docs.wendung.app/help/funnel-details
Read the funnel flow, find your biggest drop-off, compare segments, and save the views you come back to.
Click any funnel in the list to open its details page. This is where you spend most of your analysis time: it shows how users move through the funnel, where they leave, how long they take, and which segments convert best.
## The funnel flow
The main visualization shows every step with its user count and conversion rate relative to the funnel start. The segment with the worst conversion is highlighted in orange, so the biggest problem is always visible at a glance.
You can interact with the flow directly:
* **Click a step** to open the step inspector. It shows how many users reached the step, what share of the funnel start that is, the step's conditions, and shortcuts to **View trends** or **Edit step**.
* **Hover between two steps** and click the marker to inspect that transition: how many users converted, the median time, the slowest 10 percent, and whether the transition is above or below your average step conversion. From here you can jump into **Compare segments**.
* Use the icons at the top right of the graph to switch between **Funnel view** and **Segment comparison**, or to enter **Focus mode** for a distraction-free, full-width graph. Press Escape to exit focus mode.
The step inspector is also the quickest way to check what a step actually counts: the conditions table lists every property rule on the step, like `source equals google_ads`, so you never have to guess why a number looks the way it does.
The [health indicator](/help/funnels#funnel-health) next to the funnel name shows the same ring as the funnels list. Hover it for the verdict and up to three findings about what changed in the selected period.
The **Complete within** button at the top right of the page opens the funnel definition panel, where you can review every step and its conditions, and jump to **Edit definition**.
Use the funnel name in the breadcrumb to switch to another funnel without
going back to the list.
## Drop-offs and timing
Below the graph, the step breakdown card has two tabs:
* **Drop-offs** shows how many users you lost at each step, as a count and a percentage. The biggest loss is highlighted in orange so it matches what the graph is pointing at. Click a row to see the actual users who stopped there.
* **Timing** shows the median and p90 time users take between steps. Click a row to open the time-to-convert analysis.
## Segment cards
Three cards break conversion down by segment, each with tabs:
* **Countries** and **Cities**
* **Devices**, **OS**, and **Browsers**
* **Source** and **Plan**
Each row shows how many users entered from that segment, their conversion rate, and how far above or below the funnel average they land. This is the fastest way to spot patterns like "mobile converts 20 points worse than desktop".
## Step analysis
From the step inspector, **View trends** opens the step analysis drawer. It has two tabs, and both come with their own filters and date range, so you can dig into a step without touching the page-level view.
### Trend
The Trend tab charts one step over time, with summary tiles for **Users in period**, **Avg per day**, and **Avg conversion** above the chart. Use the **Step** selector to switch steps and the **Metric** selector to change what the chart plots:
* **Users**: how many users hit the step each day
* **Conversion from first step**: the share of funnel entrants that made it here
* **Step conversion**: the share of users from the previous step that made it here
### Time to convert
The Time to convert tab shows the distribution of how long users take between any two steps you select with the **From** and **To** selectors. The tiles above the histogram summarize it: **Median**, **p90**, **Average**, and the number of **Converters** in the period. Below the chart, a one-line summary calls out where most users land, for example "Most users (55.6%) convert between 2m and 4m".
If the median looks fine but p90 is far off, a slice of your users is getting
stuck. Add a filter, like country or plan, to find out which one.
## Filters and date range
The filter bar works the same way as on the [Overview page](/help/overview#filtering-data), scoped to the dimensions that matter for funnel analysis: **Country**, **Device type**, **Browser**, **OS**, **Plan**, **Source**, plus custom **user trait** and **event property** filters.
The date range picker supports the same presets and the **Compare to previous period** toggle. With comparison on, every step shows a delta badge against the previous period.
## Exporting funnel data
The **Export** button downloads CSV reports:
* **Funnel steps**: users, conversion, and timing per step
* **Segment breakdown**: conversion by country, device, and more
## Saved views
If you keep applying the same filters and period, save them. Click the bookmark icon next to Export to open saved views.
A saved view stores the relative period, filters, graph view mode, and the compared step pair. Each funnel can hold up to 15 views, and each view can be:
* **Pinned**, so it sorts to the top of the list
* **Set as default**, so it's applied automatically every time you open the funnel
* **Renamed** or **updated** to the current filters
* **Deleted**, which only removes the shortcut. Your funnel and analytics data stay unchanged.
Set your most important slice as the default view. For example "Paid plans,
last 30 days" opens automatically whenever you visit the funnel.
# Funnels
Source: https://docs.wendung.app/help/funnels
Create funnels from your tracked steps and keep an eye on conversion health across all of them.
A funnel is an ordered list of events users must complete, in order. The Funnels page lists every funnel in your project and gives you a quick read on which ones need attention.
## The funnels list
Each row shows the funnel's name, its overall conversion rate, a health indicator, and the largest drop-off between two steps. All columns are sortable, and the search box filters by name.
The menu at the end of each row lets you **Edit** or **Delete** a funnel. Deleting a funnel only removes the funnel definition, not the underlying events.
## Funnel health
The health indicator is a small ring. The arc fills to the funnel's conversion rate, and the color carries the verdict:
| Health | Meaning |
| - | - |
| **Healthy** (green) | Conversion is 50% or higher |
| **Moderate** (orange) | Conversion is between 20% and 50% |
| **Critical** (red) | Conversion is below 20% |
A funnel that no one entered in the selected date range shows an empty gray ring instead.
Hover the indicator to open the health preview. It shows the conversion rate in a larger ring, the verdict, and up to three findings about what changed and where:
* Health changed against the previous period: "Health dropped from Healthy to Critical this period."
* Conversion moved, and when the movement started: "Conversion is down 22pp vs the previous period, mostly since Tuesday."
* The biggest drop-off between two steps, including when that step converts far below the funnel's own average.
* The segment that carries most of the loss: "Mobile Safari accounts for 61% of that loss."
* A step where users take several times longer than at any other step.
A finding only appears when the data clearly supports it. If nothing stands out, the preview says that instead of guessing.
**View funnel** at the bottom of the preview opens the details page. The same indicator appears in the **Top funnels** card on the [project overview](/help/overview) and next to the funnel name on the [details page](/help/funnel-details).
Creating, editing, and deleting funnels requires the owner or admin role.
Members get a read-only view. The number of funnels per project depends on
your [plan](/help/plans); once the limit is reached, the New funnel
button is disabled until you delete a funnel or upgrade.
## Creating a funnel
Click **New funnel** at the top right to open the funnel builder.
### Basics
Give your funnel a clear name (up to 100 characters) and an optional description.
### Conversion window
Set how long users have to complete every step after entering the funnel, for example "2 weeks". You can use minutes, hours, days, or weeks, anywhere between 1 minute and 365 days. The default is 2 weeks.
This deadline is separate from the report date range: the date range decides who enters the funnel, the conversion window decides how long they get to finish it.
### Steps
Define between 2 and 20 steps. Each step is an event name, and the event picker suggests events you already track, along with how often each one occurred.
Steps match event names exactly, so the names here must match what you send with [`Wendung.step()`](/api-reference/step). Drag the handle on the right of a step to reorder, and use **Add Step** to append more.
### Step conditions
Every step can optionally be narrowed down with property conditions. Expand a step and click **Add condition** to pick one of the event's properties.
For each condition you choose a property, an operator, and a value:
* **equals** or **does not equal** a specific value. The value list shows what you've actually tracked, with counts, and you can also enter a custom value.
* **exists**, which matches any value. Pick **Any value** in the value list.
A step can have up to 10 conditions, and each property can only be used once per step. A user only advances through the step if the event matches all of its conditions.
Conditions are a good way to build variants of the same funnel. For example,
two "Signup flow" funnels where the first step is `signup_completed` with
`plan equals free` in one and `plan equals trial` in the other.
When you're done, click **Create**. The funnel starts analyzing your existing events right away, so you don't need to wait for new data.
# Overview
Source: https://docs.wendung.app/help/overview
Understand your project at a glance. The Funnels tab covers identities, events, and engagement; the Web tab covers your sites.
The Overview page is the first thing you see when you open a project. It has two tabs under the title. **Funnels** answers how many people used your product, how much they did, and how that breaks down by country, device, and more. **Web** shows traffic for your registered sites. The page reopens on the tab you looked at last.
## Web tab
The **All sites** card combines every hostname the project receives pageviews from: the visitors active right now, a 24-hour sparkline, and unique visitors, sessions, pageviews, and views per session for the last 24 hours. Click it to open [All sites](/help/site-details).
Next to it, one card per pinned site shows that site's 24-hour visitors and trend. Pin sites from the **+** card or from the [Sites page](/help/sites); the card menu unpins them. Until you register a site, the tab shows a shortcut to web analytics.
The sections below describe the **Funnels** tab.
## Metrics
The top of the page shows four metrics. The selected metric is rendered as a large trend chart, and the other three appear as smaller cards with sparklines. Click any small card to promote it to the large chart.
| Metric | What it tells you |
| - | - |
| **Active identities** | People or anonymous visitors who did something in this period. |
| **Total events** | Every action tracked in this period, from known users and anonymous visitors. |
| **Events per identity** | How much a single identity does in this period, shown as both average and median. A wide gap between the two means a few power users pull the average up. |
| **Single-event rate** | Share of people who showed up once and never came back. Lower is better. |
When [period comparison](#date-range-picker) is turned on, each metric also shows a delta badge against the previous period.
## Cards
Below the metrics you'll find a set of cards that link deeper into the app:
* **Recent events** shows the latest event batches and their delivery status. **View all** takes you to the Events page.
* **Top funnels** lists your funnels sorted by largest drop-off, each with its conversion rate and a [health indicator](/help/funnels#funnel-health). Hover the indicator for the verdict and what changed. **View all** takes you to the Funnels page.
* **Recent identities** shows the most recently seen users and their last step. Clicking one opens that user on the Users page.
* **Segment breakdown** splits your identities across a dimension. The default tabs are **Countries**, **Devices**, **OS**, and **Browsers**.
The gear icon on the segment breakdown card lets you add any other dimension
as an extra tab: Country, City, Device type, Browser, Operating system, Plan,
Source, Identity, Lifecycle, Engagement, Referrer, Landing page, Environment,
SDK version, or any user trait you send with `identify()`.
## Filtering data
The filter bar sits at the top left of the page. Until you add a filter it reads "All identities and events".
You can filter by:
* **Plan** and **Source**, from the traits you send with `identify()`
* **Referrer** and **Landing page**
* **Country** and **City**
* **Device type**, **Browser**, and **OS**
* **Identity**: identified users vs anonymous sessions
* **Lifecycle**: new vs returning identities
* **Engagement**: single-event vs engaged identities
* **Performed step** and **Did not perform step**, to include or exclude people based on funnel steps
* **Environment** and **SDK version**
* **User trait** and **Event property**, for anything custom you track
Trait and property filters support both positive and negative matching: **is** / **is any of**, and **is not** / **is none of**. You can combine up to 10 trait or property filters, with up to 20 values each.
## Date range picker
The date range picker sits at the top right. It defaults to **Last 30 days**.
* Presets: **Last 7 days**, **Last 30 days**, **Last 90 days**, **Last 365 days**, or **Custom** with a range calendar.
* **Compare to previous period** adds a comparison line to the trend chart and delta badges to every metric and card.
Presets longer than your plan's [data retention](/help/plans#data-retention)
are locked. Upgrade your plan to unlock longer date ranges.
## Exporting your data
The **Export** button downloads your overview data as CSV:
* **Trend over time**: users and events per day, week, or month
* **Segment breakdown**: users and engagement by the selected dimension
This is useful when you want to analyze the data in a spreadsheet or BI tool, or share it with your team.
# Plans and limits
Source: https://docs.wendung.app/help/plans
What each plan includes, how the free plan and trial work, and how event and pageview quotas, rate limits, data retention, and MCP queries behave when you hit a limit.
Every paid plan includes the full product: funnel analysis, web analytics for your sites, segment breakdowns, trends, dashboards with public sharing, user profiles, saved views, CSV export, and the MCP server. Plans differ only in their limits, with one exception: the free plan has no pageview allowance, so web analytics starts with Starter.
## Plans at a glance
| | Free | Starter | Growth | Scale |
| - | - | - | - | - |
| **Price** | \$0 | \$25/month | \$49/month | \$99/month |
| **Projects** | 1 | 1 | 3 | 10 |
| **Funnels per project** | 1 | 3 | 10 | Unlimited |
| **Events per month** | 10,000 | 150,000 | 500,000 | 2,500,000 |
| **Pageviews per month** | Not included | 500,000 | 2,000,000 | 10,000,000 |
| **Data retention** | 7 days | 30 days | 90 days | 365 days |
| **Ingest rate limit** | 5 requests/s | 5 requests/s | 20 requests/s | 100 requests/s |
| **MCP queries per month** | 50 | 250 | 2,000 | 10,000 |
| **Team members** | 1 | Unlimited | Unlimited | Unlimited |
Plans apply per workspace: every project in a workspace shares the same plan. You can see your current usage at any time under your workspace's **Usage** page, which shows events, pageviews, MCP queries, and data retention with warnings as you approach a limit.
## The free plan and the trial
Signing up requires no credit card. Creating your first workspace starts a 14-day Starter trial with full Starter limits. There are no payment details and nothing to cancel.
When the trial ends, the workspace moves to the Free plan on its own. Nothing is deleted:
* Events keep flowing, up to 10,000 per month.
* Dashboards and funnels keep working, showing the last 7 days.
* Older history is hidden, not destroyed. It is kept for 60 days, and upgrading within that window restores it.
* Funnels beyond the free limit are locked, not deleted. The most recently updated funnel stays active. Editing a funnel makes it the active one, deleting one frees the slot, and upgrading unlocks everything.
* Teammates beyond the single free seat keep their membership but can't open the workspace until it's upgraded.
You get an email three days before the trial ends and another when the workspace lands on Free. Additional workspaces start directly on the Free plan, since the trial runs once per account.
## Monthly events
The event quota counts stored custom events, recorded with `step()`, across all projects in your workspace. `identify()` updates the identity attached to subsequent events; it does not emit an event or consume event quota. A request from the SDK can carry up to 100 events, but the quota always counts individual events, not requests.
* Usage resets at the start of each billing cycle. On the Free plan, that's the start of each calendar month (UTC).
* At **80%** of the quota, the Usage page starts warning you. On the Free plan you also get an email.
* At **100%**, ingestion stops: new requests are rejected with HTTP `429` and the message "Event quota exceeded for the current billing period" until the quota resets or you upgrade. On the Free plan, an email tells you the moment this happens.
Rejected requests show up on the [Events page](/help/events) with the reason `event_quota_exceeded`, so a silent tracking gap is easy to diagnose.
Usage is checked periodically, about every 30 minutes, so enforcement does
not kick in the exact second you cross the line. Events accepted during that
window still count and are not deleted.
## Monthly pageviews
Pageviews have their own quota, counted across all projects in the workspace: every `$pageview` event the SDK records with `trackPageviews` on, or that you send with `page()`, is one pageview. Funnel steps and `identify()` calls never count here, and pageviews never count against the event quota.
* Usage resets with the billing cycle, like events.
* At **80%** the Usage page warns you and you get an email.
* At **100%**, new pageviews are dropped and you get an email. The ingest endpoint keeps accepting requests and answers `202` with a `dropped` count, so your funnel events in the same request are stored as usual. Reporting resumes when the quota resets or you upgrade.
The free plan has no pageview allowance. Turning on `trackPageviews` on a free workspace stores nothing; the Sites page shows an upgrade prompt instead.
## Rate limiting
The ingest endpoint rate limits **requests, not events**, per project. Limits are measured over 10-second windows, so short bursts above the per-second rate are fine as long as the window average holds. With up to 100 events per request, even the Free plan sustains around 500 events per second. The monthly event quota is the real ceiling.
When a project exceeds its rate, the ingest endpoint responds with HTTP `429` and "Rate limit exceeded". These rejections appear on the [Events page](/help/events) with the reason `rate_limited`.
In practice the browser SDK stays far below these limits on its own: it batches up to 50 events per request and flushes every 5 seconds, so a single page sends a fraction of a request per second.
The SDK treats `429` like any other client error and drops the affected
batch rather than retrying it, so events sent while rate limited or over
quota are lost. If you send events from your own backend, apply the same
batching and add a backoff on `429` responses.
## Data retention
Retention controls how far back you can look, and how long your event data is kept:
* Date ranges are limited to your retention window. Presets beyond it are locked in the date picker with an upgrade hint, and API requests for older ranges return a `date_range_exceeded` error.
* On paid plans, data older than your retention window is permanently deleted by a daily cleanup job.
* On the Free plan, the two are decoupled: queries see the last **7 days**, but data is only permanently deleted after **60 days**. Upgrading within 60 days brings the hidden history back immediately.
Retention applies retroactively on downgrades between paid plans. If you
move from Growth (90 days) to Starter (30 days), events older than 30 days
are permanently deleted during the next daily cleanup. Export anything you
need before downgrading. Landing on the Free plan is gentler: history is
hidden first and only deleted after 60 days.
## MCP queries
The [MCP server](/agents) lets AI agents query your analytics. The monthly quota only counts **analytics queries**, the ones that hit your event data: funnel overviews, trends, step timing, segment breakdowns, user timelines, ingest health, dashboard data, and the pageview summary, timeseries, and breakdown tools.
Not counted against the quota:
* Management tools: listing workspaces and projects, reading, creating, or editing funnels and dashboards.
* Cached results. Identical queries are cached for 15 minutes and served for free.
A few guardrails apply per query:
* A single analytics query can span at most **90 days**. Agents are told to split longer windows into separate queries.
* Queries cannot reach past your plan's data retention.
* Locked funnels can be listed and read, but their analytics are unavailable until they're unlocked.
* The pageview tools need a plan with a pageview allowance. On the free plan they return `PAGEVIEWS_NOT_INCLUDED` without consuming quota.
* A burst limit of 60 MCP requests per minute protects the endpoint. Hitting it returns a retry hint and does not consume quota.
The quota resets at the start of each billing cycle (calendar month, UTC, on the Free plan). When it's exhausted, analytics queries return a clear error with the reset date and an upgrade link, and agents are instructed not to retry until then.
## Fixed limits on every plan
These limits are part of the product and don't change with the plan:
| Limit | Value |
| - | - |
| Steps per funnel | 20 |
| Conditions per funnel step | 10 |
| Dashboards per project | 20 |
| Blocks per dashboard | 24 |
| Saved views per funnel or dashboard | 15 |
| Events per request | 100 |
| Properties per event | 20 top-level keys |
| Request body size | 51,200 bytes (50 KiB) |
| Event name length | 100 characters |
| Allowed origins per project | 50 |
| Path normalization rules per site | 20 |
| Kept query parameters per site | 10 |
## Billing
* Your plan is attached to the workspace. See [Billing](/help/billing) for how to find your current subscription, manage or cancel it, and download invoices.
* No card is on file until you choose a paid plan. Free is the default state, not a lapsed subscription.
* **Upgrades** take effect right away: higher rate limits, higher event and pageview quotas, a longer retention window, and any history still inside the 60-day free-plan window reappears.
* **Downgrades and cancellations** land the workspace on the Free plan. Your data and configuration are kept: funnels beyond the free limit are locked rather than deleted, extra teammates keep their membership but lose access, and retention shrinks as described above.
Not sure which plan fits? Start with the events per month number. It's the
limit teams hit first, and the Usage page shows your real volume after a
week of tracking on the Free plan.
# Project settings
Source: https://docs.wendung.app/help/settings
Manage your project details, control which domains can send events, and handle API keys.
The Settings page holds everything about the project itself: its name and logo, the origins that are allowed to send events, and the API keys your SDK uses.
Settings are only visible to workspace owners and admins.
## Project details
Update the project's logo, name, and description. The logo is used as the project identifier in your dashboard, the name appears in navigation, reports, and project switchers, and the description helps your team understand what the project tracks.
## Allowed origins
Allowed origins control which domains can send events to this project. A new project starts with an empty list and rejects every event until you add an origin.
Click **Add origin** and enter one exact http or https origin, like `https://app.example.com`. You can add up to 50.
Origins match exactly, including the protocol and subdomain, so
`https://example.com` and `https://app.example.com` are two separate entries.
Add every domain your app runs on, including staging and preview domains you
want to track.
If events stop arriving after a deploy or a domain change, this list is the first thing to check. Rejected requests show up on the [Events page](/help/events) with their origin, so you can see exactly which domain was turned away.
## Dev mode
Requests from `http://localhost:3000` are rejected like every other origin you haven't added. Dev mode adds a temporary exception for local addresses, so you can test without putting localhost on the list for good.
Turn it on with the **Dev mode** switch at the top of the Allowed origins section.
While it's on, the project also accepts `localhost`, any `*.localhost` subdomain, `127.0.0.0/8`, and `[::1]`, on any port, over http or https.
Everything else still has to be on the allowed origins list. Private network addresses like `192.168.1.42` are not covered, so a phone on your Wi-Fi hitting your dev server is still rejected. Requests without an `Origin` header, such as curl or a server-side script, are always rejected.
Dev mode switches itself off 24 hours after you turn it on. **Extend to 24 hours** restarts the clock, and the switch turns it off immediately. While it's on, a warning strip sits at the top of every page in the project.
Your publishable key ships in your browser bundle, so anyone who has it can send events with whatever `Origin` header they like. Dev mode widens that opening for a day. Turn it off when you're done testing instead of leaving it running.
Turning Dev mode on or off can take a few minutes to reach the ingest endpoint.
## API keys
API keys authenticate your SDK against the project. Every project starts with a **Default** key, and you can create more with **Add API Key**, for example one key per environment.
Each row shows the key's name, the masked key with reveal and copy buttons, whether it's active, and when it was last used. The row menu lets you edit or delete a key.
Deleting a key immediately stops all SDKs that use it from delivering events.
Check the **Last used** column first: a key that was used recently is still
in production somewhere.
## Danger zone
Two irreversible actions live at the bottom of the page, both behind a confirmation dialog:
* **Truncate project data** permanently deletes all analytics data. The project and its settings, including funnels, dashboards, origins, and API keys, are preserved. Useful when you want to clear out test data before going live.
* **Delete project** permanently deletes the project and all associated data. You have to type the project name to confirm.
# Site details
Source: https://docs.wendung.app/help/site-details
Read a site's traffic: visitors, sessions, pages, sources, locations, and devices, with filters and comparison.
The site page is the web analytics dashboard for one hostname, or for all of them when you open **All sites**. The breadcrumb at the top switches between sites, and the green badge next to the name counts visitors active in the last five minutes.
## Metrics and chart
The rail shows six metrics for the selected range. Click one to chart it below. Pageviews include aggregate and consented traffic. All visitor, session, and engagement metrics cover consented traffic only. The question-mark icon beside **Pageviews** explains this difference.
| Metric | What it counts |
| - | - |
| **Unique visitors** | Distinct visitors, by the anonymous ID the SDK keeps in their browser. |
| **Pageviews** | Every pageview, including repeat views of the same page. |
| **Sessions** | Visits, closed after 30 minutes without activity. |
| **Views per session** | Consented pageviews divided by sessions. |
| **Bounce rate** | Share of sessions with a single pageview. |
| **Session duration** | Average time between a session's first and last pageview. |
Views per session, bounce rate, and session duration come from session data that is rebuilt once an hour, so they can trail visitors and pageviews by up to an hour. With **Compare to previous period** on, each metric gets a badge with its change: green when the move is good, red when it is not (a rising bounce rate is red), and a gray **New** when the previous period had no data. The chart adds a dashed line for the previous range. Ranges up to two days are charted per hour; longer ranges per day, week, or month.
## Panels
Four panels rank the traffic. Each has tabs, an indicator in its header naming the number in the rows (pageviews, or sessions for entry and exit pages), and a **View all** button that opens the full list with a search box.
| Panel | Tabs |
| - | - |
| **Pages** | Top pages, Entry pages, Exit pages. Entry and exit rows also show bounce rate and average session duration. |
| **Sources** | Sources (referrer domains), Campaigns (UTM campaign, source, or medium, taken from the `utm_*` parameters on the link that started the session), Type (direct, search, social, email, referral, internal). |
| **Locations** | Countries, Cities. |
| **Devices** | Device type, Browser, OS. |
Hover a row to reveal two actions: copy the value, and filter by it. Clicking the row does the same as the filter action. A row that is currently a filter shows a remove-filter action instead, and clicking it clears the filter.
Paths in the Pages panel are normalized, so `/users/123` and `/users/456` appear as one row `/users/:id`. See [site settings](/help/site-settings) to change how paths are collapsed.
## Filters and date range
The filter bar accepts every dimension the panels show: hostname (on **All sites**), page, source, channel type, UTM fields, country, city, device type, browser, and OS. Each filter can be **is** or **is not**, with several values. Filters, the date range, and the selected metric are part of the URL, so a view can be shared as a link.
The date range picker has the presets from the rest of the app plus **Today** and **Last 24 hours**, which chart per hour. Presets beyond your plan's [data retention](/help/plans#data-retention) are locked.
## Exporting
**Export** downloads a CSV of the summary metrics, the top pages, or the sources, with the active filters and range applied.
# Site settings
Source: https://docs.wendung.app/help/site-settings
Choose the hostname, collapse dynamic paths with normalization rules, and decide which query parameters to keep.
A site's settings control how its URLs are stored. Open them from the site's row on the [Sites page](/help/sites) or from the site page's menu.
## Hostname
The hostname comes from the project's [allowed origins](/help/settings#allowed-origins). A site scopes reports to one hostname; all sites share the same pageview stream, so changing the hostname does not move or delete data.
## Path normalization
Each rule has a **pattern** (a regular expression) and a **replacement**. Rules are tested against one path segment at a time, in the order shown. The first rule that matches a segment wins, and that segment skips the built-in collapsing of numeric IDs and UUIDs. Drag the handle at the start of a row to reorder rules. A site can have up to 20.
Rules apply to pageviews collected after you save. Data that was already stored keeps the paths it was recorded with.
## Query parameters
Query strings are dropped at ingest, so `/docs?ref=hn&session=abc` is stored as `/docs`. Add a parameter name under **Keep parameter** to store it with the path; up to 10 per site. `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, and `utm_content` are always captured as campaign fields and do not need to be listed.
## Preview
Paste a full URL or a bare path into **Sample URL** to see what the current form would store, using the same normalizer as data collection. The preview reflects unsaved rules, so you can iterate before you click **Save**.
## Deleting a site
Delete a site from its row menu on the [Sites page](/help/sites). That removes the site's settings and its saved view; collected pageviews are kept and stay visible under **All sites**. Registering the hostname again starts with empty rules.
# Sites
Source: https://docs.wendung.app/help/sites
Register the hostnames you want web analytics for and see their traffic at a glance.
The Sites page lists every hostname you have registered for web analytics in this project, with live and 24-hour numbers for each. It is where you add a site and where you go to open one.
## The sites list
Each row shows the hostname, the visitors active in the last five minutes, the unique visitors in the last 24 hours, and a 24-hour sparkline. Click a row to open the [site details](/help/site-details).
The **All sites** row at the top combines every hostname the project has received pageviews from, registered or not. It is the place to look when your app runs on several hostnames and you want one number.
The menu at the end of a row lets you **Pin** or **Unpin** the site on the [Overview](/help/overview#web-tab), open its **Settings**, or **Delete** it. Deleting a site removes its settings and its saved filter; the pageviews it collected stay and remain visible under **All sites**.
## Adding a site
Click **Add site**. The hostname picker lists the project's [allowed origins](/help/settings#allowed-origins), so add the origin there first if it is missing. A site only needs a hostname to start; path rules and the query parameter allowlist are optional and can be changed later in [site settings](/help/site-settings).
Registering a site does not start or move any data. The SDK sends pageviews for every hostname once `trackPageviews` is on; a site is a saved view onto that stream.
## Unregistered hostnames
When the project receives pageviews from a hostname without a site, the page lists it under the table with a shortcut to register it. That is usually a preview deployment or a staging domain.
## Pageviews are not showing
* Pageview tracking is off. Set `trackPageviews: true` for pageviews with granted consent, or `'auto'` to also collect aggregate pageviews while pending. Denied consent stops both. See the [setup guide](/guides/web-analytics).
* The workspace is on the free plan, which has no pageview allowance. The page shows an upgrade prompt in that case.
* The monthly pageview allowance is used up. New pageviews are dropped until the cycle resets or you upgrade; see [Plans and limits](/help/plans#monthly-pageviews).
* The hostname is not on the allowed origins list, so the ingest endpoint rejects the whole request. Check the [Events page](/help/events) for `403` rejections.
* Only bounce rate, session duration, and views per session are empty. Those come from session data that is rebuilt once an hour; visitors and pageviews update right away.
# Users
Source: https://docs.wendung.app/help/users
Browse every identity in your project and drill into an individual user's sessions and steps.
The Users page lists every identity Wendung has seen in the selected period, both identified users and anonymous sessions. Use it when a funnel number looks off and you want to see the actual people behind it. Pageviews are counted in [web analytics](/help/sites) and stay out of this page: visitors who only produced pageviews are not listed, and a user's journey shows their steps only.
## The users table
Each row shows the identity's ID, the last step they performed, how many unique steps they've completed, their country and device type, and when they were first and last seen. All columns are sortable, and the search box finds users by ID.
The toolbar has the same filter bar and date range picker as the rest of the app. Filters cover **Last step**, **Country**, **Device type**, **Browser**, **OS**, **Plan**, **Source**, plus custom user traits and event properties.
## User details
Click a row to open the user details panel.
The panel shows:
* **User data**: the ID (with a copy button), country, and device type
* **Attributes**: last step, first seen, last seen, and unique step count
* **Journey**: every session, with its date, duration, event count, device, browser, and the page it started on. Each step in the session is listed in order with timestamps and the time elapsed between them.
Click a step in the journey to drill into its details, including the event properties that were attached.
The Recent identities card on the Overview page and the drop-off rows on a
funnel link straight into this view, so you can go from an aggregate number
to a concrete user journey in two clicks.
# Introduction
Source: https://docs.wendung.app/introduction
What Wendung is, what the SDK does, and how events and pageviews flow from your app to the dashboard.
Wendung is funnel and web analytics from one browser SDK. You instrument steps with `@wendung/sdk` and the [dashboard](https://dashboard.wendung.app) turns them into funnels, trends, segments, and per-user timelines. Turn on pageview tracking and the same SDK feeds web analytics for your sites: visitors, sessions, pages, sources, locations, and devices.
## What the SDK does
* **Tracks steps.** `step(name, properties?)` queues a named, timestamped event.
* **Identifies users.** `identify(userId, traits?)` attaches subsequent events to a user.
* **Tracks pageviews.** `trackPageviews: true` records page loads and client-side navigation with granted consent. Use `'auto'` to also count aggregate pageviews while consent is pending. Register the hostname as a site and the dashboard reports on it.
* **Batches and retries.** Events flush every 5 seconds or when the queue reaches 50 events (both configurable). Server errors and network failures are retried.
* **Runs in the browser.** The package has no import-time side effects, but call `init()` and tracking methods from client code. Sites without a build step load the same SDK from `cdn.wendung.app` with one [script tag](/guides/script-tag).
## How data flows
1. `init()` configures the tracker and starts the flush timer.
2. Each `step()` call, and each pageview when tracking is on, snapshots the current identity, session ID, and page context, then queues the event in memory (capacity 1000).
3. Batches of up to 100 events are POSTed to `https://ingest.wendung.app/v1/events` with your publishable key in the `X-API-Key` header.
4. On page hide, the SDK drains the whole queue with `fetch` requests using `keepalive: true`, so delivery survives the tab closing.
## Next steps
Initialize the SDK and send your first event in under five minutes.
Learn how events are structured, queued, and delivered.
What a pageview carries and how sessions and normalized paths are derived.
# Quickstart
Source: https://docs.wendung.app/quickstart
Prepare your project, initialize the SDK with your consent settings, track your first funnel step, and optionally enable pageviews.
Install the SDK and track your first funnel step. Add pageview tracking if you also want web analytics.
## Before you start
* Create a workspace and project in the [dashboard](https://dashboard.wendung.app), then copy the project's publishable key (`pk_...`) from [Settings → API Keys](/help/settings#api-keys).
* Add your production origin under [Settings → Allowed origins](/help/settings#allowed-origins). For local testing, enable [Dev mode](/help/settings#dev-mode) for 24 hours. A new project rejects every origin with `403` until you allow one, including localhost.
* Choose how your app supplies the visitor's [analytics consent](/guides/consent). Pageviews are optional and need a plan with a [pageview allowance](/help/plans#monthly-pageviews); the free plan has none.
## Install the SDK
Install `@wendung/sdk` from npm using your preferred package manager.
```bash npm theme={null}
npm install @wendung/sdk
```
```bash yarn theme={null}
yarn add @wendung/sdk
```
```bash pnpm theme={null}
pnpm add @wendung/sdk
```
No build step? Follow the [script tag guide](/guides/script-tag) instead. The tag initializes the SDK from its attributes, including consent and pageview settings, so skip the module initialization below.
## Initialize the SDK
Import `Wendung` and call `init()` once when your application boots in the browser. Only `apiKey` is required. Keep the optional settings in this same call:
```ts theme={null}
import { Wendung } from '@wendung/sdk'
Wendung.init({
apiKey: 'pk_your_publishable_key',
consent: 'pending', // Use the saved visitor choice when available.
trackPageviews: false, // Optional: true or 'auto' for web analytics.
debug: false, // Optional: true during development.
})
```
`init()` is browser-only: call it and all tracking methods from client-side code. In Next.js, use a Client Component. See the [Next.js guide](/guides/nextjs) for the recommended `` pattern.
This example sends nothing while consent is pending. Connect your consent manager to [`setConsent()`](/api-reference/set-consent) to apply `granted` or `denied`, and pass its saved choice to `init()` on later loads. The SDK does not store the choice. If you omit `consent`, it defaults to `granted` and full analytics uses browser identifiers.
The `identify()` and `step()` examples below require granted consent. Calls made while pending are dropped, with no replay; identify an already signed-in user again after consent is granted. See the [consent guide](/guides/consent) for the complete wiring.
Set `debug: true` in the same configuration during development to log SDK activity. Warnings are logged regardless of this setting.
## Identify the user
Once the user is known, usually after login, call `identify()` to attach all subsequent events to them. The traits you pass are included with every event that follows.
```ts theme={null}
Wendung.identify('user_123', {
email: 'alice@example.com',
plan: 'pro',
})
```
The identity is saved in the browser and restored by `init()`, so a reload keeps the user identified. Each `identify()` call replaces it wholesale, traits included, so pass the full trait set every time. Call `reset()` on logout to clear it.
## Track your first funnel step
Call `step()` with a step name (1–100 characters, matching a step in one of your funnels) and an optional properties object. The event is queued immediately and sent with the next flush.
```ts theme={null}
Wendung.step('signup_completed', {
plan: 'pro',
source: 'google_ads',
})
```
## Optional: turn on pageview tracking
Funnels come from the steps you name. Web analytics comes from pageviews. Choose a `trackPageviews` value in your existing initialization above:
* `true` records full pageviews only after consent is granted.
* `'auto'` records aggregate pageviews while consent is pending, then full pageviews after consent is granted. Aggregate pageviews contain no visitor or session identifiers.
Denied consent stops collection in either mode. When collection is active, the SDK records the initial page and client-side navigation. Open **Sites** in the dashboard and register your hostname for site reports. The [web analytics guide](/guides/web-analytics) covers path rules and the rest.
## Flushing happens automatically
You don't need to manage flushing yourself. The SDK sends queued events:
* Every 5 seconds, on a timer
* As soon as the queue hits the batch size (default 50 events)
* On page hide, draining the whole queue with `fetch` and `keepalive: true` to attempt delivery during unload
If you need a send attempt at a specific moment (for example, right before a hard navigation in a custom flow), call `await Wendung.flush()`. It sends at most one batch per call and never rejects.
## Optional: let an agent add the SDK
Drop this prompt into your AI coding agent and let it guide you through the setup:
```text Prompt theme={null}
Read https://docs.wendung.app/setup.md and follow it to set up Wendung in this project.
```
To query your analytics from an agent, connect the MCP servers through [Agent setup](/agents). That connection is separate from adding the SDK to your app.
## What's next
Now that events are flowing, head back to the dashboard. Create a funnel from the step names you track, and open your site under **Sites** for traffic.
Turn the step names you're tracking into a funnel in the dashboard.
Register your site, clean up paths, and read the site dashboard.
The recommended setup pattern for App Router and Pages Router.