# Ours Privacy Web SDK (client)

> Install the Ours Privacy Web SDK with a script tag or the npm package, track events with ours('track', ...), identify visitors with ours('identify', ...), and set init options.

Source: https://docs.oursprivacy.com/docs/web-sdk-javascript

Use this page to install the Ours Privacy Web SDK on your website, track events, identify visitors, and set init options.

---

## Install

### Script tag

Copy your snippet from the [Install Ours](https://app.oursprivacy.com/install) page: on your **Web SDK** row, select **Install**, then **Copy script**. The copied snippet already contains your token and, if you have one, your [custom domain](https://docs.oursprivacy.com/docs/custom-domains).

![The Install Ours page with a Web SDK row for the Northside Website, showing its allowed domains and an Install button](https://docs.oursprivacy.com/img/installation/installation-img-1.jpg)

Paste the snippet into the `<head>` of every page so events that happen while the page loads are captured. It looks like this, with your own token:

```html
<script>
  'use strict';
  (function () {
    var r = 'https://cdn.oursprivacy.com/main.js';
    function e() {
      var o;
      var _n = function n() {
        for (var _len = arguments.length, s = new Array(_len), _key = 0; _key < _len; _key++) {
          s[_key] = arguments[_key];
        }
        _n.queue.push(s);
      };
      ((_n.queue = ((o = window.ours) == null ? void 0 : o.queue) || []),
        (_n.version = '1.0'),
        (window.ours = _n),
        (window.ours_data = window.ours_data || {}),
        (window.oursLayer = window.oursLayer || []));
    }
    function t(n) {
      if (!window.ours) {
        e();
        var o = document.createElement('script');
        ((o.async = !0), (o.src = n));
        var s = document.getElementsByTagName('script')[0];
        s && s.parentNode && s.parentNode.insertBefore(o, s);
      }
    }
    t(r);
  })();
  ours('init', 'YOUR_TOKEN', { track_web_events: true, bot_detection: true });
</script>
```

The snippet turns on [automatic web events](#track-web-events-track_web_events) and [bot detection](https://docs.oursprivacy.com/docs/bot-detection). Add any other [init options](#init-options) to its `ours('init', ...)` call. Calls you make before the SDK finishes loading are queued and sent once it loads.

To install through Google Tag Manager instead, see [Install with Google Tag Manager](https://docs.oursprivacy.com/docs/gtm-install).

### npm package

For React, Vue, Next.js, and other bundled apps, install [@oursprivacy/cdp-sdk](https://www.npmjs.com/package/@oursprivacy/cdp-sdk). It includes TypeScript types.

```bash
npm install @oursprivacy/cdp-sdk
```

```javascript
import ours from '@oursprivacy/cdp-sdk';

ours.init('YOUR_TOKEN', { track_web_events: true, bot_detection: true });

ours.track('Purchase Completed', { value: 100 });
```

The package has the same methods and options as the script tag, called as `ours.track(...)` instead of `ours('track', ...)`. Call `init` in browser code (for example, in a client component or `useEffect`), not during server rendering. Call it before other methods: `identify` calls made earlier wait for `init`, and the rest throw until it runs.

### Initialize once

Call `init` once per page load, or once at startup in a single-page app; route changes don't need it. To change default properties after that, use the [update methods](#update-default-properties).

---

## Track events

```javascript
ours(
  'track',
  'Form Submitted',
  {
    // Event properties
    form_name: 'newsletter',
  },
  {
    // Visitor properties (optional)
    first_name: 'Jane',
    custom_properties: {
      plan: 'premium',
    },
  }
);
```

The arguments are the event name, event properties, and optional visitor properties. See [Visitor Properties](https://docs.oursprivacy.com/docs/visitor-properties-overview) for the visitor fields you can send.

---

## Identify visitors

Send what you know about a visitor, such as after they log in or submit a form:

```javascript
ours('identify', {
  email: 'user@example.com',
  external_id: 'user123',
  first_name: 'Jane',
  custom_properties: {
    plan: 'premium',
  },
});
```

`identify` updates the visitor's properties and records an `$identify` event. Send an `external_id` (your own stable user ID) or `email` so the same person is recognized across devices; see [Visitor Identity and Matching](https://docs.oursprivacy.com/docs/visitor-identity-and-matching). Use `custom_properties` for any visitor data that isn't a standard field.

> **Note:** On standard fields like `email` or `gclid`, `null` clears the stored value, while `undefined` and `""` leave it alone. Code like `ours('identify', { gclid: params.get('gclid') })` clears a stored `gclid` on any page without one. See [Data Types and Field Values](https://docs.oursprivacy.com/docs/data-types).

---

## Reset on logout

```javascript
// Start a new anonymous visitor
ours('reset');

// Or start a new visitor with an ID you choose
ours('reset', 'new_visitor_id');
```

`reset` gives the browser a new visitor and records a `$reset` event for it. Events sent before the reset stay with the previous visitor, and the new visitor starts without the previous visitor's stored properties or history. Data already collected is kept.

Default properties you set in `init` or with the [update methods](#update-default-properties) stay in place after a reset and go on the new visitor's events. If they describe the person who logged out, such as a plan or consent choice, update them when you reset.

Use it when someone logs out or switches accounts. To connect one person's devices, don't reset: identify them with the same `external_id` on each device.

---

## Update default properties

Change the [default properties](#default-event-properties-default_event_properties) you set in `init` at any time:

| Method                               | Updates                                          |
| ------------------------------------ | ------------------------------------------------ |
| `updateDefaultEventProperties`       | Properties added to every event                  |
| `updateDefaultUserCustomProperties`  | Visitor `custom_properties` added to every event |
| `updateDefaultUserConsentProperties` | Visitor `consent` values added to every event    |

```javascript
ours('updateDefaultUserConsentProperties', {
  analytics: true,
  marketing: false,
});
```

Each call merges into the current defaults (new values win for the same key) and applies to events tracked afterward. Properties passed on a single event override the defaults for that event.

---

## Read the visitor and session IDs

```javascript
const visitorId = ours.getVisitorId();
const sessionId = ours.getSessionId();
```

Both work the same way with the script tag and the npm package, once `init` has run. With the script tag, they're available after the SDK loads, so call them from a click handler or after page load rather than inline after the snippet.

Use them to [carry identity across your domains](#cross-domain-tracking) or to pass the visitor ID to another system.

---

## Init options

Pass these in the third argument of `ours('init', ...)`, or the second argument of `ours.init(...)` in the npm package:

```javascript
ours('init', 'YOUR_TOKEN', {
  track_web_events: true,
  enhanced_web_events: true,
  bot_detection: true,
  custom_domain: 'https://metrics.example.com',
  default_event_properties: { environment: 'production' },
  url_query_params_blocklist: ['token'],
});
```

| Option | What it does |
| --- | --- |
| `track_web_events` | Tracks page views, clicks, scrolls, forms, and more automatically. See [Track Web Events](#track-web-events-track_web_events). |
| `enhanced_web_events` | Adds link and click text to automatic events. Requires `track_web_events`. Off by default. |
| `bot_detection` | Collects the behavioral signals behind [Advanced Bot Detection](https://docs.oursprivacy.com/docs/bot-detection). Off by default; the dashboard snippet turns it on. |
| `custom_domain` | Sends events through your [custom domain](https://docs.oursprivacy.com/docs/custom-domains), so tracking runs first-party. |
| `user_id` | Sets the visitor ID to a value you choose (at least 3 characters), instead of a generated one. To identify a logged-in person, send `external_id` with [`identify`](#identify-visitors). |
| `default_event_properties` | Properties added to every event. See [Default Event Properties](#default-event-properties-default_event_properties). |
| `default_user_custom_properties` | Visitor `custom_properties` added to every event, for example a plan or segment you send to GA4 as user properties. |
| `default_user_consent_properties` | Visitor `consent` values added to every event. |
| `url_query_params_blocklist` | Query parameters to remove from captured URLs. See [URL Query Params Blocklist](#url-query-params-blocklist-url_query_params_blocklist). |
| `force_ipv4` | Sends events over IPv4. See [IPv4 Endpoints](#ipv4-endpoints-force_ipv4). |
| `session_replay` | Turns on [Session Replay](https://docs.oursprivacy.com/docs/session-replay/configuration) with your replay `token`, plus sampling, masking, and page options. |
| `experimentation` | Turns on [Experimentation](https://docs.oursprivacy.com/docs/experimentation/installation) with your experimentation `token`. Experiments use the Web SDK's visitor ID. |
| `cookie_names` | Renames the cookie and storage keys for the visitor ID (`device_id`) and SDK data (`sdk_data`), for example to use non-identifying names. |

### Track Web Events (`track_web_events`)

With `track_web_events: true`, the SDK tracks these events. Properties marked † need `enhanced_web_events` too.

| Event | When it fires | Properties |
| --- | --- | --- |
| `page_view` | On page load and on single-page app route changes. | `is_first_visit`, `is_new_session`, `is_spa_navigation` |
| `scroll` | Once per page, when the visitor scrolls 90% of the way down. | `percent_scrolled` |
| `click` | On a click on an outbound, `mailto:`, or `tel:` link. | `link_url`, `link_domain`, `protocol`, `outbound`, `click_text`† |
| `$link_click` | On a click on any link, internal or outbound. | `link_url`, `link_domain`, `link_id`, `link_classes`, `outbound`, `link_text`† |
| `file_download` | On a click on a link to a common file type (PDF, DOCX, XLSX, ZIP, MP4, and others). | `file_name`, `file_extension`, `link_url` |
| `form_start` | The first time a visitor focuses a field in a form. | `form_id`, `form_name`, `page_location` |
| `form_submit` | When a form is submitted. | `form_id`, `form_name`, `page_location` |
| `view_search_results` | When the URL has a search parameter (`q`, `s`, `search`, `query`, `keyword`, or `term`). | `search_term`, `search_parameter`, `page_location` |
| `user_engagement` | When the visitor leaves a page after interacting with it or staying at least 10 seconds. | `_et` (engagement time in milliseconds) |

An outbound link click fires both `click` and `$link_click`. Use `click` for outbound clicks only and `$link_click` for every link, and allow just the one you need on each destination.

Every automatic event also includes `is_engaged_session` (`1` or `0`), and `_et` once the visitor has interacted with the page.

### Default Event Properties (`default_event_properties`)

Add context such as environment or app version to every event:

```javascript
ours('init', 'YOUR_TOKEN', {
  default_event_properties: {
    environment: 'production',
    app_version: '1.0.0',
  },
});
```

Properties passed on a single event take precedence. To change the defaults later, use [`updateDefaultEventProperties`](#update-default-properties).

### URL Query Params Blocklist (`url_query_params_blocklist`)

Remove parameters such as tokens from the page URL and referrer before events are sent:

```javascript
ours('init', 'YOUR_TOKEN', {
  url_query_params_blocklist: ['token', 'access_token', 'code'],
});
```

Matching ignores case. The names are removed from the query string and from query-like hash fragments:

- `#access_token=abc&state=xyz` becomes `#state=xyz`
- `#/dashboard?token=abc&page=1` becomes `#/dashboard?page=1`
- `#!/page?token=abc&keep=1` becomes `#!/page?keep=1`

The blocklist applies to the captured page URL, referrer, and link URLs. Marketing parameters captured on their own, such as `utm_source`, `gclid`, and `fbclid`, are unchanged.

### IPv4 Endpoints (`force_ipv4`)

Some advertising platforms match more accurately when events arrive over IPv4. Set `force_ipv4: true` to send events through the Ours Privacy IPv4 endpoint:

```javascript
ours('init', 'YOUR_TOKEN', {
  force_ipv4: true,
});
```

Visitors on IPv6-only networks can't reach the IPv4 endpoint. Custom domains don't proxy it, so IPv4 traffic goes to the Ours Privacy host even when you set `custom_domain`.

---

## Cross-domain tracking

Cookies don't carry between separate domains. To keep one visitor and session across domains you own, add `ours_visitor_id` and `ours_session_id` to links between them:

```javascript
const url = `https://other-domain.com?ours_visitor_id=${ours.getVisitorId()}&ours_session_id=${ours.getSessionId()}`;
```

The Web SDK on the destination page adopts both IDs, so analytics and destinations see one continuous visit. See [Maintaining identity across your own domains](https://docs.oursprivacy.com/docs/visitor-identity-and-matching#maintaining-identity-across-your-own-domains).

---

## Troubleshooting

- **No events arriving:** Check that the snippet is in the `<head>` and your site's domain is in [Allowed Domains](https://docs.oursprivacy.com/docs/domain-allowlisting). Then follow [Tracking and Debugging Events](https://docs.oursprivacy.com/docs/tracking-and-debugging-events) to send a test event from your site.
- **`Ours SDK not initialized` error:** `getVisitorId`, `getSessionId`, or an npm method ran before `init`. Call `init` first.
- **Two visitors after logout and login:** That's `reset` working as intended. Identify the returning person with the same `external_id`.

---

## Next Steps

- [Visitor Identity and Matching](https://docs.oursprivacy.com/docs/visitor-identity-and-matching): how visitors are recognized across sessions and devices.
- [Visitor Properties](https://docs.oursprivacy.com/docs/visitor-properties-overview): the fields you can send with `identify` and `track`.
- [Custom Domains](https://docs.oursprivacy.com/docs/custom-domains): send events from your own domain.
- [Install with Google Tag Manager](https://docs.oursprivacy.com/docs/gtm-install): load the Web SDK through GTM.
