SDKsClient

Web SDK (client)

Get started with the Ours Privacy Web SDK. This guide covers installation in the head, event tracking using ours('track', ...), and user identification with ours('identify', ...).

Ours Privacy Web SDK Documentation

This guide covers everything you need to know about implementing and using the Ours Privacy Web SDK. Follow the sections below to get started and learn about advanced features.


Getting Started

Installation

You have two options for installing the Ours Privacy Web SDK:

To ensure that all page events are captured accurately, include the SDK script in the <head> section of your HTML:

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

    // Define function to track purchase events (call onPurchase() when purchase happens)
    function onPurchase() {
      ours('track', 'Purchase Complete', { value: 100 });
    }
  </script>
</head>

Note: Installing the SDK in the <head> ensures that events occurring as soon as the page loads are tracked properly. You can copy/paste this snippet from inside of your application.

For modern JavaScript frameworks and applications, you can install the SDK as an NPM package: @oursprivacy/cdp-sdk

npm install @oursprivacy/cdp-sdk
# or
yarn add @oursprivacy/cdp-sdk

Then import and initialize the SDK in your application:

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

// Initialize once per application startup
// In SPAs, this means once when the app loads - routing doesn't require re-initialization
ours.init('YOUR_TOKEN');

// Define function to track purchase events (call onPurchase() when purchase happens)
function onPurchase() {
  ours.track('Purchase Completed', { value: 1000 });
}

When to use the NPM package:

  • Building React/Vue/Next.js/Node.js applications
  • Want TypeScript types and local control over initialization
  • Prefer not to load the snippet from the Ours Privacy CDN
  • Need first-party integration in your build process

When to use the script tag:

  • Simple websites or landing pages
  • Quick implementation without build tools
  • When you want the drop-in solution

Both installation methods provide the same functionality - choose the one that best fits your development workflow.


Methods

Init

Initialize the SDK with your API key and any desired configuration options. Important: init can only be called once per page load (for traditional websites) or once per application startup (for single-page applications). In single-page applications (SPAs) like Next.js or React Router, initialize once at app startup - routing between pages doesn't require re-initialization.

ours('init', '<ours web api key>', {
  // Optional configuration
  user_id: '<custom user id>', //  Optional: Provide your own user ID
  custom_domain: 'https://metrics.example.com', // Optional: Set a custom domain
  force_ipv4: false, // Optional: Whether to force data collection through IPV4 ingest endpoints. (Note: Some destinations require this.)
  track_web_events: true, // Enable automatic web event tracking
  enhanced_web_events: false, // Optional: Enable enhanced web event tracking
  default_event_properties: {
    // Set default event_properties to include on every event
    // Your default event properties
  },
  default_user_custom_properties: {
    // Set default user custom_properties for every event
    // Your default user properties
  },
  default_user_consent_properties: {
    // Set default user consent_properties for every event
    // Your default consent properties
  },
  session_replay: {
    token: 'replay_token', // Optional: Session replay token from your account team
    mask_all_text: true, // Optional: Masks all text content on the page
    sampleRate: 0.1, // Optional: Record 10% of sessions
  },
  cookie_names: {
    device_id: 'anon_device_id', // Optional: Override the default visitor ID cookie name
    sdk_data: 'anon_sdk_data', // Optional: Override the default SDK data cookie name
  },
  experimentation: {
    token: 'exp_token', // Optional: Experimentation token from Experiment Settings
  },
  url_query_params_blocklist: ['token'], // Optional: Strip these query parameter names from captured URLs before send
});

Critical: init can only be called once per page load (traditional websites) or once per application startup (SPAs). All configuration options must be set during this single init call. If you need to change configuration after initialization, use the update methods (updateDefaultEventProperties, updateDefaultUserCustomProperties, updateDefaultUserConsentProperties) instead of calling init again.

Configuration Options:

  • user_id: String: Your custom user ID to identify the user with
  • custom_domain: String: Custom domain for cookie storage and cross-domain tracking
  • force_ipv4: Boolean: Whether to force data collection through IPv4 ingest endpoints (Note: Some destinations require this. Custom domains do not currently proxy the IPv4 endpoint.)
  • track_web_events: Boolean: Enable/disable automatic web event tracking
  • enhanced_web_events: Boolean: Enable enhanced web event tracking to automatically capture additional event properties. When enabled, we'll collect extra details like click text, link URLs, and other contextual data for all automatically tracked web events.
  • default_event_properties: Object: Default properties to include with all tracked events
  • default_user_custom_properties: Object: Default user properties for GA4 tracking
  • default_user_consent_properties: Object: Default user consent properties to include with all tracked events
  • session_replay: Object: Session replay configuration. Requires token. Optional fields include mask_all_text, sampleRate, alwaysRecordEvents, and the selector overrides block_selector / ignore_selector / mask_text_selector. When a token is provided, recording starts automatically; use sampleRate: 0 plus alwaysRecordEvents if you only want event-triggered capture. See the Session Replay docs.
  • cookie_names: Object: Override default cookie/localStorage key names. Use this when you need non-identifying cookie names (e.g., for privacy or compliance reasons).
    • device_id: String: Override the default ours_device_id key used to persist visitor identity.
    • sdk_data: String: Override the default key used for consolidated SDK data (session, engagement, etc.).
  • experimentation: Object: Experimentation configuration with token (required). When provided, the Web SDK loads the experimentation runtime automatically using your existing install.
  • url_query_params_blocklist: Array of strings: Query parameter names to remove from captured current_url and referrer values before events are sent. See url_query_params_blocklist below.

