# Browser

> Install @sypnia/browser with a package manager or one script tag, every option of init with its type and default, what is captured without any code, and the few functions you call yourself.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service). Status: at launch.  
Source: https://docs.sypnia.com/sdks/browser/

This page is for whoever adds Sypnia to a web app. `@sypnia/browser` works in any app that runs in a browser: React, Vue, Svelte, plain HTML, and mobile apps built as web views. It is MIT-licensed and identical for the open-source engine and for Sypnia Cloud. Only two things differ: where it sends, and where the key comes from.

**At the end you will have:** errors, session replay, page performance, slow and failing API calls, and rage and dead clicks arriving from your app, with nothing a person types ever leaving their browser.

## Install

**npm**

```bash
npm install @sypnia/browser
```

```js
import { init } from '@sypnia/browser';

init({ project: 'YOUR_PROJECT_KEY' });
```

**pnpm**

```bash
pnpm add @sypnia/browser
```

```js
import { init } from '@sypnia/browser';

init({ project: 'YOUR_PROJECT_KEY' });
```

**yarn**

```bash
yarn add @sypnia/browser
```

```js
import { init } from '@sypnia/browser';

init({ project: 'YOUR_PROJECT_KEY' });
```

**bun**

```bash
bun add @sypnia/browser
```

```js
import { init } from '@sypnia/browser';

init({ project: 'YOUR_PROJECT_KEY' });
```

**script tag**

```html
<script async
  src="https://ingest.sypnia.com/v1/sdk.js"
  data-project="YOUR_PROJECT_KEY"></script>
```

No build step and no `init` call: paste it before `</head>`. The tag starts Sypnia with the key in `data-project`.

Replace `YOUR_PROJECT_KEY` with your project's ingest key. It starts with `spk_`, it is public, and it can only send data.

**Sypnia Cloud**

The key is on your project's page in `app.sypnia.com`. You do not set an address: the SDK sends to `https://ingest.sypnia.com`.

`src/main.ts`

```ts
import { init } from '@sypnia/browser';

init({
  project: 'spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e',
  environment: location.hostname === 'shop.example' ? 'production' : 'development',
  release: '4f2a91c',
});
```

**Self-hosted**

