Skip to content

Compass Web SDK: JavaScript API Reference

Last updatedView as Markdown

This page is the reference for the public JavaScript API of the Arc XP Compass Web SDK, version 1.2.0. To add the SDK to a site, see Compass Web SDK: Integration Guide.

Entry points

The SDK exposes the same methods in two ways:

DistributionEntry pointNotes
Script bundle (compass-sdk.iife.min.js)window.ArcCompassA single client. The loader snippet queues calls made before the bundle loads and replays them in order.
npm package (@arcxp/compass-sdk)new ArcCompassClient()An ES module for build pipelines. Construct one client, then call init() on it.
import { ArcCompassClient } from "@arcxp/compass-sdk";
const compass = new ArcCompassClient();
compass.init({ origin: "https://{org}-config-prod.api.arc-cdn.net", apiKey: "<arc-delivery-token>" });

The npm package also exports these values:

ExportValue
EVENT_TYPESEvery event type track() accepts, as an array.
ATTRIBUTION_ATTRSThe data-arc-compass-* attribute names listed in Attribution attributes.
ATTRIBUTION_SELECTOR[data-arc-compass-attribution-id], the selector the SDK scans for.
CATCH_UP_SOURCE"fy-catchup", the attribution source on Catch Up card events.

It exports these TypeScript types: InitOptions, BatchOptions, QueueOptions, ArcCompassErrorInfo, ExperienceFailureCode, ConsentStatus, EventType, TrackProps, AttributionContext, ItemAttribution, ObservedItem, ObserveOptions, ObserveHandle, CatchUpCardAttribution, and CatchUpSegmentAttribution.

Methods

MethodReturnsSummary
init(options)voidConfigure and start the SDK. Call once.
setConsent(granted)voidRecord the reader’s consent decision.
setUserId(userId)voidSet or clear the known user ID.
getUserId()string | nullThe identifier the SDK puts on events.
track(eventType, props?)voidQueue a behavioral event.
observeRecommendations(options)ObserveHandleAttribution-track a rendered recommendation set.
trackExposure(element, attribution)voidAttribution-track one host-rendered recommendation element.
refreshExperiences(selector?)voidRe-fetch and re-render SDK-rendered Experiences.
flush()Promise<void>Send queued events now.
diagnose()voidPrint a setup summary to the console.

None of these methods throws except init(). On an ArcCompassClient, calls to setUserId(), track(), observeRecommendations(), and trackExposure() made before init() are ignored; under debug, the last three log a warning. On the script bundle, calls made before the SDK initializes, from init() or from markup, are held and applied in order right after it initializes.

init(options)

Configures the client and starts it: it registers the <arc-compass-*> Experience elements, starts automatic page_view capture unless autoPageView is false, and starts the attribution attribute scan unless attributionRoot is false. For options, see Configuration options.

init() throws an Error when:

  • apiKey is missing or empty.
  • Neither origin nor domain is set.
  • origin is not a bare http or https origin, for example because it carries a path.
  • It has already been called on this client.

On the script bundle, an init() call made after the SDK initialized from markup has no effect and logs a console.error instead of throwing. See When the SDK initializes.

setConsent(granted)

Records the reader’s consent decision. It is the single gate on collection and on SDK-rendered Experiences.

grantedEffect
trueSends the events queued while consent was unknown, sends later events as they are tracked, and lets Experiences render.
falseDiscards the queued events, deletes the persistent identifiers the SDK wrote, and drops later track() calls. Experiences render nothing.

Until you call it, events wait in memory and Experiences render nothing. See Consent & Identity.

setUserId(userId)

Sets the known user ID, such as your own ID for a logged-in reader. Pass null to clear it, so that events fall back to the SDK’s anonymous ID. Compass stores the value as sent, so pass an opaque identifier, never PII such as an email address. To re-render SDK-rendered Experiences for the new reader, call refreshExperiences() afterward.

getUserId()

Returns the identifier the SDK puts on events, so you can pass the identical value as user_id when you request recommendations yourself:

  • The ID set with setUserId(), when there is one.
  • Otherwise, the SDK’s anonymous ID, after consent is granted.
  • Otherwise, null, before consent or before init().

It returns a value, so it can’t be queued. The loader snippet’s stub returns null until the bundle has loaded and initialized.