For detailed information about each configuration option, see the Advanced Configuration section below.

Experimentation And Visitor Identity

If you enable experimentation through the Web SDK:

ours('init', '<ours web api key>', {
  experimentation: {
    token: 'exp_token',
  },
});

...the Web SDK owns visitor identity for experimentation too.

If you ever need to manually initialize window.ours_experiments yourself, get the visitor ID from the CDP:

const visitorId = ours.getVisitorId();

window.ours_experiments.init({
  visitorId,
});

Do not generate your own visitor ID for experimentation. The CDP and experiments runtime must use the same visitor identity.

Track Events

Track events on your website using the ours('track', ...) method:

ours(
  'track',
  'event name',
  {
    // Event properties
    value: 1,
  },
  {
    // User properties
    first_name: 'test',
  }
);
  • Event Name: The name of your event
  • Event Properties: Metrics or values related to the event
  • User Properties: Additional user context. See allowed user properties. See Data Types and Field Values for how null, undefined, and empty strings are handled.

Identify

To associate tracked events with a specific user, use the ours('identify', ...) method. This method helps in linking the user's actions across sessions and devices.

ours('identify', {
  first_name: 'test',
  email: 'user@example.com',
  external_id: 'user123',
});

Heads up — how null, undefined, and "" behave: On top-level visitor properties (like email, gclid, phone_number), passing null clears the existing value. Passing undefined or an empty string leaves it alone. Inside custom_properties, all three are ignored. This matters when you're writing code like ours('identify', { gclid: urlParams.get('gclid') }) — if the param isn't present, get() returns null and the existing gclid on the visitor will be cleared. See Data Types and Field Values for the full rules and common pitfalls.

Reset

The ours('reset') method allows you to clear the current user's identity and start fresh with a new anonymous visitor ID. This is useful for scenarios like user logout, account switching, or privacy compliance.

// Generate a new anonymous visitor ID
ours('reset');

// Set a specific new visitor ID immediately
ours('reset', 'new_visitor_id');

Key behaviors:

  1. Calling ours.reset() generates a new anonymous visitor ID, different from the prior one
  2. Calling ours.reset('next_id') sets the new ID immediately, without requiring identify()
  3. No previous user properties or attribution state appear on post-reset events
  4. In-flight events from the old user are sent before reset; queued events are dropped

Important Warning:

The reset method creates a completely new visitor in Ours Privacy. This new visitor will be missing:

  • All UTM parameters and attribution data
  • Previous session history and user properties
  • Cross-device identity linking
  • Any stored visitor properties

When you have multiple visitors on different devices that should be tied together, you typically want to associate them using the same externalId within the same session, not create separate visitors.

Only use reset when you are absolutely certain this is what you want:

  • User logout functionality (when you want to completely clear identity)
  • Account switching within the same browser session
  • Privacy compliance (GDPR right to be forgotten)
  • A/B testing with fresh user identities

Update Default Event Properties (updateDefaultEventProperties)

Update default event properties after SDK initialization. This method exists because init can only be called once per page load (traditional websites) or once per application startup (SPAs). The updated properties will be merged with existing defaults and apply to all subsequent tracked events.

ours('updateDefaultEventProperties', {
  source: 'test',
  campaign: 'e2e',
});

Key behaviors:

  1. Merges with existing defaults: The new properties are merged with the previous default event properties. If a key already exists, the new value takes precedence
  2. Applies to subsequent events: Updated defaults are included in all events tracked after the update
  3. No server event: The update action itself is not sent as an event to the server
  4. Can be called multiple times: You can update default event properties multiple times during the SDK lifecycle

Example use case:

// Initialize with initial defaults
ours('init', '<ours web api key>', {
  default_event_properties: {
    environment: 'production',
  },
});

// Later, update defaults based on user action or context
ours('updateDefaultEventProperties', {
  environment: 'production',
  source: 'mobile_app',
  campaign: 'summer_sale',
});

// All subsequent events will include the updated defaults
ours('track', 'Purchase', { amount: 99.99 });
// This event will include: environment, source, campaign, and amount