Create the key with `sypnia project create` or the [API](https://docs.sypnia.com/api/projects-keys-and-tokens), and point the SDK at your engine's base URL with `endpoint`.

`src/main.ts`

```ts
import { init } from '@sypnia/browser';

init({
  project: 'spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e',
  endpoint: 'https://sypnia.example.com',
  environment: location.hostname === 'shop.example' ? 'production' : 'development',
  release: '4f2a91c',
});
```

Call `init` once, as early as your app starts, before it renders. A second call does nothing.

### With one script tag, for apps without a build step

The engine serves the SDK itself, so there is nothing to install.

**Sypnia Cloud**

`index.html`

```html
<script async src="https://ingest.sypnia.com/v1/sdk.js" data-project="spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e" data-release="4f2a91c"></script>
```

**Self-hosted**

`index.html`

```html
<script async src="https://sypnia.example.com/v1/sdk.js" data-project="spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e" data-endpoint="https://sypnia.example.com" data-release="4f2a91c"></script>
```

Paste it before `</head>`. The tag starts Sypnia by itself, with these attributes:

| Attribute          | Same as the option | Required         |
| ------------------ | ------------------ | ---------------- |
| `data-project`     | `project`          | yes              |
| `data-endpoint`    | `endpoint`         | self-hosted only |
| `data-environment` | `environment`      | no               |
| `data-release`     | `release`          | no               |

The script puts the same functions on `window.sypnia` and then fires the event `sypnia:ready` on `window`. To use any other option, leave `data-project` out and call `init` yourself:

`index.html`

```html
<script async src="https://ingest.sypnia.com/v1/sdk.js"></script>
<script>
  window.addEventListener('sypnia:ready', () => {
    sypnia.init({ project: 'spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e', maskAllText: true });
  });
</script>
```

Errors thrown before the script has loaded are not captured. That is the price of `async`; remove `async` if you need the very first script of the page covered.

## Check that it works

1. Open your app and click something.
2. Open the browser's developer tools, tab **Network**, and filter by `ingest`.
3. Within 10 seconds you see a `POST` to `…/v1/ingest/events`, answered `200` with a body like `{"accepted": 4, "dropped": 0}`.

To read what is being sent, set `debug: true`: the SDK prints every event to the console before sending it. Bodies above 2,048 characters are gzipped, so the Network tab shows them as binary; the console shows them as they are. The full list of fields is the [event schema](https://docs.sypnia.com/reference/event-schema).

## What is captured without any code

| What               | How                                                                                                                                                                                          | Event                     |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
| Sessions           | One per visit, shared by every tab, ended by 30 minutes without activity.                                                                                                                    | `session_start`           |
| Pages              | Page loads and navigations inside the app, time on page and scroll depth.                                                                                                                    | `page_view`, `page_leave` |
| Clicks             | Every click, described in words: the control's label, its kind and where it is. Never a field's value.                                                                                       | `click`                   |
| Rage clicks        | 3 clicks or more within 30 px and 1 second of each other.                                                                                                                                    | `rage_click`              |
| Dead clicks        | A click on something clickable, after which nothing happens for 1 second.                                                                                                                    | `dead_click`              |
| Errors             | Uncaught errors and unhandled promise rejections, with their stack.                                                                                                                          | `error`                   |
| API calls          | `fetch` and `XMLHttpRequest` calls to your own origin: method, route, status, duration. For a failed call, the error code and the start of the error message of a JSON answer. Never a body. | `request`                 |
| Performance        | LCP, INP, CLS and TTFB of each page, with the element behind each one.                                                                                                                       | `vital`                   |
| Form failures      | A form the browser refused to submit, with the field's label and the reason.                                                                                                                 | `form_invalid`            |
| Replay             | The session as the person saw it, for every session where something goes wrong and for a share of the rest.                                                                                  | uploaded apart            |
| Click-map pictures | A masked snapshot of a page, at most one per route and five per session, for half of the sessions.                                                                                           | uploaded apart            |

What each rule means for the reader of a problem is in [Events](https://docs.sypnia.com/concepts/events), [Rage and dead clicks](https://docs.sypnia.com/concepts/rage-and-dead-clicks) and [Performance](https://docs.sypnia.com/concepts/performance).

### Noise the SDK leaves out

- Errors thrown by browser extensions, and by wallet or web-view code injected into the page.
- Errors whose stack lies entirely in scripts from other origins. Tell the SDK about your own CDN with `appFrames`.
- `Script error.` without detail, and the `ResizeObserver loop` notice.
- The same error again within 5 seconds, and more than 20 errors in a minute.

### What it does not do

It sets no cookies. It reads no typed value. It does not patch `console`. It keeps two ids in `localStorage` (`sypnia:session`, `sypnia:device`), one replay decision (`sypnia:replay`) and, if someone opts out, `sypnia:off`. Every entry point is wrapped so that a failure inside the SDK never reaches your app.

## `init(options)`

```ts
function init(options: InitOptions): void
```

| Option                         | Type                                                | Default                       | What it does                                                                                                                                                                                                                                                               |
| ------------------------------ | --------------------------------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `project`                      | `string`                                            | required                      | The project's ingest key, `spk_…`. Without it the SDK does nothing and prints one warning.                                                                                                                                                                                 |
| `endpoint`                     | `string`                                            | `'https://ingest.sypnia.com'` | Where to send. A self-hosted engine's base URL, or a path on your own domain that you proxy to it (see [Troubleshooting](https://docs.sypnia.com/sdks/troubleshooting)).                                                                                                   |
| `environment`                  | `string`, 1 to 40 characters                        | `'production'`                | The environment. Alerts and the daily summary only cover `production`.                                                                                                                                                                                                     |
| `release`                      | `string`, up to 40 characters                       | none                          | The release: use the short git commit. It must be the same string you upload source maps for.                                                                                                                                                                              |
| `enabled`                      | `boolean`                                           | `true`                        | `false` turns the SDK into a no-op. Use it in tests.                                                                                                                                                                                                                       |
| `debug`                        | `boolean`                                           | `false`                       | Prints every event, and every decision not to send one, to the console.                                                                                                                                                                                                    |
| `ignoreRoutes`                 | `(string \| RegExp)[]`                              | `[]`                          | Paths where the SDK captures nothing at all. A string matches the path itself and everything under it: `'/admin'` covers `/admin/users`.                                                                                                                                   |
| `routeFor`                     | `(pathname: string) => string`                      | the built-in rule             | Your own way to turn a path into a route. The built-in rule replaces segments that are all digits, a UUID, 16 or more hex characters, a token of 20 characters or more with a digit, or that contain `%`, by `:id`.                                                        |
| `hashRouting`                  | `boolean`                                           | `false`                       | `true` treats the hash as the path, for apps that route with `#/checkout`.                                                                                                                                                                                                 |
| `capture.errors`               | `boolean`                                           | `true`                        | Uncaught errors and unhandled rejections. `reportError` works either way.                                                                                                                                                                                                  |
| `capture.clicks`               | `boolean`                                           | `true`                        | Clicks, rage clicks and dead clicks.                                                                                                                                                                                                                                       |
| `capture.requests`             | `boolean`                                           | `true`                        | API calls, and the trace headers on them.                                                                                                                                                                                                                                  |
| `capture.requestFailureDetail` | `boolean`                                           | `true`                        | Reads `code` and the message from the JSON answer of a failed call (status 400 and above). `false` records the status only.                                                                                                                                                |
| `capture.vitals`               | `boolean`                                           | `true`                        | LCP, INP, CLS, TTFB and FCP.                                                                                                                                                                                                                                               |
| `capture.forms`                | `boolean`                                           | `true`                        | Form-validation failures.                                                                                                                                                                                                                                                  |
| `traceTargets`                 | `(string \| RegExp)[]`                              | `[]`                          | Addresses outside your origin whose calls are recorded **and** receive the trace headers. A string matches the start of the URL. Your own origin is always included.                                                                                                       |
| `recordTargets`                | `(string \| RegExp)[]`                              | `[]`                          | Addresses outside your origin whose calls are recorded **without** adding any header. For APIs you do not control.                                                                                                                                                         |
| `ignoreRequests`               | `(string \| RegExp)[]`                              | `[]`                          | Calls that are never recorded. Calls to Sypnia itself never are.                                                                                                                                                                                                           |
| `ignoreErrors`                 | `(string \| RegExp)[]`                              | `[]`                          | Errors whose message matches are not sent. A string matches anywhere in the message.                                                                                                                                                                                       |
| `appFrames`                    | `(string \| RegExp)[]`                              | `[]`                          | Script addresses that are your code although they are served from another origin, such as your CDN.                                                                                                                                                                        |
| `maskAllText`                  | `boolean`                                           | `false`                       | Masks every text of every page in replays and snapshots, and sends no click label, context or field name. See [Privacy and masking](https://docs.sypnia.com/sdks/privacy-and-masking).                                                                                     |
| `maskSelector`                 | `string` (CSS selector)                             | none                          | Elements to mask, on top of `[data-sypnia-mask]`.                                                                                                                                                                                                                          |
| `blockSelector`                | `string` (CSS selector)                             | none                          | Elements to leave out of replays, on top of `[data-sypnia-block]`, `iframe` and `video`.                                                                                                                                                                                   |
| `replay`                       | `false \| { blockedRoutes?: (string \| RegExp)[] }` | `{}`                          | `false` never loads the recorder. `blockedRoutes` are routes where nothing is recorded, on top of the project's own list. How many sessions are recorded is a project setting, not an option: see [Sampling and quotas](https://docs.sypnia.com/sdks/sampling-and-quotas). |
| `snapshots`                    | `boolean`                                           | `true`                        | Page snapshots for click maps.                                                                                                                                                                                                                                             |
| `beforeSend`                   | `(event) => event \| null`                          | none                          | Called with each event before it is queued. Return it, changed or not, to send it; return `null` to drop it. Not called for replay content.                                                                                                                                |

Limits that are not options: a batch every 10 seconds or at 50 events, at most 200 events and 40,800 characters per batch, a queue of 500 events in memory, a session ends after 30 minutes without activity. They are listed in the [event schema](https://docs.sypnia.com/reference/event-schema#limits-and-constants).

## The functions you call

### `identify(who)`

Says who the person is. Call it when someone signs in and when your app loads with someone already signed in; call `identify(null)` when they sign out.

`src/auth.ts`

```ts
import { identify } from '@sypnia/browser';

identify({
  person: { id: 'u_1042', name: 'Ada Park', email: 'ada@example.com' },
  account: { id: 'acc_77', name: 'Corner Café' },
});
```

Only `person.id` is required. Names and e-mails are personal data and are stored only if you send them. The rules are in [Identifying people](https://docs.sypnia.com/sdks/identifying-people).

### `track(name, props?)`

Sends a custom event: something that matters in your app and that Sypnia cannot see by itself.

`src/checkout/coupon.ts`

```ts
import { track } from '@sypnia/browser';

track('coupon_applied', { code: 'SPRING10', discount_cents: 640, first_order: false });
```

|         | Limit                                                                                                                                                           |
| ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`  | 1 to 80 characters                                                                                                                                              |
| `props` | Up to 20. A name has at most 40 characters. A value is a string of at most 200 characters, a finite number, a boolean or `null`. Objects and lists are removed. |

Custom events appear in the session's timeline. They do not count towards a plan. Never put what a person typed in a property.

### `reportError(error, info?)`

Reports an error your code caught. Errors nobody catches are reported without it.

`src/checkout/checkout.tsx`

```ts
import { reportError } from '@sypnia/browser';

try {
  await confirmPayment(cart);
} catch (error) {
  reportError(error);
  showMessage('We could not take the payment. Nothing was charged.');
}
```

| `info`   | Type                           | Default    | Meaning                                             |
| -------- | ------------------------------ | ---------- | --------------------------------------------------- |
| `source` | `'manual' \| 'boundary'`       | `'manual'` | Use `'boundary'` from a framework's error boundary. |
| `digest` | `string`, up to 100 characters | none       | The id your framework gave the error, if any.       |

Anything that is not an `Error` is turned into one, so there is always a message. The limits on rate and repeats above apply here too.

### The rest

| Function                         | What it does                                                                                                                                           |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `flush(): Promise<void>`         | Sends what is waiting now. The SDK already does this when the tab is hidden or closed.                                                                 |
| `getSessionId(): string \| null` | The current session's id, 32 hex characters, or `null` when there is none. Put it in a support request to find the session later.                      |
| `optOut(): void`                 | Stops everything for this browser and remembers it (`localStorage`, `sypnia:off`). Use it for a person who refuses analytics, and in end-to-end tests. |
| `optIn(): void`                  | Undoes `optOut`.                                                                                                                                       |

## Releases

Set `release` to the short git commit of the build. Most bundlers can inject it:

`vite.config.ts`

```ts
import { execSync } from 'node:child_process';
import { defineConfig } from 'vite';

export default defineConfig({
  build: { sourcemap: 'hidden' },
  define: {
    __RELEASE__: JSON.stringify(execSync('git rev-parse --short HEAD').toString().trim()),
  },
});
```

`src/main.ts`

```ts
declare const __RELEASE__: string;

init({ project: 'spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e', release: __RELEASE__ });
```

With a release, a problem can say «since yesterday's change». With that release's source maps, its stack shows `src/checkout/checkout.tsx:142` instead of `checkout-3f9c.js:1:48211`. Upload them in your build: [Source maps in CI](https://docs.sypnia.com/guides/source-maps-in-ci).

## Single-page apps

Nothing to do. The SDK follows the History API, so every navigation of a client-side router is a page view, and INP and CLS are measured per page. A change of query or hash alone is not a page view; set `hashRouting: true` if your router lives in the hash.

## Calls to your API, and traces

Each recorded call gets a trace id. On calls to your own origin, and to `traceTargets`, the SDK adds two request headers:

| Header             | Value                                        | For                                   |
| ------------------ | -------------------------------------------- | ------------------------------------- |
| `traceparent`      | `00-<trace id>-<span id>-01`, the W3C format | Your server continues the same trace. |
| `x-sypnia-session` | The session id                               | The server's part joins the session.  |

Headers your code already set are never replaced. If your API lives on another origin, list it and allow the two headers in its CORS answer:

`src/main.ts`

```ts
init({
  project: 'spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e',
  traceTargets: ['https://api.shop.example'],
});
```

```http
Access-Control-Allow-Headers: content-type, authorization, traceparent, x-sypnia-session
```

The server side is in [Node](https://docs.sypnia.com/sdks/node), [Next.js](https://docs.sypnia.com/sdks/nextjs) and [OpenTelemetry](https://docs.sypnia.com/sdks/opentelemetry).

## Framework notes

The install is the same everywhere: `init` once, before the app renders. What differs is where errors that the framework catches are handed over.

**React**

React catches errors thrown while rendering. Report them from your error boundary:

`src/ErrorBoundary.tsx`

```tsx
import { Component, type ReactNode } from 'react';
import { reportError } from '@sypnia/browser';

export class ErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
  state = { failed: false };
  static getDerivedStateFromError() {
    return { failed: true };
  }
  componentDidCatch(error: Error) {
    reportError(error, { source: 'boundary' });
  }
  render() {
    return this.state.failed ? <p>Something went wrong. Reload the page.</p> : this.props.children;
  }
}
```

In React 19 you can instead pass `onCaughtError` and `onUncaughtError` to `createRoot` and call `reportError` there. For Next.js use [`@sypnia/next`](https://docs.sypnia.com/sdks/nextjs).

**Vue**

`src/main.ts`

```ts
import { createApp } from 'vue';
import { init, reportError } from '@sypnia/browser';
import App from './App.vue';

init({ project: 'spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e' });

const app = createApp(App);
app.config.errorHandler = (error) => {
  reportError(error, { source: 'boundary' });
  console.error(error);
};
app.mount('#app');
```

**Svelte**

In SvelteKit, start the SDK and hand over errors in the client hooks:

`src/hooks.client.ts`

```ts
import { init, reportError } from '@sypnia/browser';
import type { HandleClientError } from '@sveltejs/kit';

init({ project: 'spk_7d1f0c9e4b8a2f6d3c5e1a9b0f4d8c2e' });

export const handleError: HandleClientError = ({ error }) => {
  reportError(error, { source: 'boundary' });
};
```

In Svelte without SvelteKit, call `init` in `src/main.ts` before `mount`.

**Plain HTML**

Use the script tag above. Nothing else is needed: every page load is a page view, and uncaught errors are reported.

`checkout.html`

```html
<script>
  window.addEventListener('sypnia:ready', () => {
    sypnia.identify({ person: { id: 'u_1042' } });
  });
</script>
```

## Size

These are budgets the SDK commits to, checked in its build on every release:

| Part                                             | Budget              | When it loads                                                                                        |
| ------------------------------------------------ | ------------------- | ---------------------------------------------------------------------------------------------------- |
| The SDK itself (`@sypnia/browser`, and `sdk.js`) | under 20 kB gzipped | With your app.                                                                                       |
| The recorder, for replay and snapshots           | under 80 kB gzipped | Later, in its own file, when the browser is idle. Never with `replay: false` and `snapshots: false`. |

Starting the SDK does only cheap work before your app renders: it installs its listeners and sends the page view. Performance measurement and the recorder start when the browser is idle.

## Mobile apps

An app built as a web view (Capacitor, Cordova, a wrapped web app) works with this SDK as it is. Native iOS and Android SDKs are **\[Planned]**; see [Planned](https://docs.sypnia.com/reference/planned).

## Next
