Skip to Content
CDPGuidesSupport
SDKsClient

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.

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 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.

The Install Ours page with a Web SDK row for the Northside Website, showing its allowed domains and an Install button

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:

<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 and bot detection. Add any other 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.

npm package

For React, Vue, Next.js, and other bundled apps, install @oursprivacy/cdp-sdk. It includes TypeScript types.

npm install @oursprivacy/cdp-sdk
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.


Track events

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 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:

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. 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.


Reset on logout

// 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 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 you set in init at any time:

MethodUpdates
updateDefaultEventPropertiesProperties added to every event
updateDefaultUserCustomPropertiesVisitor custom_properties added to every event
updateDefaultUserConsentPropertiesVisitor consent values added to every event
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

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 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:

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'],
});
OptionWhat it does
track_web_eventsTracks page views, clicks, scrolls, forms, and more automatically. See Track Web Events.
enhanced_web_eventsAdds link and click text to automatic events. Requires track_web_events. Off by default.
bot_detectionCollects the behavioral signals behind Advanced Bot Detection. Off by default; the dashboard snippet turns it on.
custom_domainSends events through your custom domain, so tracking runs first-party.
user_idSets 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.
default_event_propertiesProperties added to every event. See Default Event Properties.
default_user_custom_propertiesVisitor custom_properties added to every event, for example a plan or segment you send to GA4 as user properties.
default_user_consent_propertiesVisitor consent values added to every event.
url_query_params_blocklistQuery parameters to remove from captured URLs. See URL Query Params Blocklist.
force_ipv4Sends events over IPv4. See IPv4 Endpoints.
session_replayTurns on Session Replay with your replay token, plus sampling, masking, and page options.
experimentationTurns on Experimentation with your experimentation token. Experiments use the Web SDK's visitor ID.
cookie_namesRenames 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.

EventWhen it firesProperties
page_viewOn page load and on single-page app route changes.is_first_visit, is_new_session, is_spa_navigation
scrollOnce per page, when the visitor scrolls 90% of the way down.percent_scrolled
clickOn a click on an outbound, mailto:, or tel: link.link_url, link_domain, protocol, outbound, click_text†
$link_clickOn a click on any link, internal or outbound.link_url, link_domain, link_id, link_classes, outbound, link_text†
file_downloadOn a click on a link to a common file type (PDF, DOCX, XLSX, ZIP, MP4, and others).file_name, file_extension, link_url
form_startThe first time a visitor focuses a field in a form.form_id, form_name, page_location
form_submitWhen a form is submitted.form_id, form_name, page_location
view_search_resultsWhen the URL has a search parameter (q, s, search, query, keyword, or term).search_term, search_parameter, page_location
user_engagementWhen 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:

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.

URL Query Params Blocklist (url_query_params_blocklist)

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

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:

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:

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.


Troubleshooting

  • No events arriving: Check that the snippet is in the <head> and your site's domain is in Allowed Domains. Then follow 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

How is this guide?

On this page