track(eventType, props?)

Queues one behavioral event. The SDK resolves identity and the item and site IDs when it sends the batch, so a consent decision made after track() still applies. track() never throws.

  • Before init(), the event is dropped.
  • While consent is unknown, the event waits in the queue.
  • After setConsent(false), the event is dropped.

eventType is one of: page_view, click, video_start, video_complete, video_progress, search, share, article_save, deepest_scroll, engaged_read, recommendation_exposure, recommendation_click, catch_up_shown, catch_up_click, or catch_up_dismiss. The SDK emits the recommendation_* and catch_up_* types itself; don’t track them by hand. For what each type means, see Supported Event Types.

props is optional:

PropertyTypeDefaultDescription
itemIdstringThe arc-compass:item-id meta tagThe item this event is about.
siteIdstring | nullinit({ siteId }), then the arc-compass:site-id meta tagThe site for this event. null sends no site_id.
eventValuenumber—Magnitude from 0.0 to 1.0, such as the fraction of a video watched.
sessionIdstringThe SDK-managed sessionOverrides the session ID for this event.
timestampDate | string | numberCapture timeA Date, a parseable timestamp string, or epoch milliseconds. A value that doesn’t parse is ignored.
attributionContextAttributionContext—Attribution identifiers from the recommendation response. Ignored on event types that don’t carry attribution.

The SDK applies the Collector’s event_value rules before sending. It drops a deepest_scroll that has no eventValue and reports the drop to onError with reason: "rejected". It sends an article_save without its eventValue. See

Events & Reliability

for item ID and site ID resolution and batching.

observeRecommendations(options)

Attribution-tracks a recommendation set that your code rendered. The SDK sends a recommendation_exposure when an element has been at least 50% visible in the viewport for 1 second, and a recommendation_click when the reader clicks the element or anything inside it.

options is an ObserveOptions object:

PropertyTypeDescription
containerElementThe element that wraps the set. The SDK attaches one click listener here.
itemsObservedItem[]Each rendered element as { element, attribution }, where attribution is an ItemAttribution.

It returns an ObserveHandle. Call its disconnect() method when the set is replaced or removed, so a stale set stops sending events. disconnect() is safe to call more than once. Through the loader snippet, the call is queued and the returned handle takes effect after the bundle loads.

trackExposure(element, attribution)

Attribution-tracks one recommendation element that your code rendered, with the same exposure and click behavior as observeRecommendations(). It is the imperative alternative to the attribution attributes. attribution is an ItemAttribution.

The element must be inside attributionRoot for its clicks to register. Registering the same element twice has no effect. A call made before the SDK has found attributionRoot is held until it does. When attributionRoot is false or invalid, the call is dropped with a warning.

ItemAttribution

The attribution for one rendered recommendation element. Copy each value from the recommendation response.

PropertyTypeRequiredDescription
itemIdstringYesThe recommended item’s item_id, not the page’s own item.
attributionIdstringYesThe item’s attribution_id.
exposureIdstringYesThe response’s attribution.exposure_id. Identical for every item in the set.
surfaceIdstringNoThe surface the set is rendered on.
positionnumberNoThe item’s zero-based position.
issuedAtDate | stringNoThe response’s attribution.issued_at.
sourcestringNoAttribution origin. Leave it unset; it defaults to fy, and only fy attribution counts toward Confirmed CTR.

For the full attribution flow, see Recommendation Attribution.

refreshExperiences(selector?)

Re-fetches and re-renders SDK-rendered Experiences, for example after setUserId() on a login. With a CSS selector, it refreshes the Experiences that match the selector or are inside an element that matches it; without one, it refreshes every Experience on the page. An invalid selector refreshes nothing and logs a warning under debug. A refreshed Experience still waits for consent.

flush()

Sends the queued events now and resolves when the request finishes. It does nothing until consent is granted. You rarely need it: the SDK sends on a timer, on batch size, and when the reader leaves the page.

diagnose()

Prints a setup summary with console.warn: the SDK version, the event and Experiences endpoints, whether an API key is set, the debug and consent state, whether a site_id resolved, the arc-compass:* meta tags present, and each Experience tag with its last lifecycle event. It works before init() and without debug, and it never prints the API key, a meta tag’s value, or anything that identifies the reader. Type ArcCompass.diagnose() in the browser console; the loader snippet doesn’t queue it.

