Web SDK Documentation
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:
Option 1: HTML Script Tag Installation (Recommended for most websites)
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.
Option 2: NPM Package Installation (Recommended for React/Vue/Next.js apps)
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-sdkThen 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
custom_domain_ipv4: "https://ip4-metrics.example.com", // Optional: Set a custom domain that works for IPV4
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
start: true, // Optional: Defaults to true when token is provided. Set to false to opt out.
mask_all_text: true, // Optional: Masks all text content on the page
},
});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 withcustom_domain: String: Custom domain for cookie storage and cross-domain trackingcustom_domain_ipv4: String: Custom domain for IPv4 requests whenforce_ipv4is enabledforce_ipv4: Boolean: Whether to force data collection through IPv4 ingest endpoints (Note: Some destinations require this.)track_web_events: Boolean: Enable/disable automatic web event trackingenhanced_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 eventsdefault_user_custom_properties: Object: Default user properties for GA4 trackingdefault_user_consent_properties: Object: Default user consent properties to include with all tracked eventssession_replay: Object: Session replay configuration withtoken(required),start(optional, defaults to true when token is provided), andmask_all_text(optional). When a token is provided, recording automatically starts by default.
For detailed information about each configuration option, see the Advanced Configuration section below.
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
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",
});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:
- Calling
ours.reset()generates a new anonymous visitor ID, different from the prior one - Calling
ours.reset('next_id')sets the new ID immediately, without requiringidentify() - No previous user properties or attribution state appear on post-reset events
- 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 replace existing defaults and apply to all subsequent tracked events.
ours("updateDefaultEventProperties", {
source: "test",
campaign: "e2e",
});Key behaviors:
- Replaces existing defaults: The new properties completely replace the previous default event properties (does not merge)
- Applies to subsequent events: Updated defaults are included in all events tracked after the update
- No server event: The update action itself is not sent as an event to the server
- 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 amountUpdate 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 replace existing defaults and apply to all subsequent tracked events.
ours("updateDefaultUserCustomProperties", {
plan: "premium",
tier: "gold",
});Key behaviors:
- Replaces existing defaults: The new properties completely replace the previous default user custom properties (does not merge)
- Applies to subsequent events: Updated defaults are merged with event-specific user properties on subsequent events
- No server event: The update action itself is not sent as an event to the server
- 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_tierUpdate Default User Consent Properties (updateDefaultUserConsentProperties)
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 replace existing defaults and apply to all subsequent tracked events.
ours("updateDefaultUserConsentProperties", {
analytics: true,
marketing: false,
});Key behaviors:
- Replaces existing defaults: The new properties completely replace the previous default user consent properties (does not merge)
- 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
- No server event: The update action itself is not sent as an event to the server
- 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: trueAdvanced 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 and may need to be enabled by your OursPrivacy account rep. See Custom Domain Setup 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_eventsto betrue - 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
updateDefaultEventPropertiesmethod. 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
updateDefaultUserCustomPropertiesmethod. See the Methods section for details.
Default User Consent Properties (default_user_consent_properties)
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
updateDefaultUserConsentPropertiesmethod. See the Methods section for details.
IPv4 CDN Support (force_ipv4 and custom_domain_ipv4)
Force the SDK to use IPv4-only endpoints for improved attribution accuracy with advertising platforms:
ours("init", "<ours web api key>", {
force_ipv4: true,
custom_domain_ipv4: "https://ipv4.yourdomain.com", // Optional custom IPv4 domain - requires setup. But allows you to send information all through your domain. You likely need custom_domain and custom_domain_ipv4 setup if forcing ipv4
});- force_ipv4: When enabled, the SDK will send events to the Ours Privacy IPV4 endpoint by default
- custom_domain_ipv4: Optional custom domain for IPv4 requests when
force_ipv4is enabled - Note: This setting may prevent event tracking for users on IPv6-only networks, but improves attribution accuracy with advertising platforms
Cross-Domain Tracking
Maintain user identity across different domains by passing the Ours user ID via query parameters:
// Example URL with user ID
https://example.com?ours_user_id=${localStorage.getItem('ours_device_id')}This is particularly useful when you need to maintain user identity across domains that don't share the same cookie domain.
Best Practices
Summary
- Installation: Place the SDK script in your
<head>for complete event capture - Initialization: Use the
initmethod to configure with your API key and desired options. Important:initcan 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
identifyto link events with specific users - Event Tracking: Use
trackto capture user actions and behaviors - User Reset: Use
resetto clear user identity when needed - Default Properties: Use
updateDefaultEventProperties,updateDefaultUserCustomProperties, andupdateDefaultUserConsentPropertiesto update default properties during the SDK lifecycle (sinceinitcan only be called once) - Cross-Domain Tracking: Pass user IDs via query parameters when needed
Common Use Cases
-
Basic Implementation
// Initialize ours("init", "<ours web api key>"); // Identify user ours("identify", { email: "user@example.com" }); // Track event ours("track", "page_view"); -
User Logout Flow
// When user logs out ours("reset", null); // Or set a specific new ID ours("reset", "anonymous_visitor_123"); -
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?