Analytics SDKs

Add the script tag or the browser, Node.js, or Python SDK and send your first product event.

Send pageviews and product actions, including clickstream events, to a Contrast Analytics project. Your browser and backend can use the same project.

What gets captured

Every browser install captures pageviews and, when a visitor leaves a page, a $pageleave event with time on page and scroll depth. The script tag also captures outbound link clicks, file downloads, and web vitals; a bundled app turns those on with startWebSignals. Record other clicks and actions with track. The SDK never reads page text, form contents, or the text of a clicked element, and has no session replay or feature flags.

Send your first event

Create a project

Open Analytics in Contrast and choose Create project. That turns on Analytics if it is off and shows the project's key with its install steps: a setup prompt to paste into a coding agent, or the steps for Next.js, React, JavaScript, a website, or Node.js. To add another app later, choose New project and name it. Only a workspace admin can create a project.

A project has one public project key. It only sends events, so it is safe in browser code, and it works on your own machine and on your live site with nothing else to set up.

For backend events, also create a server key under Settings. Store it as a server-side secret such as CONTRAST_ANALYTICS_SERVER_KEY. Never put it in browser code or a NEXT_PUBLIC_ variable.

Install the SDK

For Webflow, WordPress, Shopify, Framer, or plain HTML. Paste this before </head> on every page (the site's custom code or theme settings) with your project key. There is nothing to install.

<script async src="https://cdn.jsdelivr.net/npm/@contrastlabs/analytics@0.4/dist/contrast.js" data-project-key="pk_your_project_key"></script>

The tag loads the client and exposes it as window.contrast. @0.4 follows patch releases; pin @0.4.0 to freeze it.

To call contrast.track(...) before the script has loaded, add this above it. It queues the calls and replays them in order:

<script>
  window.contrast = window.contrast || { q: [] };
  ["track", "identify", "group", "page", "reset", "setEnabled"].forEach(function (method) {
    contrast[method] = contrast[method] || function () {
      contrast.q.push([method].concat([].slice.call(arguments)));
    };
  });
</script>

Every client sends to https://api.embrasure.ai/collect by default. Use the same project key in each integration.

Send an event

Pageviews, outbound link clicks, file downloads, and web vitals need no code. Call contrast from any script or handler on the page for your own events:

<button onclick="contrast.track('signup_started', { source: 'pricing' })">Sign up</button>

window.contrast has the same methods as the browser client, including identify, group, and reset.

Verify collection and reporting

Open your site or trigger the action. The project's page in Contrast shows Awaiting data… until the event arrives, then First event received on its own; choose Open dashboard. Receiving an event means the collector acknowledged it. Reports fill in after warehouse processing, which can take a few minutes. If nothing arrives after a minute, see Troubleshooting.

While testing the browser client, call await analytics.flush() and inspect accepted, discarded, dropped, and pending. Node.js flush() and Python flush(timeout=...) or shutdown(timeout=...) return the same counts. discarded means the event was not stored; pending means delivery has not finished.

Core APIs

PurposeBrowserNode.js serverPython server
Record an actiontrack(name, properties)track(message)track(name, **fields)
Update user traitsidentify(userId, traits)identify(message)identify(user_id, **fields)
Update group traitsgroup(type, key, traits)group(message)group(type, key, **fields)
Record a pageviewpage(); automatic by defaultSend a page message through the collection APISend a page message through the collection API
Send queued events nowflush()flush()flush(timeout=...)
End a clientdestroy()destroy()shutdown(timeout=...)

In the browser, call identify after sign-in and reset() on logout or account change. group associates the current browser identity with a company or other group:

analytics.identify("user_123", { plan: "pro" });
analytics.group("company", "company_456", { seats: 5 });
analytics.track("report_created", { report_id: "report_789" });
// On logout: analytics.reset();

Server SDKs do not retain a current user, group, or session. Include identity on every message. Python's track, identify, and group return True when a message is queued, not delivered.

Browser options

Pass options to createAnalytics, or set the matching data- attribute on the script tag.

OptionScript tag attributeDefaultWhat it does
hostdata-hosthttps://api.embrasure.ai/collectWhere events are sent. Set it to send through your own domain.
capturePageviewdata-capture-pageviewInitial page and path changes{ path: true, search: true } also counts query string changes, and { path: true, hash: true } counts hash routes (path search and path hash on the script tag). true counts the initial page only; false leaves pageviews to page().
enableddata-enabledtruefalse sends nothing until setEnabled(true), for consent banners.
respectPrivacySignalsdata-respect-privacy-signalsfalsetrue keeps the client off when the browser sends Global Privacy Control or Do Not Track.
crossSubdomainCookiedata-cross-subdomain-cookiefalsetrue keeps a visitor one person across subdomains, such as a marketing site on www and an app on app. It sets a first-party cookie, so check it against your consent policy.
botFilterdata-bot-filtertrueBots and automated browsers send nothing. Set false in end-to-end tests that assert on analytics, since Playwright, Cypress, and Selenium count as bots.
persistencedata-persistencelocalsession keeps identity per tab; memory uses no browser storage.

The script tag also takes data-outbound-clicks, data-downloads, and data-web-vitals; set one to false to turn that event off.

Automatic events

EventSent byWhen
PageviewEvery browser installThe initial page and each path change.
$pageleaveEvery browser install with pageviews onOnce when a visitor leaves a page, with duration_seconds and max_scroll_percentage. It is not counted as a pageview.
$outbound_clickScript tag, or startWebSignalsA click on a link to another host.
$downloadScript tag, or startWebSignalsA click on a link to a file such as a PDF or ZIP.
$web_vitalsScript tag, or startWebSignalsOnce per page load, with the vitals the browser reports.

In a bundled app, turn on the last three with the web entry point:

import { startWebSignals } from "@contrastlabs/analytics/web";

startWebSignals(analytics);

Link events carry the destination's host and path, never its query string or the link's text.

Pageviews also carry the campaign from utm_* parameters. ?ref= sets the campaign source when there is no utm_source, and the name of an ad click ID parameter such as gclid or fbclid marks paid traffic; the ID's value is never sent. The first pageview of a new browser is saved, and every later identify sends it as initial_landing_path, initial_referring_domain, initial_utm_source, initial_utm_medium, and initial_utm_campaign, which are set once per person.

Send through your own domain

Ad blockers and some browsers block requests to analytics hosts by name. Forward a path on your own domain to the collector and point host at it, and events travel as requests to your site. host must be an absolute URL; the SDK posts to <host>/v1/batch.

createAnalytics({
  projectKey: "pk_your_project_key",
  host: `${window.location.origin}/ingest`,
});

With the script tag, add data-host="https://www.example.com/ingest".

// next.config.js
module.exports = {
  async rewrites() {
    return [
      { source: "/ingest/:path*", destination: "https://api.embrasure.ai/collect/:path*" },
    ];
  },
};
  • Choose a path that does not name analytics: /ingest, not /analytics or /track.
  • The proxy must pass the visitor's Origin and User-Agent headers through unchanged. The collector reads browser, OS, and device from User-Agent, and checks Origin when the project restricts websites.
  • The script itself still loads from cdn.jsdelivr.net. A bundled app has no script request to block.
  • A proxied visit takes its country from the browser's time zone, because the request reaches the collector from your server's network, not the visitor's. It is an approximation for visitors whose time zone spans countries. Visits sent straight to the collector take their country from the network.
  • Keep the proxy on your site's own domain, as above. If it runs on a different domain, have it remove the Sec-Fetch-Site header, or visits can take the country your proxy runs in.

Restrict which websites can send events

A project accepts browser events from any website that has its project key, including a local address such as http://localhost:3000. The key only sends events and cannot read anything, so most projects need no restriction.

To accept browser events only from your own sites, a workspace admin lists them under Restrict to these websites in the project's Settings. From then on every other website gets a 403. Leave the list empty to accept any website again.

  • An entry is an exact origin such as https://app.example.com: scheme, host, and port, with no page path.
  • https://*.example.com covers every subdomain at any depth, which includes preview deployments, but not example.com itself. No other wildcard is accepted.
  • Adding a website to an existing list takes effect within seconds. The first entry starts restricting within 30 seconds.
  • Events your server sends are never restricted.

The list filters browser traffic. It is not authentication: a client that is not a browser can send any Origin header.

For consent-controlled browser collection, initialize with enabled: false and call analytics.setEnabled(true) after consent. Your app owns consent persistence. Set capturePageview: false and call analytics.page() if you want to control pageviews yourself.

Browser page data includes pathname and host, but excludes query strings, fragments, page text, and form values. Keep secrets and sensitive values out of event properties. The browser saves pending events locally for retry when storage is available; shutdown remains best effort. Server clients buffer events in memory. Use a transactional outbox when an event must survive an application crash.

Troubleshooting and reference

SymptomCheck
401Confirm the project key, and that the server key was created in the same project.
403Only a project that restricts websites returns this: the request's origin is not in its list. The project's page shows We blocked a request from with the address, and an admin can choose Allow this website; once events are arriving, the same notice appears under Settings. Allow an address only if the site is yours: anyone with your project key can send a request that claims any address. A newly allowed website starts working within seconds.
No request reaches ContrastAn ad blocker stopped it; send through your own domain. Or the page's Content-Security-Policy needs connect-src https://api.embrasure.ai, plus script-src https://cdn.jsdelivr.net for the script tag. The optional queueing snippet is inline, so a strict policy needs a nonce or hash for it; without it, call contrast only after the script loads.
www works but the apex does notThe project restricts websites, and each origin is separate. List both, or https://*.example.com plus https://example.com.
One visitor counted twice across subdomainsTurn on crossSubdomainCookie on both sites.
422Check required fields, event names, and payload limits.
Accepted but absent from reportsConfirm the key belongs to the project you are looking at. Reports trail collection by a few minutes; the project's Settings shows Ready in reports once they have caught up.

For browser diagnostics without logging event bodies or credentials, pass onDiagnostic: ({ type, count, reason }) => console.info(type, count, reason) to createAnalytics.

The package README has every option in full, including friction signals and the React and Next.js mount patterns. See the collection API for fields, limits, receipts, and errors, or the OpenAPI schema for native request and response models.