Update Default User Custom Properties (updateDefaultUserCustomProperties)

Update default user custom properties after SDK initialization. This method exists because init can only be called once per page load (traditional websites) or once per application startup (SPAs). The updated properties will be merged with existing defaults and apply to all subsequent tracked events.

ours('updateDefaultUserCustomProperties', {
  plan: 'premium',
  tier: 'gold',
});

Key behaviors:

  1. Merges with existing defaults: The new properties are merged with the previous default user custom properties. If a key already exists, the new value takes precedence
  2. Applies to subsequent events: Updated defaults are merged with event-specific user properties on subsequent events
  3. No server event: The update action itself is not sent as an event to the server
  4. Can be called multiple times: You can update default user custom properties multiple times during the SDK lifecycle

Example use case:

// Initialize SDK
ours('init', '<ours web api key>');

// Update defaults when user upgrades their plan
ours('updateDefaultUserCustomProperties', {
  plan: 'premium',
  subscription_tier: 'enterprise',
});

// All subsequent events will include the updated user custom properties
ours('track', 'Feature Used', { feature: 'advanced_analytics' });
// This event's userProperties.custom_properties will include: plan and subscription_tier

Get Visitor ID (getVisitorId)

Returns the current visitor ID. Useful when you need to pass the visitor ID to another domain or system.

// Script tag (CDN install)
const visitorId = ours.getVisitorId();

// NPM SDK
const visitorId = ours.getVisitorId();

This is also the correct current-state source of truth when you need to pass a visitor ID into window.ours_experiments.init(...).

Get Session ID (getSessionId)

Returns the current session ID. Useful when you need to pass the session ID to another domain to maintain session continuity.

// Script tag (CDN install)
const sessionId = ours.getSessionId();

// NPM SDK
const sessionId = ours.getSessionId();

Example: Cross-domain link with both visitor and session ID

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

Update default user consent properties after SDK initialization. This method exists because init can only be called once per page load (traditional websites) or once per application startup (SPAs). The updated properties will be merged with existing defaults and apply to all subsequent tracked events.

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

Key behaviors:

  1. Merges with existing defaults: The new properties are merged with the previous default user consent properties. If a key already exists, the new value takes precedence
  2. Applies to subsequent events: Updated defaults are merged with event-specific consent properties on subsequent events. Event-specific consent properties take precedence if there is a conflict
  3. No server event: The update action itself is not sent as an event to the server
  4. Can be called multiple times: You can update default user consent properties multiple times during the SDK lifecycle

Example use case:

// Initialize SDK
ours('init', '<ours web api key>');

// Update consent defaults when user changes their preferences
ours('updateDefaultUserConsentProperties', {
  analytics: true,
  marketing: false,
  functional: true,
});

// All subsequent events will include the updated consent properties
ours('track', 'Page View');
// This event's userProperties.consent will include: analytics, marketing, and functional

// Event-specific consent can override defaults
ours(
  'track',
  'Button Click',
  {},
  {
    consent: { marketing: true }, // Overrides the default marketing: false
  }
);
// This event's userProperties.consent will have: analytics: true, marketing: true, functional: true

Advanced Configuration

Note: All configuration options shown below are set during the single init method call. Remember that init can only be called once per page load (traditional websites) or once per application startup (SPAs). In single-page applications (SPAs), you initialize once at app startup and then route between pages without re-initializing. If you need to change configuration after initialization, use the update methods (updateDefaultEventProperties, updateDefaultUserCustomProperties, updateDefaultUserConsentProperties) instead.

Custom User IDs (user_id)

Provide your own user ID for tracking when you have your own user identification system. This is useful for linking analytics data to your internal user records.

ours('init', '<ours web api key>', {
  user_id: 'user_12345',
});
  • Best Practice: Use a stable, unique identifier (such as your database user ID or external_id) to ensure consistent tracking across sessions and devices.

Custom Domains (custom_domain)

Set a custom domain for cookie storage to help with cross-domain tracking and to ensure cookies are set as first-party. This is especially important for privacy, compliance, and accurate tracking.

ours('init', '<ours web api key>', {
  custom_domain: 'https://yourdomain.com',
});
  • Advanced: Requires DNS setup. See Custom Domains for details.
  • Best Practice: Use the same custom domain across all your sites for seamless cross-domain tracking.

Track Web Events (track_web_events)

Enable or disable automatic tracking of standard web events (such as page views, clicks, etc.).

ours('init', '<ours web api key>', {
  track_web_events: true,
});

Enhanced Web Events (enhanced_web_events)

Enable enhanced web event tracking to automatically capture additional event properties. When enabled, we'll collect extra details like click text, link URLs, and other contextual data for all automatically tracked web events.

