Skip to content
Optima docs
SDKsJavaScript SDK

API reference

JavaScript SDK v1.4.0 — API reference

API

MethodSignatureNotes
tracktrack(category: string, name?: string, props?: Record<string, unknown>): voidQueues a hit to the local outbox; batched to POST /edge/v1/track (20 hits, or 2 s after the first queued hit — whichever comes first).
pagepage(name?: string, props?: Record<string, unknown>): voidtrack("page_view", …) plus session/UTM enrichment. Called automatically on load (and on SPA navigation) unless page: "off".
identifyidentify(identifiers: Record<string, string>, attributes?: Record<string, unknown>, opts?: { assertion?: IdentityAssertion }): Promise<void>Attaches allowlisted identifiers/attributes to this device's profile via POST /edge/v1/identify. An identifier another customer already owns is NOT attached (it is recorded as an unverified claim) unless opts.assertion proves it — see Linking a logged-in customer.
resetreset(): void"A different visitor is using this browser now" — see What reset() clears. Call on logout on shared devices.
getDeviceIdgetDeviceId(): stringThe SDK-minted, persisted device id.
consent.getconsent.get(): ConsentStateThe current {v, decisions, decided_at, banner_id, policy, lang}.
consent.setconsent.set(decisions: Record<string, boolean>, meta?: { banner_id?, lang?, policy? }): Promise<void>Persists locally first, then posts POST /edge/v1/consent. The promise resolves after the local write and the first POST attempt; a 429/503/network failure keeps retrying in the background (5 attempts, Retry-After honoured) and a final give-up surfaces as an error event with op: "consent".
consent.setKeysconsent.setKeys(keys: Record<string, boolean>): voidVendor-level consent keys declared alongside every request.
consent.setGCMconsent.setGCM(g: Record<string, "granted"|"denied">): voidFed automatically by the built-in Google Consent Mode reader — call directly only if you're not using the automatic passthrough.
consent.setTCFconsent.setTCF(tc: string): voidFed automatically by the built-in TCF reader.
consent.canconsent.can(trackerName: string): booleanAnswers whether a named data-optima-tracker is currently allowed to run.
consent.onconsent.on(cb: (s: ConsentState) => void): () => voidSubscribe to consent changes; returns an unsubscribe function.
onon(name: EventName, cb: (payload: unknown) => void): () => voidSee Events below for the full name/payload list.
flushflush(): Promise<void>Forces an immediate outbox flush (also runs automatically on pagehide/tab-hide).
content.slotcontent.slot(name: string, o?: { el?: Element; render?: (item, el) => void }): voidDeclares a display slot in code (markup's [data-optima-slot] works too). Loads the display chunk on first use.
content.refreshcontent.refresh(): voidRe-fetches every declared slot. Runs automatically on load (when a [data-optima-slot] exists) and on every SPA navigation while spa: true — independently of page, since content is URL-targeted. (It stays a no-op until content has been engaged at least once: a route change on a page that never touches content must not be what downloads the display chunk.)
content.registercontent.register(type: string, fn: (item, el) => void): voidRegisters a renderer for a structured item type the built-ins don't cover.
content.fetchcontent.fetch(slot: string): Promise<ContentItem[]>Headless: resolves the slot's raw items without declaring the slot or rendering anything.
forms.renderforms.render(id: string, target: Element | string, o?: { lang?, onSuccess?, onError?, theme?, assertion? }): Promise<{ destroy(): void }>Fetches, builds, mounts, and wires submit for a published form. Loads the forms chunk on first use.
forms.loadforms.load(id: string, o?: { lang?, assertion? }): Promise<{ definition, submit(values) } | FormError>Headless: the definition plus a bound submit(), for a caller-built UI.
forms.pageUrlforms.pageUrl(url: string): stringAppends ?device_id= to a hosted-page (GET /edge/v1/pages/:token/:slug) URL. Synchronous — never loads the forms chunk.
nba.respondnba.respond(nbaId: string, action: "presented"|"accepted"|"postponed"|"rejected"|"realized", extra?: { reason?, reference_id?, value? }): voidReports a customer response to a decided offer; batched to POST /edge/v1/nba/responses. A no-op (logged once) while the operator's edge_nba_responses_enabled kill switch is off.

Every public method is guarded: an internal failure never throws into the host page — it emits an "error" event instead.

Batch size is fixed at 20 and is not configurable client-side. The operator setting edge_max_hits_per_batch cannot go below 20 (Optima refuses a lower value and floors the environment default), and a batch over the gateway's cap is answered 413. On a 400 or 413 for a multi-hit batch the tracker resends only the refused hits, in halves, until the one the gateway refuses is alone; that hit is dropped with an error event and every other hit is delivered. Hits queued behind keep the full batch size.

Linking a logged-in customer

On the public edge the device id is the only identifier a browser has proven it holds. identify({email}) therefore links the device to an EXISTING customer only with a signed assertion minted by your backend. Generate the key's identify secret under Edge › Tracking › SDK keys. The console shows Node/Python/Go helpers.

sig = base64url(HMAC-SHA256(secret, tenant_id + "\n" + sdk_key_token + "\n" + key + "\n" + value + "\n" + exp))

exp is unix seconds, at most 24 h ahead. tenant_id is the tenant in the SDK key token (oek_<tenant>_…), or default for unprefixed tokens. The whole secret string is the HMAC key. Render the assertion into the page after login and call:

optima.identify({ email: user.email }, undefined, { assertion });

Without an assertion, sign-ups with a new email still attach immediately. A returning customer on a new device is linked by your identity rules, or when they confirm a double-opt-in email in the same browser.

Events

Every EventName on(...) can subscribe to, and the shape of the payload each one carries:

EventPayloadFires when
ready{ version: string }Once, on a microtask right after construction — the SDK's own version. Replayed: subscribing after it has already fired invokes your callback immediately with the same payload, so a late on("ready", …) (or one replayed out of the command-queue stub) can never miss it.
track{ accepted: number, dropped: unknown[], hits: unknown[] }A /edge/v1/track batch is accepted (2xx), even if some hits in it were dropped.
identifythe raw response bodyPOST /edge/v1/identify succeeds.
consent:changeConsentState ({v, decisions, decided_at, banner_id, policy, lang})The consent store changes for any reason — consent.set, a Global Privacy Control deny, reset(), another tab's decision (via the storage event), or loading a stored decision. The payload is a frozen copy. Under consent.source: "cmp", TCF/GCM signals do NOT emit this event and do not drive tag gating — map the CMP's decision to purposes with consent.set.
consent:revoked{ purposes: string[] }A previously granted purpose is withdrawn. Scripts already activated by tracker gating keep running — see Consent-gated third-party scripts.
content:loaded{ slot: string, count: number }A slot's GET /edge/v1/content fetch resolves.
content:item{ slot: string, item: ContentItem }A structured item has no registered renderer (so nothing is drawn), or a web_personalization item is about to apply.
content:blocked{ itemId?: string, blockedURI: string, directive: string }The browser reports a securitypolicyviolation for a re-created <script>/<style> node. itemId is undefined when the violation can't be traced back to an Optima-rendered item — see Custom code run and the trust model.
form:submitted{ id: string, dropped: Array<{ key: string; reason: string }>, double_opt_in: boolean }A form submission is accepted (202) or already-submitted (409, treated as success).
tracker:fired{ name: string, kind: "page"|"script"|"pixel"|"html" }A tracker/managed tag ran successfully — see Consent-gated third-party scripts.
tracker:error{ name: string, kind: "page"|"script"|"pixel"|"html", error: unknown }A tag's runner threw; caught, never surfaced as an uncaught exception.
error{ op: string, ... } — op names the failing surface (track, identify, consent, content_refresh, trigger_fire, forms_render, nba, internal, ...)Any internal failure that would otherwise throw into the host page.

NBA responses

Reports what happened to a Next-Best-Action offer your own code decided and displayed, batched to POST /edge/v1/nba/responses. Small enough to ship in the core bundle rather than a lazy chunk.

optima.nba.respond(decision.nba_id, "presented");

acceptButton.addEventListener("click", () => {
  optima.nba.respond(decision.nba_id, "accepted", { value: 29.99 });
});
declineButton.addEventListener("click", () => {
  optima.nba.respond(decision.nba_id, "rejected", { reason: "too_expensive" });
});

nba_id comes from the winning offer in a Campaign decide response (POST /campaign/api/v1/campaigns/{id}/decide or POST /nba/api/v1/campaigns/{id}/decide — outside this SDK's scope, since decisioning is a server-to-server call). Call respond with:

  • "presented" right after you actually show the offer to the visitor.
  • "accepted" / "rejected" / "postponed" on the visitor's response.
  • "realized" normally comes from a back-office system (e.g. an order confirming a redeemed offer), not this SDK — it's part of the same enum for completeness.

extra.reason (a caller-supplied code), extra.reference_id (your own handle for the outcome) and extra.value (a monetary amount) are all optional and independent of action. Batched up to 50 per request, flushed 1s after the first queued response (and immediately on pagehide/tab-hide, same as everything else). A malformed nba_id or an action outside the closed enum is dropped with a console warning (debug: true) and never queued.

The whole endpoint is gated behind an instance-wide operator setting (edge_nba_responses_enabled), off by default: while it's off the SDK gets a 404 for every batch and silently stops sending — no error event, just one debug-only log line the first time. There is nothing to check on your side; ask your Optima operator to enable it if responses aren't showing up.

Storage

KeyWhereHolds
_optima_did / __Host-_optima_didlocalStorage + cookies (400-day, SameSite=Lax)The device id. Without cookieDomain: the localStorage copy is authoritative, then (on https) the __Host-_optima_did cookie, which no other subdomain can set. The plain _optima_did cookie is still written, for Optima-hosted pages, but never read back — a sibling subdomain could plant it. With cookieDomain: the shared _optima_did cookie is authoritative, so every subdomain under that domain is trusted with the visitor's device id. Falls back to memory-only if no store is writable.
_optima_consentcookie + localStorage mirror{v, decisions, decided_at, banner_id, policy, lang}.
_optima_q:<tabId>localStorageThe per-tab hit outbox {hb, did, hits} — capped at 200, oldest dropped first. See the note below.
_optima_sidsessionStorage (per tab)id:last_seen. A 30-minute idle gap starts a new session.
_optima_utmsessionStorageThe landing page's UTM/click-id set (utm_source, utm_medium, utm_campaign, utm_term, utm_content, gclid, fbclid), reused on every page() for the rest of the session.
_optima_seenlocalStorageDisplay frequency/dismiss memory for once/{per_days} rules and every dismissal, keyed by item id: {shown_at, dismissed?}.
_optima_seen_ssessionStorageDisplay frequency memory for session-rule items, keyed by item id.

If neither localStorage nor sessionStorage is writable (Safari private mode, storage disabled by policy), every store transparently falls back to an in-memory twin — the SDK keeps working, nothing survives a page load, and one [optima] warning is logged (debug: true only).

The outbox lives under a per-tab key _optima_q:<tabId> ({hb, did, hits}, where did is the device id the hits were queued under). A tab adopts queues whose heartbeat is older than 5 minutes (a closed or crashed tab) and the 1.2.x key _optima_q. A page releases its queue on pagehide, so the next page loaded in the same tab picks it up immediately (a back/forward-cache restore takes it back). A reset() in another tab discards this tab's queued hits and held identify() calls, and a queue stamped with a previous visitor's device id is dropped rather than adopted. Some hits can be sent twice: a tab frozen for longer than 5 minutes can resend hits its adopter already sent, two tabs that open at the very same instant can both adopt the same orphaned queue (localStorage has no compare-and-swap), and during a rollout a still-running 1.2.x tab keeps rewriting the legacy _optima_q key that new tabs re-adopt; in every case the gateway de-duplicates the copies by message_id.

What reset() clears

reset() is "a different visitor is using this browser now" — the logout call on a shared device. It clears, in this order:

ClearedKey(s)Why it must go
The hit outbox_optima_q:<tabId>This tab's hits queued (or buffered awaiting a consent decision) under the OLD device id must never flush under the new one. Cleared before the id rotates.
The device id_optima_did (cookie + mirror)Rotated to a fresh id — the new visitor is a new device.
Consent state_optima_consent (cookie + mirror)The previous visitor's decisions are not this visitor's.
Session + attribution_optima_sid, _optima_utmA new visitor starts a new session; the old landing attribution does not carry over.
Display frequency + dismiss memory_optima_seen, _optima_seen_sOtherwise the new visitor inherits "already seen, do not show again" from the old one.

reset() emits consent:change with the empty state and drops identify() calls still buffered for the previous visitor.

Not cleared: anything your own page stores, the CMP signal last passed in (consent.setTCF/setGCM/setKeys — re-fed by the CMP itself), and content already rendered on the current page (the next content.refresh()/navigation re-decides it).

On this page