Reserved methods

ArcCompassClient also has observeCatchUp(), trackCatchUpShown(), trackCatchUpClick(), and trackCatchUpDismiss(). The SDK’s Catch Up card uses them to send its own analytics events. They aren’t on window.ArcCompass; don’t call them.

Configure from markup

Instead of calling init(), you can put the SDK configuration in HTML. The bundle reads it when it loads and initializes itself, so you don’t write any JavaScript to set up the SDK.

Add the configuration as data-arc-compass-* attributes on the <script> tag that loads the bundle:

<head>
<meta name="arc-compass:item-id" content="ARTICLE-ABC123" />
<meta name="arc-compass:site-id" content="the-daily" />
<script
src="https://arc-rec.app-recommend.aws.arc.pub/arc-rec/v1.2.0/compass-sdk.iife.min.js"
integrity="sha384-VvYEr4g99L9WMmYHPcTMN3vZyiIlN4jT+c/GtVx5CBfQimkjKeTbE/Njl6hWfdGZ"
crossorigin="anonymous"
data-arc-compass-origin="https://{org}-config-prod.api.arc-cdn.net"
data-arc-compass-api-key="<arc-delivery-token>"
></script>
<script>
// Pass true after your CMP reports consent.
ArcCompass.setConsent(true);
</script>
</head>
<body>
<!-- … -->
<arc-compass-recommendations-list surface-id="article-footer"></arc-compass-recommendations-list>
</body>

Load the bundle with a plain <script> tag, without async or defer, so ArcCompass exists when the code that follows it runs. To load the bundle asynchronously, use the loader snippet and put the configuration in meta tags instead (see Meta tags).

Consent is not part of the markup configuration. You still call ArcCompass.setConsent() from your consent code, as described in Resolve consent. Until you do, the SDK sends no events and SDK-rendered Experiences render nothing.

Attributes

Each attribute sets the init() option of the same name. See the configuration options for what each option does.

Attributeinit() optionValue
data-arc-compass-originoriginRequired, unless data-arc-compass-domain is set.
data-arc-compass-api-keyapiKeyRequired.
data-arc-compass-site-idsiteIdOptional. The Site every event and Experience uses.
data-arc-compass-domaindomainOptional override.
data-arc-compass-experiences-domainexperiencesDomainOptional override.
data-arc-compass-cookie-domaincookieDomainOptional.
data-arc-compass-attribution-rootattributionRootOptional. A CSS selector, or false to turn off the scan.
data-arc-compass-auto-page-viewautoPageViewOptional. On unless set to false or 0.
data-arc-compass-debugdebugOptional. On when present, unless set to false or 0.

The batching, queue, and onError options have no attribute. To set them, call init() instead.

Meta tags

If you can’t add attributes to the <script> tag, for example because a tag manager or the loader snippet inserts it, use meta tags with the same names:

<meta name="arc-compass:origin" content="https://{org}-config-prod.api.arc-cdn.net" />
<meta name="arc-compass:api-key" content="<arc-delivery-token>" />

If an attribute and a meta tag set the same option, the attribute is used.

The Site is the exception. <meta name="arc-compass:site-id"> keeps the meaning described in Add the content and site meta tags: the SDK reads it each time it needs a Site, so it can change from route to route. It does not count as configuration. To fix the Site for every page, use the data-arc-compass-site-id attribute.

When the SDK initializes

The SDK initializes from markup when the page finishes parsing (DOMContentLoaded), and only if the page sets an origin, a domain, or an API key. A page that declares none of them, for example one with only a data-arc-compass-debug attribute, does not initialize from markup.

  • An init() call made before then takes precedence, whether you call it directly or the loader snippet queues it. The SDK ignores the markup configuration entirely; it does not merge the two.
  • Calls such as setConsent(), setUserId(), and track() made before the SDK initializes are held and applied in order right after it initializes, from either source.
  • The SDK initializes only one time, so an init() call made after it has initialized from markup has no effect: none of its options apply, including onError. The SDK logs a console.error instead of throwing. If you need an option that markup can’t express, call init() before DOMContentLoaded, or remove the markup configuration.
  • If the markup configuration is invalid, for example because the API key is missing, the SDK logs a console.error and does not initialize. A later init() call still works.