ours('init', '<ours web api key>', {
  track_web_events: true,
  enhanced_web_events: true,
});
  • Requires: track_web_events to be true
  • Default: false
  • Note: This feature enhances the data collected by automatic web event tracking with additional contextual information

Default Event Properties (default_event_properties)

Set default properties to include with every tracked event. Useful for adding environment, app version, or other context to all events.

ours('init', '<ours web api key>', {
  default_event_properties: {
    environment: 'production',
    app_version: '1.0.0',
  },
});
  • Advanced: These properties are merged with event-specific properties. Event-specific properties take precedence if there is a conflict.
  • Note: Default event properties can be updated after initialization using the updateDefaultEventProperties method. See the Methods section for details.

Default User Custom Properties (default_user_custom_properties)

Set default user properties to include with every event, often used for GA4 or other destinations that support user-level properties.

ours('init', '<ours web api key>', {
  default_user_custom_properties: {
    user_type: 'premium',
    subscription_tier: 'enterprise',
  },
});
  • Advanced: These are included as user properties on the first event of each session. Useful for segmenting users in analytics platforms.
  • Note: Default user custom properties can be updated after initialization using the updateDefaultUserCustomProperties method. See the Methods section for details.

Set default user consent properties to include with every event. Useful for managing consent preferences across your application.

ours('init', '<ours web api key>', {
  default_user_consent_properties: {
    analytics: true,
    marketing: false,
  },
});
  • Advanced: These consent properties are merged with event-specific consent properties. Event-specific consent properties take precedence if there is a conflict.
  • Note: Default user consent properties can be updated after initialization using the updateDefaultUserConsentProperties method. See the Methods section for details.

URL Query Params Blocklist (url_query_params_blocklist)

Remove specific query parameter names from captured current_url and referrer values before events are sent.

ours('init', '<ours web api key>', {
  url_query_params_blocklist: ['token'],
});
  • Matching is case-insensitive.
  • This applies only to captured current_url and referrer values. Other URL-derived fields and separately captured marketing params such as utm_source, gclid, and fbclid are unchanged.

IPv4 Endpoints (force_ipv4)

Some advertising platforms attribute more accurately when ingest traffic comes over IPv4. Setting force_ipv4: true routes events through the Ours Privacy IPv4 endpoint:

ours('init', '<ours web api key>', {
  force_ipv4: true,
});
  • Note: This may prevent event tracking for visitors on IPv6-only networks. Custom domains do not currently proxy the IPv4 endpoint — force_ipv4 traffic goes to Ours Privacy's IPv4 host.

Cross-Domain Tracking

Maintain visitor identity across different domains by passing the Ours Privacy visitor ID via query parameters:

// Example URL with visitor ID
https://example.com?ours_visitor_id=${ours.getVisitorId()}

This is particularly useful when you need to maintain visitor identity across domains that don't share the same cookie domain.

Passing Session ID

You can also pass a session ID via the ours_session_id query parameter to maintain session continuity across domains:

// Example URL with both visitor ID and session ID
https://example.com?ours_visitor_id=${ours.getVisitorId()}&ours_session_id=${ours.getSessionId()}

When ours_session_id is present, the SDK uses it as the current session ID instead of generating a new one. This ensures analytics and destinations see one continuous session across domains.


Best Practices

Summary

  • Installation: Place the SDK script in your <head> for complete event capture
  • Initialization: Use the init method to configure with your API key and desired options. Important: init can only be called once per page load (traditional websites) or once per application startup (SPAs). In SPAs, initialize once at app startup - routing doesn't require re-initialization.
  • User Identification: Use identify to link events with specific users
  • Event Tracking: Use track to capture user actions and behaviors
  • User Reset: Use reset to clear user identity when needed
  • Default Properties: Use updateDefaultEventProperties, updateDefaultUserCustomProperties, and updateDefaultUserConsentProperties to update default properties during the SDK lifecycle (since init can only be called once)
  • Cross-Domain Tracking: Pass user IDs via query parameters when needed

Common Use Cases

  1. Basic Implementation

    // Initialize
    ours('init', '<ours web api key>');
    
    // Identify user
    ours('identify', { email: 'user@example.com' });
    
    // Track event
    ours('track', 'page_view');
  2. User Logout Flow

    // When user logs out
    ours('reset', null);
    
    // Or set a specific new ID
    ours('reset', 'anonymous_visitor_123');
  3. Account Switching

    // Clear current user
    ours('reset', null);
    
    // Identify new user
    ours('identify', { email: 'newuser@example.com' });

Troubleshooting

  • Events not tracking: Ensure the SDK is installed in the <head> section
  • User identification issues: Verify user properties are being passed correctly
  • Cross-domain problems: Check that custom domains are configured properly
  • Reset not working: Ensure you're calling reset before identifying a new user

For additional details and advanced configurations, please refer to the related guides in the sidebar.

How is this guide?

On this page