Configuration options

ArcCompass.init(options) accepts the following options. Only apiKey and one of origin or domain are required.

OptionTypeDefaultDescription
originstring— (required unless domain is set)Your org’s Arc XP edge origin with no path, for example https://{org}-config-prod.api.arc-cdn.net. The SDK derives the event collector endpoint (/collect-web/v1/events/batch) and the Experiences endpoints (/experiences/…) from it. init() throws if it carries a path, query, or fragment, or is not an http(s) URL. Since SDK 1.2.0.
apiKeystring— (required)Delivery token provisioned by Arc XP. Sent as X-API-Key on every request — event posts and the SDK-rendered Experiences’ recommendation reads alike.
domainstringorigin + /collect-web/v1Override for the events collector base path, for example https://{org}-config-prod.api.arc-cdn.net/collect-web/v1. The SDK appends /events/batch. Set it only when your event collector is not at the path origin implies. On SDK versions earlier than 1.2.0, this option is required in place of origin.
experiencesDomainstringoriginOverride for the origin the SDK-rendered Experiences read from, the Arc XP edge root the /experiences/… recommendation and Catch Up routes hang off. Defaults to origin, or, when only domain is set, to domain with a trailing /collect-web/v<n> removed. Set it only when the Experiences service is on a different host from your event collector.
siteIdstringthe arc-compass:site-id meta tagThe Site every event and Experience read uses. Takes priority over <meta name="arc-compass:site-id">, which the SDK then never reads; a siteId passed to track() still overrides it for that event. Leave it unset on a host whose Site varies by route, and set the meta tag on each route instead. See Add the content and site meta tags. Since SDK 1.2.0.
cookieDomainstringdetected registrable domainCookie Domain attribute for the anonymous-ID and session cookies. Defaults to the broadest scope the browser accepts for the current host, found by probing rather than by counting labels, so ccTLDs and platform hosts share identity across subdomains without configuration. Set it explicitly to override. See Cookie domain.
batch.maxEventsnumber20Flush when the buffer reaches this many events.
batch.flushIntervalMsnumber2000Flush this many milliseconds after the last flush.
queue.maxBufferednumber500Hard cap on in-memory queued events. Oldest are dropped on overflow with a console.warn.
autoPageViewbooleantrueFire page_view automatically each time the <meta name="arc-compass:item-id"> tag resolves to a new item (covering the initial load and every SPA route change), reading the optional site_id from <meta name="arc-compass:site-id"> at the same moment. Set false to call track('page_view', { itemId }) yourself.
attributionRootElement | string | falsedocument.bodyRoot under which the SDK scans for host-rendered recommendations carrying the data-arc-compass-* binding — also the click-delegation container, so tagged elements (and elements passed to trackExposure) must live inside it. Accepts an element or a CSS selector (resolved after the DOM is ready). Narrow it to the container that holds recommendations to avoid a page-wide MutationObserver; pass false to disable the scan entirely. A structurally-broken root (invalid selector, or a non-Element value) disables the binding with a console.warn; a valid selector whose container has not mounted yet is deferred and attaches on the next trackExposure. See Recommendation Attribution.
debugbooleanfalseLog lifecycle and transport diagnostics, including the event and Experiences endpoints the SDK resolved from your configuration, the cookie scope it detected, and why an SDK-rendered Experience showed nothing. You can also turn it on without editing init(); see Diagnostics and Nothing renders?.
onError(e: ArcCompassErrorInfo) => void—Called when the SDK abandons a batch (a terminal 4xx/429, or a 5xx/network failure that exhausts retries), when it drops an event before sending because the Collector would reject it, when an SDK-rendered Experience fails to load, and when the browser accepts no cookie scope so identity drops to per-origin. Use it to forward otherwise-silent loss to your observability. Never runs inside a track() call, so it cannot interrupt the page; anything it throws is swallowed. See Error visibility.

Diagnostics

The debug option logs lifecycle, transport, and Experience-render diagnostics to the console. When you can’t edit the init() call, for example because it sits in a tag manager or a template you don’t own, you can turn debug on from the page (since SDK 1.2.0):

  • Add ?arcCompassDebug to the page URL.
  • Add a data-arc-compass-debug attribute to the <script> tag that loads the SDK.

Either one turns debug on even when init() passes debug: false. A value of 0 or false leaves it off.

Separately from debug, the SDK logs one console.warn when an <arc-compass-*> Experience tag on the page can’t render (since SDK 1.2.0). The SDK checks a few seconds after the page loads, and the warning names the cause:

  • init() never ran, threw, or couldn’t load the Experience.
  • setConsent() hasn’t been called, so the Experience is still waiting for consent.

The warning is always on, and logs at most one time per page. It stays silent when the SDK is initialized and consent is set, including setConsent(false), because a Reader who declines consent is not an integration error.

Also without debug, an Experience that fails to load for a setup cause (the key, the origin or domain, a missing site_id, or a timeout) logs one console.warn per cause per page. For a summary of the whole setup, call ArcCompass.diagnose() from the browser console.

Error visibility

The SDK is fire-and-forget: track() never throws, and a batch that the Collector rejects (or that never gets through) is dropped rather than surfaced to the page. To make those drops observable, wire onError to your tooling. It never runs inside a track() call: batch failures and dropped events arrive from a batch timer or the page-unload handler, experience arrives from the failed Experience’s render, and degraded arrives wherever identity first resolves after consent.

ArcCompass.init({
origin: "https://{org}-config-prod.api.arc-cdn.net",
apiKey: "<browser token>",
onError: (e) => {
// e: { message, reason, code?, experience?, status?, droppedEvents, eventTypes, cause? }
Sentry.captureException(e.cause ?? new Error(e.message), { extra: e });
// or: datadogRum.addError(e.cause ?? new Error(e.message), e);
},
});

onError receives an ArcCompassErrorInfo object:

PropertyTypeDescription
messagestringHuman-readable summary, safe to log.
reason"rejected" | "exhausted" | "degraded" | "experience"What went wrong. See the following table. More values may be added in a minor version, so give a switch a default branch.
codeExperienceFailureCodeWhy an Experience didn’t load. Set only when reason is "experience". See Failure codes.
experiencestringThe failed Experience’s tag name, such as arc-compass-recommendations-list. Set with code.
statusnumberThe Collector’s HTTP status, when there was a response. Absent for network and CORS failures and for events the SDK dropped before sending.
droppedEventsnumberEvents discarded. 0 when reason is "degraded" or "experience".
eventTypesstring[]Distinct event types among the discarded events. Empty when reason is "degraded" or "experience".
causeunknownThe underlying thrown value, such as a network error, when there was one.
reasonMeaningEvents lost
"rejected"The Collector returned a terminal 4xx or 429, or the SDK dropped events before sending because the Collector would reject them (no status). Fix the payload or key; retrying won’t help.Yes
"exhausted"Repeated 5xx or network failures used up the retry budget.Yes
"degraded"The browser accepted no cookie scope, so identity is per-origin. Fires at most once per page. See Cookie domain.No
"experience"An SDK-rendered Experience didn’t load. Fires once per code and tag per page.No

Per-event issues (an unresolved item_id, a coerced event_value) are logged only under debug, not through onError.

When cookieDomain is omitted, the SDK writes its identity cookies at the broadest scope the browser accepts for the current host, which is that host’s registrable domain. It finds the scope by offering each candidate to the browser and keeping the first one that sticks, rather than by counting labels, so multi-segment public suffixes (.co.uk, .com.au) and platform hosts (CloudFront, Vercel, Netlify, GitHub Pages) resolve correctly without configuration. Probe cookies are deleted as soon as they are read back, and none is written before consent.

Set cookieDomain explicitly to override the detected scope. If the browser accepts no scope at all, identity still works but is per-origin rather than shared across subdomains, and onError fires once with reason: "degraded" (see Error visibility).

DOM lifecycle events

Every SDK-rendered Experience element dispatches lifecycle events on itself. The events bubble, so you can listen on a container and use event.target to tell which element fired.

EventdetailWhen
arc-compass:renderednullThe Experience rendered content.
arc-compass:emptynullThere is no content for this reader. This is a successful answer, not a failure.
arc-compass:error{ code }The Experience failed at any step. code is one of the failure codes.
arc-compass:catchup-donenullFired only by arc-compass-catchup-card, when the reader reaches the end of the card. It can fire after arc-compass:rendered, or never.

Each mount fires exactly one of rendered, empty, or error. Nothing fires while the Experience is waiting for consent. arc-compass:error is also reported to onError with reason: "experience". For using these events to reserve and release layout space, see Reserve Space and Handle Empty States.

Failure codes

ExperienceFailureCode names a setup cause you can fix:

CodeCause
unauthorizedThe Experiences API rejected apiKey (401).
forbiddenThe Experiences API returned 403. Either the key can’t read Experiences from this page, so check its access and allowed origins, or your organization isn’t active yet, with the body {"detail":"Tenant is not active"}. See Cold-start response states.
networkNo readable response: the API refused this page’s origin (CORS), the host is unreachable, or origin or experiencesDomain is wrong.
not_foundThe Experiences base returned 404. Check origin or experiencesDomain.
missing_site_idNo site resolved. Pass siteId to init() or add <meta name="arc-compass:site-id">.
timeoutNo response within 5 seconds.
otherAnything else, such as a 5xx, a response that didn’t validate, or a render error. Turn on debug for the detail.

Attribution attributes

To attribution-track recommendations your code renders without calling trackExposure(), add these attributes to each rendered recommendation element inside attributionRoot. The SDK finds elements by data-arc-compass-attribution-id, including elements added later.

AttributeRequiredValue
data-arc-compass-item-idYesThe recommended item’s item_id. An element without it is skipped.
data-arc-compass-attribution-idYesThe item’s attribution_id.
data-arc-compass-exposure-idYesThe response’s attribution.exposure_id. Identical for every item in the set.
data-arc-compass-surface-idNoThe surface the set is rendered on.
data-arc-compass-positionNoThe item’s zero-based position.
data-arc-compass-issued-atNoThe response’s attribution.issued_at.

See Recommendation Attribution. For the attributes of the <arc-compass-*> Experience elements themselves, see

Recommendations Components

and Catch Up Card.

Endpoints the SDK calls

The SDK posts events to POST {domain}/events/batch, which is /collect-web/v1/events/batch by default, in batches of up to 100. SDK-rendered Experiences read GET /experiences/recommend/v1/recommendations and GET /experiences/storyline/v1/catch-up from experiencesDomain. These requests are internal to the SDK, and their contract can change with it; you don’t call the collect-web or Catch Up endpoints yourself. The events use the same envelope as the Collector API.

Browser support

The SDK supports Chrome and Edge 111+, Firefox 113+, Safari and iOS Safari 16.2+, and Samsung Internet 22+. That floor is set by the rendered Experiences; event collection on its own runs on older browsers too, with the caveats in the table. The floor ships as the browserslist field in the package’s package.json.

FeatureUsed forChrome / EdgeFirefoxSafariWithout it
fetch with keepalive: trueSending events, including the flush when the reader leaves the page6613313Events still send, but the final flush on page exit can be lost
visibilitychange, pagehideDetecting when the reader leaves, to flush queued events33187Events still in the queue when the reader leaves may not be sent
localStorage, sessionStorage, cookiesAnonymous and session IDsAllAllAllIf storage is blocked, IDs do not persist across page views
crypto.randomUUIDGenerating IDs929515.4Falls back to crypto.getRandomValues; no effect
Custom elements, shadow DOMEvery Experience is an <arc-compass-*> element with a shadow root676310.1Experiences do not render
IntersectionObserverExposure attribution; Catch Up Card view telemetry585512.1Exposure events are not sent; click attribution still works
::part()Restyling Experience internals from your CSS737213.1Your ::part() rules do not apply
color-mix(), including in oklabThe Catch Up Card’s neutral colours: muted text, hairlines, subtle fills11111316.2The card renders without its fills and hairlines, and muted text shows at full strength

The recommendations Components do not use color-mix(), so they render in older browsers as well, but only the browsers listed at the start of this section are supported. In Firefox before 133, the event flush on page exit is best-effort. For more on theming features, see Compass Web SDK: Theming Reference.

The SDK is browser-only. The IIFE bundle is safe to include in a server-rendered page — it no-ops on import when window is undefined.