npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@optable/web-sdk

v0.65.4

Published

JavaScript SDK for integrating with an [Optable Data Connectivity Node (DCN)](https://docs.optable.co/) from a web site or web application.

Readme

Optable Web SDK Continuous Integration

JavaScript SDK for integrating with an Optable Data Connectivity Node (DCN) from a web site or web application.

Contents

Installing

The Optable web SDK can be installed as a ES6 compatible npm module using package managers such as pnpm, paired with module bundlers such as webpack or browserify, or can be loaded on a webpage directly by referencing a release build from the page HTML via a <script> tag.

:warning: CORS Configuration: Regardless of how you install the SDK, make sure that the Allowed HTTP Origins setting in the Optable DCN that you are integrating with contains the URL(s) of any web site(s) where the SDK is being used, otherwise your browser may block communication with the DCN.

NPM module

If you're building a web application or want to bundle the SDK functionality with your own JavaScript, then using a package manager like pnpm or npm is the recommended installation method. It pairs nicely with module bundlers such as webpack or browserify and exports types for applications using the typescript language and type checker. To use it simply install the package:

# latest stable release (using pnpm):
pnpm install @optable/web-sdk

# or using npm:
npm install @optable/web-sdk

And then simply import and use the OptableSDK class as shown in the Usage section below.

Script tag

For simple integrations from your web site, you can load the SDK built for the browser from Optable's CDN via a HTML script tag. In production it's advised to lock your SDK bundle to a specific major version identified by vX or a specific minor version with vX.Y, while in development you may want to experiment with latest.

E.g. in development use the following in the <head> block of your HTML page:

<!-- Latest version for development -->
<script async src="https://cdn.optable.co/web-sdk/latest/sdk.js"></script>

Or in production:

<!-- v0 in production -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>

Note the presence of the async attribute, which instructs browsers to load the library asynchronously and not block the page from rendering.

Versioning

The SDK follows Semantic Versioning conventions. You can therefore expect that there will not be any breaking API changes if you are tracking a particular major version.

Domains and Cookies

By default, the Optable SDK makes use of a secure HTTP-only first-party browser cookie in order to anonymously identify browsers via a visitor ID, within the context of any web sites sharing an effective top-level domain plus one (eTLD+1) with the configured DCN host.

For example, if your website runs at www.customer.com or customer.com, then ideally your DCN will be configured to run at dcn.customer.com, and will read/write a first-party cookie at customer.com. The contents of the cookie will not be accessible to any third-party scripts. Finally, the cookie will have the SameSite=Laxattribute so that it is available on the first visit.

:warning: Optable Visitor ID Scope: The visitor ID configured by the Optable DCN will be unique to a browser only within the top-level domain that the DCN shares with the calling web site.

LocalStorage

In cases where it is not practical or possible to configure your DCN to run on the same effective top-level domain plus one (eTLD+1) as your website(s), then the default cookie-based transport that the SDK depends on will not work. Instead, you can configure the SDK to use browser LocalStorage. To switch to the LocalStorage based configuration, simply set the optional cookies parameter to false when creating your SDK instance. For example:

import OptableSDK from "@optable/web-sdk";

const sdk = new OptableSDK({ host: "dcn.customer.com", site: "my-site", cookies: false });

Note that the default is cookies: true and will be inferred if you do not specify the cookies parameter at all.

Using the NPM module

Initialization Configuration (InitConfig)

When creating an instance of OptableSDK, you can pass an InitConfig object to customize its behavior. Below are the available configuration keys and their descriptions:

Required Keys

  • site (string) The identifier (slug) of Javascript SDK source. This must match a configured site in the Optable DCN. Must have properly configure Allowed HTTP Origins.

  • host (string) The hostname of the Optable DCN to which the SDK will connect. All API requests will be directed here.

Optional Keys

  • node (string) If supported by the DCN host, specify the API node for SDK requests. Used in multi-node environments.

  • cookies (boolean, default: true) If true, enables the use of browser cookies for storage.

  • initPassport (boolean, default: true) If true, initializes the user passport (identity mechanism) upon SDK load.

  • initTargeting (boolean, default: false) If true, the SDK will automatically perform a targeting request during initialization and store the response in cache. This ensures the cache is populated with the most up-to-date targeting data as soon as the SDK is loaded.

  • pageContext (PageContextConfig | boolean, default: undefined) When set, enables page context extraction for contextual intelligence. Set to true to use defaults, or pass a PageContextConfig object to customize what is extracted (HTML content, content selector, max lengths). Extracted context is automatically attached to the first witness() call that uses { includeContext: true }.

  • initContextual (boolean | (response: ContextualSegmentsResponse) => void, default: false) If true, the SDK will automatically fire a pageview witness event with full page context during initialization, and also call ctxSegments() to fetch contextual segments for the current page, caching the result on the instance for later use via ctxTargetingKeyValues(). This is the recommended way to enable contextual pageview tracking and contextual targeting without writing custom code. Implies pageContext: true when no pageContext is explicitly configured. When set to a callback function, the SDK does everything true does and invokes the callback with the ContextualSegmentsResponse once it resolves — useful for chaining an ad-server load (e.g. GAM) on the contextual response without making a second ctxSegments() call. The callback is not invoked if the request fails.

  • consent (InitConsent) Defines the consent settings for data collection and processing.

  • readOnly (boolean, default: false) When set to true, puts the SDK in a read-only mode, preventing any data modifications while still allowing API queries.

  • optableCacheTargeting (string, defaults: optable-cache:targeting) Local storage cache key used to store latest targeting response.

  • ois (boolean, default: false) When set to true, participates in the Optable Identity System: the SDK stores the derived OIS ID the DCN returns on the X-Optable-OID response header and replays it on subsequent requests, so the DCN recognizes the browser instead of deriving a new identity each visit. Requires a DCN node with OIS ID derivation enabled and device access consent, so it is a no-op otherwise. The OPTABLE_OID cookie identity is separate and needs no configuration.

These configurations allow fine-tuned control over how the OptableSDK interacts with the Optable DCN, ensuring compatibility with different environments and privacy settings.

Usage Example

To configure an instance of OptableSDK integrating with an Optable DCN running at hostname dcn.customer.com, from a configured web site origin identified by slug my-site, you simply create an instance of the OptableSDK class exported by the @optable/web-sdk module:

import OptableSDK from "@optable/web-sdk";

const sdk = new OptableSDK({ host: "dcn.customer.com", site: "my-site" });

You can then call various SDK APIs on the instance as shown in the examples below. It is also possible to configure multiple instances of OptableSDK in order to connect to different DCNs or reference multiple site slugs.

Security & Privacy

  • All SDK communication with Optable DCNs is done over TLS to ensure data security.
  • The consent option allows compliance with privacy regulations by defining explicit data collection settings.

Identify API

To associate a user's browser with an authenticated identifier such as an Email address, optionally linked with other identifiers, such as your own vendor, publisher, or site-level PPID, you can call the identify API as follows:

const onSuccess = () => console.log("Identify API success!");
const onFailure = (err) => console.warn("Identify API error: ${err.message}");

const emailID = OptableSDK.eid("[email protected]");

// Identify with Email ID (eid):
sdk.identify(emailID).then(onSuccess).catch(onFailure);

// You can optionally link it with your own PPID in the same DCN identification call,
// simply pass a second argument to identify(). A custom PPID value can be sent to identify()
// after it is prepared with the OptableSDK.cid() helper:
const ppid = OptableSDK.cid("some.ppid");
sdk.identify(emailID, ppid).then(onSuccess).catch(onFailure);

The identify() method will asynchronously connect to the configured DCN and send IDs for resolution.

:warning: Client-Side Email Hashing: The OptableSDK.eid() helper will compute the SHA-256 hash of the Email address on the client-side and send the hashed value to the DCN. The Email address is not sent by the browser in plain text.

The frequency of invocation of identify is up to you, however for optimal identity resolution we recommended to call the identify() method on your OptableSDK instance on each page load while the user is authenticated, or periodically such as for example once every 15 to 60 minutes while the user is authenticated and actively using your site.

Profile API

To associate key value traits with a user's browser, for eventual audience assembly, you can call the profile API as follows:

const onSuccess = () => console.log("Profile API success!");
const onFailure = (err) => console.warn("Profile API error: ${err.message}");

const visitorTraits = {
  gender: "M",
  age: 44,
  favColor: "blue",
  hasAccount: true,
};

sdk.profile(visitorTraits).then(onSuccess).catch(onFailure);

The specified visitor traits are associated with the user's browser and can be matched during audience assembly.

Note that visitor traits are key value pairs and have type ProfileTraits:

type ProfileTraits = {
  [key: string]: string | number | boolean;
};

You can also override the main identifier (replacing the Optable Visitor ID) as the second argument of the function. The third argument is to provide additional identifier(s) that you want to associate to that profile.

const onSuccess = () => console.log("Profile API success!");
const onFailure = (err) => console.warn("Profile API error: ${err.message}");

const visitorTraits = {
  gender: "M",
  age: 44,
  favColor: "blue",
  hasAccount: true,
};

const emailID = OptableSDK.eid("[email protected]");
const additionalIDs = [];
additionalIDs.push(OptableSDK.cid("id1"));
additionalIDs.push(OptableSDK.cid("id2", "c2"));

sdk.profile(visitorTraits, emailID, additionalIDs).then(onSuccess).catch(onFailure);

Targeting API

To get the targeting information associated by the configured DCN with the user's browser in real-time, you can call the targeting API as follows:

sdk
  .targeting()
  .then((response) => {
    console.log(`Audience targeting: ${targeting.audience}`);
    console.log(`User targeting: ${targeting.user}`);
  })
  .catch((err) => console.warn(`Targeting API Error: ${err.message}`));

The targeting() function accepts different parameter formats:

Single Identifier (Default)

// Uses the default passport identifier
sdk.targeting();

// Uses a specific identifier
sdk.targeting("some_identifier");

Multiple Identifiers

To target multiple identifiers, use the object parameter format:

// Target multiple identifiers
sdk
  .targeting({ ids: ["identifier1", "identifier2", "identifier3"] })
  .then((response) => {
    console.log(`Multi-targeting response: ${response}`);
  })
  .catch((err) => console.warn(`Targeting API Error: ${err.message}`));

TypeScript Types

The targeting function accepts the following parameter types:

type TargetingRequest = string | { ids?: string[] };

// Examples:
sdk.targeting(); // Uses default "__passport__"
sdk.targeting("some_id"); // Single identifier
sdk.targeting({ ids: ["id1", "id2"] }); // Multiple identifiers

On success, the resulting targeting data is typically sent as part of a subsequent ad call. Therefore we recommend that you either call targeting() before each ad call, or in parallel periodically, caching the resulting targeting data which you then provide in ad calls.

Caching Targeting Data

The targeting API will automatically cache resulting key value data in client storage on success. You can subsequently retrieve the cached key value data as follows:

const cachedTargetingData = sdk.targetingFromCache();
if (cachedTargetingData) {
  console.log(`Audience targeting: ${cachedTargetingData.audience}`);
  console.log(`User targeting: ${cachedTargetingData.user}`);
}

You can also clear the locally cached targeting data:

sdk.targetingClearCache();

Note that both targetingFromCache() and targetingClearCache() are synchronous.

Witness API

To send real-time event data from the user's browser to the DCN for eventual audience assembly, you can call the witness API as follows:

const onSuccess = () => console.log("Witness API success!");
const onFailure = (err) => console.warn("Witness API error: ${err.message}");

const eventProperties = {
  property_one: "some_value",
  property_two: 123,
  property_three: false,
};

sdk.witness("event_type_here", eventProperties).then(onSuccess).catch(onFailure);

The specified event type and properties are associated with the logged event and which can be used for matching during audience assembly.

Note that event properties are key value pairs and have type WitnessProperties:

type WitnessProperties = {
  [key: string]: string | number | boolean;
};

Contextual Pageview Tracking

The SDK can automatically fire a pageview witness event with full page context on initialization. This sends semantic content from the page (title, description, keywords, headings, canonical URL, Open Graph tags, and body text) to the DCN for contextual audience assembly.

Option 1: Automatic (recommended)

Set initContextual: true in your SDK config. The SDK fires the pageview event once after passport initialization, with no additional code required:

const sdk = new OptableSDK({
  host: "dcn.customer.com",
  site: "my-site",
  initContextual: true,
});

You can combine this with pageContext to customize what content is extracted:

const sdk = new OptableSDK({
  host: "dcn.customer.com",
  site: "my-site",
  initContextual: true,
  pageContext: {
    contentSelector: "article",
    maxContentLength: 3000,
  },
});

Option 2: Manual

Enable pageContext in your config and call witness() with { includeContext: true } yourself. Context is attached once per page load (subsequent calls with includeContext: true send no context):

const sdk = new OptableSDK({
  host: "dcn.customer.com",
  site: "my-site",
  pageContext: true,
});

// Fire a pageview with URL property and full page context attached
const url = `${window.location.hostname}${window.location.pathname}`;
sdk.witness("pageview", { url }, { includeContext: true });

To reset the context (e.g. on SPA navigation), call sdk.resetContext() before the next witness() call.

Contextual Segments API

In addition to pageview tracking, the SDK can classify a page URL against one or more contextual taxonomies (such as the IAB Content Taxonomy) and use the result for ad targeting. Call ctxSegments() to fetch the contextual classifications for a URL:

// Classify the current page (defaults to window.location.href):
const response = await sdk.ctxSegments();

// Or classify an explicit URL:
const response = await sdk.ctxSegments("https://example.com/article");

The response has the shape:

type ContextualSegmentsResponse = {
  classifications: {
    categories: { id: string; name: string; score: number; taxonomy: string }[];
    keywords: { keyword: string; prominence: number /* 1 = most prominent */ }[];
    brandSafety: {
      assessed: boolean;
      categories: { name: string; riskLevel: "low" | "medium" | "high" | "floor" | "not_assessed" | "" }[];
    };
    sentiment:
      | { scored: false }
      | { scored: true; id: "positive" | "neutral" | "negative"; name: string; score: number };
    emotions: {
      id: "joy" | "trust" | "fear" | "surprise" | "sadness" | "disgust" | "anger" | "anticipation";
      name: string;
      score: number;
    }[];
    entities: {
      name: string;
      kind: "person" | "organization" | "product" | "location" | "event" | "work_of_art";
      score: number;
    }[];
  };
};

classifications groups results by classification method; the DCN populates only the methods it has enabled. categories and keywords are empty when the DCN never classified the page or does not run that classifier.

Note: The requested URL must already have been classified by the DCN.

Each call to ctxSegments() caches its response on the SDK instance (calling it again refreshes the cache). When initContextual: true, the SDK calls ctxSegments() for you during initialization, so the cache is populated automatically.

Brand safety

ctxBrandSafety() reads the brand-safety classifications off the cached ctxSegments() response, as { assessed, categories }. The categories and the risk tiers follow the Brand Safety Floor + Suitability Framework, which is where the category list and the term floor come from.

Note: Only the page's text is assessed. Embedded media, such as images, video and audio, is not, so a page can come back with nothing flagged and still carry unsafe media. Treat the result as a signal about what the page says, not about everything a visitor sees.

Read assessed before categories. An empty categories list means two opposite things depending on it:

| assessed | categories | Meaning | | ---------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | true | empty | An assessment ran and flagged nothing. | | true | non-empty | An assessment ran: each entry is a category it flagged, at its riskLevel, or a not_assessed category the pass did not cover. Assessed categories with no finding are omitted. | | false | always empty | Nothing is known about this page. The DCN never classified it, the read failed, or this DCN does not run the brand-safety classifier at all. |

Three more things to keep in mind:

  • floor is the most severe tier, not a baseline. The order is low < medium < high < floor, floor being the framework's brand-safety floor, below which inventory should not monetize. not_assessed is not a severity at all; it is the entry's own state.
  • A page assessed clean is not a clearance. The taxonomy enumerates risks, so the classifier can report that a page matches one but never that it is free of them. Neither the response nor these helpers can express "safe".
  • riskLevel can be "". Only when the DCN stored a tier it could not resolve, which is a defect on its side rather than a state of the page. It is in the type because the wire can carry it, so an exhaustive switch has to handle it; treat it as "no usable tier". ctxMaxRiskLevel() already ignores it.

ctxMaxRiskLevel() returns the most severe tier flagged on the page, or null when nothing is flagged, which is convenient for a single gate:

if (sdk.ctxMaxRiskLevel() === "floor") {
  // Do not monetize this page.
}

null comes back in two different situations: an assessment ran and flagged nothing, and nothing is known about the page at all. A gate that must tell those apart reads ctxBrandSafety().assessed as well.

Sentiment

ctxSentiment() reads the page's sentiment (its polarity) off the cached ctxSegments() response:

const sentiment = sdk.ctxSentiment();
if (sentiment.scored) {
  // sentiment.id is "positive", "neutral" or "negative"; sentiment.score is from -1.0 to 1.0.
}

Read scored first. When it is false there is no sentiment for the page: the DCN never classified it, does not run the sentiment classifier, or found nothing to score. id, name and score are then absent, so a missing score is never mistaken for a neutral one.

The label in id is derived by the DCN from the score. Use it as served rather than bucketing score yourself, so your targeting follows the DCN's thresholds.

Emotions

ctxEmotions() reads the emotions the page evokes off the cached ctxSegments() response, as a list of { id, name, score }:

sdk.ctxEmotions();
// => [{ id: "joy", name: "Joy", score: 0.9 }, { id: "sadness", name: "Sadness", score: 0.7 }]

id is one of the eight Plutchik emotions: joy, trust, fear, surprise, sadness, disgust, anger or anticipation. score is from 0.0 to 1.0, and the DCN serves the list highest score first. It is multi-label: a page can evoke several emotions at once, opposites included (a bittersweet story can carry both joy and sadness).

The list is empty when the page has no emotion: the DCN never classified it, does not run the emotion classifier, or nothing reached its cutoff. The DCN applies that cutoff before serving, so use the list as served rather than filtering on score yourself.

Entities

ctxEntities() reads the named entities the page is about off the cached ctxSegments() response, as a list of { name, kind, score }:

sdk.ctxEntities();
// => [{ name: "LeBron James", kind: "person", score: 0.9 }, { name: "Los Angeles Lakers", kind: "organization", score: 0.8 }]

kind is one of person, organization, product, location, event or work_of_art. score is the entity's salience from 0.0 to 1.0, and the DCN serves the list highest score first. The list is empty when the page has no entity: the DCN never classified it or does not run the entity classifier.

Contextual targeting key-values

ctxTargetingKeyValues(taxonomyKeys?, options?) reads the cached ctxSegments() response and builds a Record<string, string[]>, ready to pass to an ad server such as Google Ad Manager via googletag.pubads().setTargeting(). It emits category ids grouped by taxonomy, plus, by default, the page's keywords under ctx_kw, its brand-safety tier under ctx_bs_max, its sentiment label under ctx_sentiment, its emotions under ctx_emotion and its entities under ctx_ent:

sdk.ctxTargetingKeyValues();
// => {
//   "iab_ct_3_1": ["53", "91", "58", "115", "90", "52"],
//   "ctx_kw": ["advertising", "programmatic", "ad tech"],
//   "ctx_bs_max": ["no_flags"],
//   "ctx_sentiment": ["positive"],
//   "ctx_emotion": ["joy", "anticipation"],
//   "ctx_ent": ["lebron james", "los angeles lakers"]
// }

Pass a taxonomyKeys map to rename category keys. Only taxonomies present in the map are emitted (filter + rename), which is useful when you only want to set keys you have configured in your ad server:

sdk.ctxTargetingKeyValues({ iab_ct_3_1: "foo" });
// => { "foo": ["53", ...], "ctx_kw": ["advertising", "programmatic", "ad tech"], "ctx_bs_max": ["no_flags"] }

Keyword values are ordered by prominence (most prominent first), capped to the top 10, and sanitized to GAM's value rules (lowercased, reserved characters stripped, truncated to the 40-character value limit). Use the options argument to change the keyword key (keywordKey), change the cap (maxKeywords), or opt out of keyword key-values by passing an empty keywordKey:

// Rename the keyword key and emit only the top 5 keywords:
sdk.ctxTargetingKeyValues({ iab_ct_3_1: "foo" }, { keywordKey: "kw", maxKeywords: 5 });
// => { "foo": ["53", ...], "kw": ["advertising", "programmatic", "ad tech", "marketing", "audience targeting"], ... }

// Opt out of keyword key-values entirely:
sdk.ctxTargetingKeyValues(undefined, { keywordKey: "" });
// => { "iab_ct_3_1": ["53", "91", "58", "115", "90", "52"], "ctx_bs_max": ["no_flags"] }

Brand safety is emitted by default under ctx_bs_max, carrying the page's most severe flagged tier. It is the same text-only assessment described above, so a line item keyed on it is gating on the page's words and not on its embedded media. Use brandSafetyKey to rename it, or pass an empty brandSafetyKey to opt out, exactly as keywordKey works:

// Rename the brand-safety key:
sdk.ctxTargetingKeyValues(undefined, { brandSafetyKey: "bs" });
// => { "iab_ct_3_1": ["53", ...], "ctx_kw": [...], "bs": ["floor"] }

// Opt out of the brand-safety key-value entirely:
sdk.ctxTargetingKeyValues(undefined, { brandSafetyKey: "" });
// => { "iab_ct_3_1": ["53", ...], "ctx_kw": [...] }

A value is emitted for every state rather than the key being dropped when nothing is flagged:

| State | Value | | ------------------------------- | ------------------------------------------------------- | | A tier was flagged | The most severe one: low, medium, high or floor | | Assessed, nothing flagged | no_flags | | Nothing is known about the page | not_assessed |

The two sentinels exist so a line item can tell them apart. If the key were simply absent when nothing was flagged, "we never looked" and "we looked and flagged nothing" would look identical in GAM, and you could not exclude unassessed inventory without also excluding clean inventory. Note that no_flags is deliberately not named safe: a pass with no finding is not a clearance.

not_assessed is spelled the same as the riskLevel a category carries when the assessment did not cover it. That is deliberate: one word for one idea, "nothing is known here", at two scopes. The scopes cannot be confused, because ctx_bs_max only ever carries a page-level answer.

One difference from keywordKey is worth knowing before you ship: keywords are dropped when the DCN produced none, whereas ctx_bs_max is always present unless you disable it. A DCN that does not run the brand-safety classifier therefore adds ctx_bs_max=not_assessed to every ad request. That is the intended behavior, since it is a state a line item may want to target, but if you do not use brand safety at all, pass an empty brandSafetyKey to keep it out of the request.

The page's sentiment label is emitted by default under ctx_sentiment, as positive, neutral or negative. Like keywords, the key is omitted when the page has no sentiment. The score is never emitted: GAM matches values exactly, so a raw score cannot be range-targeted. Use sentimentKey to rename the key, or pass an empty sentimentKey to opt out:

sdk.ctxTargetingKeyValues(undefined, { sentimentKey: "mood" });
// => { "iab_ct_3_1": ["53", ...], "ctx_kw": [...], "ctx_bs_max": ["no_flags"], "mood": ["positive"] }

sdk.ctxTargetingKeyValues(undefined, { sentimentKey: "" });
// => { "iab_ct_3_1": ["53", ...], "ctx_kw": [...], "ctx_bs_max": ["no_flags"] }

Every one of the page's emotions is emitted by default under ctx_emotion, as a multi-value key (e.g. ctx_emotion=[joy,sadness]). Like keywords, the key is omitted when the page has no emotion, and scores are never emitted. Use emotionKey to rename the key, or pass an empty emotionKey to opt out:

sdk.ctxTargetingKeyValues(undefined, { emotionKey: "feel" });
// => { "iab_ct_3_1": ["53", ...], "ctx_kw": [...], "ctx_bs_max": ["no_flags"], "feel": ["joy", "sadness"] }

sdk.ctxTargetingKeyValues(undefined, { emotionKey: "" });
// => { "iab_ct_3_1": ["53", ...], "ctx_kw": [...], "ctx_bs_max": ["no_flags"] }

The names of the page's entities are emitted by default under ctx_ent, as a multi-value key ordered by score (highest first), capped to the top 10, and sanitized like keywords (so Beyoncé Knowles becomes beyoncé knowles). Like keywords, the key is omitted when the page has no entity. Kinds and scores are never emitted. Use entityKey to rename the key, maxEntities to change the cap, or pass an empty entityKey to opt out:

sdk.ctxTargetingKeyValues(undefined, { entityKey: "who", maxEntities: 1 });
// => { "iab_ct_3_1": ["53", ...], "ctx_kw": [...], "ctx_bs_max": ["no_flags"], "who": ["lebron james"] }

sdk.ctxTargetingKeyValues(undefined, { entityKey: "" });
// => { "iab_ct_3_1": ["53", ...], "ctx_kw": [...], "ctx_bs_max": ["no_flags"] }

A typical Google Ad Manager activation uses a loadGAM() helper:

// Helper to load GAM ads with optional targeting data:
var loadGAM = function (tdata = {}) {
  window.googletag = window.googletag || { cmd: [] };
  googletag.cmd.push(function () {
    for (const [key, values] of Object.entries(tdata)) {
      googletag.pubads().setTargeting(key, values);
    }
    googletag.pubads().refresh();
  });
};

Because ctxTargetingKeyValues() reads the cached response, the instance should be initialized with initContextual: true so the segments are fetched during initialization and the cache is likely populated by the time loadGAM() runs:

loadGAM(optable.instance.ctxTargetingKeyValues());

If you want loadGAM() to run as soon as the contextual segments arrive — without making a second ctxSegments() call — pass a callback to initContextual. The SDK fires the contextual request automatically during initialization and invokes the callback with the response, populating the cache before ctxTargetingKeyValues() reads from it:

const sdk = new OptableSDK({
  host: "dcn.customer.com",
  site: "my-site",
  initContextual: function (response) {
    loadGAM(sdk.ctxTargetingKeyValues());
  },
});

If you are not using initContextual at all, fetch the segments explicitly and call loadGAM() once ctxSegments() resolves (falling back to an untargeted load on error):

optable.cmd.push(function () {
  optable.instance
    .ctxSegments()
    .then(loadGAM)
    .catch((err) => {
      loadGAM();
    });
});

You can also rename and allow-list the GAM keys by passing a taxonomyKeys map to ctxTargetingKeyValues() (only the taxonomies present in the map are emitted):

// Emit only the "iab_ct_3_1" taxonomy, under the GAM key "ctx_iab":
loadGAM(optable.instance.ctxTargetingKeyValues({ iab_ct_3_1: "ctx_iab" }));

When GAM is the only consumer, setContextualTargetingInGAM(sdk, taxonomyKeys?, options?, url?) wraps the fetch-convert-push sequence into one call: it fetches the segments, converts them with ctxTargetingKeyValues() (forwarding taxonomyKeys and options), and queues a googletag.pubads().setTargeting() call per key — creating the googletag command queue if the page has none yet. Pass url to classify a route other than the current location, as in an SPA:

import { setContextualTargetingInGAM } from "@optable/web-sdk/lib/dist/addons/gpt";

await setContextualTargetingInGAM(sdk, { iab_ct_3_1: "ctx_iab" });

Nothing is queued when the page yields no key-values, and the call never rejects: a failed classification is logged under optableDebug and ads load untargeted rather than an unhandled rejection reaching a page that fired this without awaiting. For the full behaviour, including the extra request when the SDK is configured with initContextual, see the GPT addon README.

Using a script tag

For each SDK release, a webpack-generated browser bundle targeting the browsers list described by pnpm dlx browserslist "> 0.25%, not dead" can be loaded on a website via a script tag.

As described in the Installation section above, the recommended way to load the SDK via script tag is asynchronously using the async attribute, to avoid blocking page rendering.

Option 1: Automatic Initialization

If you want to avoid manually instantiating the SDK, you can define the instance_config before loading the SDK bundle. When the script loads, it will automatically initialize the SDK using this configuration and assign the instance to window.optable.instance.

<!-- Define configuration before loading the SDK -->
<script>
  window.optable = { cmd: [], instance_config: { host: "dcn.customer.com", site: "my-site" } };
</script>

<!-- Asynchronously load the SDK -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>

<!-- Optionally identify a client-side user after the page loads -->
<script>
  window.addEventListener("DOMContentLoaded", () => {
    optable.cmd.push(() => {
      const emailInput = document.getElementById("email");
      optable.instance.identify(optable.SDK.eid(emailInput.value)).then(() => {
        console.log("Identify API Success!");
      });
    });
  });
</script>

Option 2: Manual Initialization with Commands Queue

You can also manually initialize the SDK using the cmd queue. This approach is useful if you prefer full control or are loading the config dynamically.

<!-- Asynchronously load the SDK as early as possible: -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>

<!-- Later in the page: -->
<script>
  // Setup stub that will get replaced once the SDK get loaded
  window.optable = window.optable || { cmd: [] };
  optable.cmd.push(() => {
    // At this point optable.SDK is available and can be used to create a new sdk instance.
    // That instance can be stored anywhere for later referencing.
    // One option is to keep it within the global optable object space.
    optable.instance = new optable.SDK({ host: "dcn.customer.com", site: "my-site" });
  });
  // Now configure DOM content loaded event listener to dispatch identify() API:
  window.addEventListener("DOMContentLoaded", (event) => {
    optable.cmd.push(() => {
      // Fetch input on document load
      const emailInput = document.getElementById("email");
      optable.instance.identify(optable.SDK.eid(emailInput.value)).then(() => console.log("Identify API Success!"));
    });
  });
</script>

<input type="text" id="email" value="[email protected]" />

Integrating PrebidJS analytics

The OptablePrebidAnalytics addon hooks into Prebid.js auction events (auctionEnd and bidWon) and sends auction analytics to the Optable DCN via the witness API. It reports per-bidder EID coverage, bid outcomes, and optional custom key-value pairs, enabling you to measure the impact of Optable targeting on your Prebid auctions.

Script tag

When the SDK is loaded via a <script> tag, OptablePrebidAnalytics is available as window.optable.OptablePrebidAnalytics.

<!-- Optable SDK async load: -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>

<!-- Prebid.js async load: -->
<script async src="prebid.js"></script>

<script>
  window.optable = window.optable || { cmd: [] };
  window.pbjs = window.pbjs || { que: [] };

  optable.cmd.push(function () {
    optable.instance = new optable.SDK({ host: "dcn.customer.com", site: "my-site" });

    const analytics = new optable.OptablePrebidAnalytics(optable.instance, {
      analytics: true,
      tenant: "my_tenant", // Replace with your Optable tenant name
    });

    analytics.hookIntoPrebid(window.pbjs);
  });
</script>

NPM package

When using the SDK as an NPM package, import OptablePrebidAnalytics directly from the addon module:

import OptableSDK from "@optable/web-sdk";
import OptablePrebidAnalytics from "@optable/web-sdk/lib/addons/prebid/analytics";

const sdk = new OptableSDK({ host: "dcn.customer.com", site: "my-site" });

const analytics = new OptablePrebidAnalytics(sdk, {
  analytics: true,
  tenant: "my_tenant", // Replace with your Optable tenant name
});

analytics.hookIntoPrebid(window.pbjs);

For extended configuration options such as sampling, debug mode, and custom analytics data, see the Prebid analytics addon README.

Integrating GAM360

The Optable Web SDK can fetch targeting data from a DCN and map it to be sent to Google Ad Manager 360 ad server account for real-time targeting. It's also capable of intercepting advertising events from the Google Publisher Tag and logging them to a DCN via the witness API.

Targeting key values

Loading the Optable SDK via a script tag on a web page which also uses the Google Publisher Tag, we can further extend the targeting example above to show an integration with a Google Ad Manager 360 ad server account.

It's suggested to load the GAM banner view with an ad even when the call to your DCN targeting() method raises an exception, as shown in the example below:

<!-- Optable SDK async load: -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>

<!-- Google Publisher Tag (GPT) async load: -->
<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>

<!-- Optable SDK, GPT, and targeting data initialization: -->
<script>
  window.optable = window.optable || { cmd: [] };
  window.googletag = window.googletag || { cmd: [] };

  // Init Optable SDK via command:
  optable.cmd.push(function () {
    optable.instance = new optable.SDK({ host: "dcn.customer.com", site: "my-site" });
  });

  // Init GPT and disable initial ad load so that we can load targeting data first:
  googletag.cmd.push(() => {
    adSlot = googletag
      .defineSlot(...)
      .addService(googletag.pubads());

    googletag.pubads().enableSingleRequest();
    googletag.pubads().disableInitialLoad();
    googletag.enableServices();
  });
</script>

<!-- Placeholder DIV for adSlot... referenced by googletag.defineSlot() above: -->
<div id="div-gpt-ad-12345-0"></div>

<script>
  // Helper to load GAM ads with optional targeting data:
  var loadGAM = function (tdata = {}) {
    // Sets up page-level targeting in GAM360 GPT:
    window.googletag = window.googletag || { cmd: [] };
    googletag.cmd.push(function () {
      for (const [key, values] of Object.entries(tdata)) {
        googletag.pubads().setTargeting(key, values);
      }

      // Explicitly calls refresh() on googletag:
      googletag.pubads().refresh();
    });
  };

  // Call Optable DCN for targeting data and setup GPT page-level targeting, then
  // explicitly refresh GPT ads.
  //
  // NOTE: We load and refresh GPT ads without targeting data when there is an exception,
  // so that GAM ads are always loaded.
  optable.cmd.push(function () {
    optable.instance
      .targetingKeyValues()
      .then(loadGAM)
      .catch((err) => {
        loadGAM();
      });
  });

  googletag.cmd.push(() => {
    googletag.display(adSlot);
  });
</script>

Note the use of googletag.pubads().disableInitialLoad() in the above example. This will disable GAM ads from loading until the call to googletag.pubads().refresh() from the loadGAM() function.

Targeting key values from local cache

It's also possible to avoid disabling of the initial ad load by using the SDK's targetingKeyValuesFromCache() method instead as in the following example:

<!-- Optable SDK async load: -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>

<!-- Google Publisher Tag (GPT) async load: -->
<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>

<!-- Optable SDK, GPT, and targeting data initialization: -->
<script>
  window.optable = window.optable || { cmd: [] };
  window.googletag = window.googletag || { cmd: [] };

  // Init Optable SDK via command:
  optable.cmd.push(function () {
    optable.instance = new optable.SDK({ host: "dcn.customer.com", site: "my-site" });
  });

  // Init GPT and disable initial ad load so that we can load targeting data first:
  googletag.cmd.push(() => {
    adSlot = googletag
      .defineSlot(...)
      .addService(googletag.pubads());

    // Attempt to load Optable targeting key values from local cache, then load GAM ads:
    optable.cmd.push(function () {
      const tdata = optable.instance.targetingKeyValuesFromCache();
      for (const [key, values] of Object.entries(tdata)) {
        googletag.pubads().setTargeting(key, values);
      }

      googletag.pubads().enableSingleRequest();
      googletag.enableServices();
    });
  });
</script>

<!-- Placeholder DIV for adSlot... referenced by googletag.defineSlot() above: -->
<div id="div-gpt-ad-12345-0"></div>

<script>
  // Call Optable DCN for targeting data which will update the local cache on success.
  optable.cmd.push(function () {
    optable.instance.targeting().catch((err) => {
      // Maybe log error
    });
  });

  googletag.cmd.push(() => {
    googletag.display(adSlot);
  });
</script>

Note that the above example fetches locally cached targeting key values and calls googletag.pubads().setTargeting() with them. Note also that the usual targeting() call is done as well, though its return value is ignored. This ensures that the local targeting cache is kept updated as activations are modified.

Witnessing ad events

To automatically capture GPT SlotRenderEndedEvent and ImpressionViewableEvent and send log data to your DCN using the witness API, simply install GPT event listeners on the SDK instance as follows:

<!-- Optable SDK async load: -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>
<script>
  window.optable = window.optable || { cmd: [] };
  optable.cmd.push(function () {
    optable.instance.installGPTEventListeners();
  });
</script>

Advanced usage: You can customize which GPT events are registered and which event properties to include, per event type, by passing an options object:

// Only listen to impressionViewable and emit only `slot_element_id`
optable.instance.installGPTEventListeners({ impressionViewable: ["slot_element_id"] });

// For slotRenderEnded, emit all properties. For impressionViewable, emit only the listed properties.
optable.instance.installGPTEventListeners({
  slotRenderEnded: "all",
  impressionViewable: ["slot_element_id", "is_empty"],
});

The value for each event key can be "all" (to include all witness properties) or an array of property names from the set below (as mapped by the SDK):

advertiser_id, campaign_id, creative_id, is_empty, line_item_id, service_name, size, slot_element_id, source_agnostic_creative_id, source_agnostic_line_item_id. If no argument is provided, the default behavior is unchanged and both slotRenderEnded and impressionViewable are captured with all properties.

Note that you can call installGPTEventListeners() as many times as you like on an SDK instance, there will only be one set of registered event listeners per instance. Each SDK instance can register its own GPT event listeners.

A working example of both targeting and event witnessing is available in the demo pages.

GAM Secure Signals

The Optable Web SDK provides a method installGPTSecureSignals to pass user-defined signals to Google Ad Manager (GAM) Secure Signals. The method supports an array of objects, each representing a unique signal to pass to GAM, for example:

<!-- Optable SDK async load: -->
<script async src="https://cdn.optable.co/web-sdk/latest/sdk.js"></script>
<script>
  const mySecureSignals = [];
  mySecureSignals.push({
    // Name of the provider
    provider: "uidapi.com",
    // ID to use in the Secure Signal
    value: "uid2_token_goes_here",
  });
  window.optable = window.optable || { cmd: [] };
  optable.cmd.push(function () {
    optable.instance.installGPTSecureSignals(mySecureSignals);
  });
</script>

Please refer to the list of approved Secure Signal providers. Please refer to the provider's integration documentation for the exact provider name and value to pass as a signal.

To build the signals from cached EIDs instead of by hand, secureSignalsFromEids(eids, filter?) builds one { provider, id } pair per EID source — GPT keys secure signals by provider, so the first EID that passes the filter and carries a non-empty uid wins its source — optionally filtered by sources, inserters or matchers (an empty or missing list means no constraint on that field).

The signals come from the last cached targeting response, so a first visit installs none until targeting() has resolved once.

With the npm package:

import { secureSignalsFromEids } from "@optable/web-sdk/lib/dist/core/secure-signals";

const eids = sdk.targetingFromCache()?.ortb2?.user?.eids ?? [];
sdk.installGPTSecureSignals(...secureSignalsFromEids(eids, { sources: ["uidapi.com"] }));

With the SDK loaded from a script tag, the helper is available under optable.utils:

<script async src="https://cdn.optable.co/web-sdk/latest/sdk.js"></script>
<script>
  window.optable = window.optable || { cmd: [] };
  optable.cmd.push(function () {
    const eids = optable.instance.targetingFromCache()?.ortb2?.user?.eids ?? [];
    optable.instance.installGPTSecureSignals(...optable.utils.secureSignalsFromEids(eids, { sources: ["uidapi.com"] }));
  });
</script>

You can verify the signal was correctly passed to GAM by searching for its value cached in localStorage under the key _GESPSK-<provider_name>.

Integrating Prebid

The Optable Web SDK can integrate with Prebid.js to provide targeting data for real-time bidding. There are three main ways to integrate:

Open Pair ID Prebid Module

For publishers who only need to transmit Optable's cleanroom PAIR IDs in the bid stream, the Open Pair ID Prebid module provides a simple integration method. This approach is recommended when PAIR ID transmission is your only requirement.

Here's how to integrate it:

<!-- Optable SDK async load: -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>

<!-- Prebid.js lib async load: -->
<script async src="prebid.js"></script>

<!-- Initialize Optable SDK and cache PAIR identifiers: -->
<script>
  window.optable = window.optable || { cmd: [] };
  // Init Optable SDK via command:
  optable.cmd.push(function () {
    optable.instance = new optable.SDK({ host: "dcn.customer.com", site: "my-site" });
  });
  // Call targeting() to cache PAIR identifiers
  optable.cmd.push(function () {
    optable.instance.targeting().catch((err) => {
      // Maybe log error
    });
  });
</script>

<!-- Configure Prebid.js to use the cached PAIR identifiers: -->
<script>
  window.pbjs = window.pbjs || { que: [] };
  pbjs.que.push(function () {
    // Configure the Open Pair Prebid module to look for our cached PAIR identifiers
    pbjs.mergeConfig({
      userSync: {
        userIds: [
          {
            name: "openPairId",
            inserter: "<PUBLISHER DOMAIN>", // Replace with your publisher domain
            matcher: "optable.co",
            params: {
              optable: { storageKey: "_optable_pairId" },
            },
          },
        ],
      },
    });
    // Request bids - the Open Pair module will automatically include the PAIR identifiers
    pbjs.requestBids({
      bidsBackHandler: function (bids) {
        // Handle bids
      },
      timeout: 3000,
    });
  });
</script>

Key points about this integration:

  • It only transmits PAIR IDs, making it simpler than the full ORTB2 integration
  • The PAIR IDs are automatically picked up from the Optable SDK's local storage
  • No additional configuration is needed beyond this snippet
  • It's compatible with all bidders that support the Open Pair ID module

If you need to transmit additional targeting data or have more control over what information is sent to bidders, you should use the ORTB2 integration method described in the next section.

Seller Defined Audiences

The HTML code snippet below shows how prebidORTB2FromCache() can be used to retrieve targeting data from the LocalStorage administered by the Optable SDK, and write Seller Defined Audiences (SDA) into prebid.js which is also loaded into the page, using pbjs.mergeConfig({ ortb2: ortb2 }) as documented in the prebid.js first party data documentation. The targeting() API is also called in order to retrieve and locally store the latest matching activations from dcn.customer.com/my-site.

Note that prebid.js bidder adapters can subsequently retrieve the data from the global config.

An example of how to install the SDA data through pbjs is shown below. The districtMDMX bidder adapter is referenced, though the integration would look similar with any SDA compatible bidder adapters.

For a working demo showing a pbjs and GAM integrated together, see the demo pages section below.

<!-- Optable SDK async load: -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>

<!-- Prebid.js lib async load: -->
<script async src="prebid.js"></script>

<!-- Initialize Optable SDK, and targeting call early when possible: -->
<script>
  window.optable = window.optable || { cmd: [] };

  // Init Optable SDK via command:
  optable.cmd.push(function () {
    optable.instance = new optable.SDK({ host: "dcn.customer.com", site: "my-site" });
  });

  // Call Optable DCN for targeting data which will update the local cache on success.
  optable.cmd.push(function () {
    optable.instance.targeting().catch((err) => {
      // Maybe log error
    });
  });
</script>

<!-- Placeholder DIV for adSlot -->
<div id="div-gpt-ad-12345-0"></div>

<!-- Initialize prebid.js -->
<script>
  window.pbjs = window.pbjs || { que: [] };

  var PREBID_TIMEOUT = 3000;
  var FAILSAFE_TIMEOUT = 5000;

  var adUnits = [
    {
      code: "/22081946781/web-sdk-demo/box-ad",
      mediaTypes: {
        banner: {
          sizes: [
            [250, 250],
            [300, 250],
            [200, 200],
          ],
        },
      },
      bids: [
        {
          bidder: "districtmDMX",
          params: {
            dmxid: "/22081946781/web-sdk-demo/box-ad",
            memberid: "102034",
          },
        },
      ],
    },
  ];

  function initAdserver() {
    if (pbjs.initAdserverSet) return;
    pbjs.initAdserverSet = true;
    // ... etc ...
  }

  pbjs.que.push(function () {
    optable.cmd.push(function () {
      const ortb2 = optable.instance.prebidORTB2FromCache();
      pbjs.mergeConfig({ ortb2: ortb2 });

      // ... etc ...

      pbjs.requestBids({
        bidsBackHandler: initAdserver,
        timeout: PREBID_TIMEOUT,
      });
    });
  });

  setTimeout(function () {
    initAdserver();
  }, FAILSAFE_TIMEOUT);
</script>

Custom key values

For bidder adapters that do not support SDA, but that do support targeting private marketplace deals to key values, you can use a similar approach to the Google Ad Manager integration with key values from local cache. For example, for the IX bidder adapter and IX bidder-specific FPD, you can encode the targeting key values as shown below:

<script>
  // ...
  // prior to pbjs.requestBids():
  pbjs.que.push(function () {
    optable.cmd.push(function () {
      const tdata = optable.instance.targetingKeyValuesFromCache();
      var fpd = {};

      /*
       * Flatten targeting key=values from Optable SDK targeting cache
       * into a custom key value object, such that a key K with values
       * V1, V2, ... in the Optable SDK targeting cache is transformed
       * to look like:
       * {
       *   K + V1: 1,
       *   K + V2: 1,
       *   ...
       * }
       *
       * Note that + above indicates string concatenation.
       *
       * Optable DCNs have K configured to "optable" by default, so the
       * above would result in a custom key value "optable_audienceKeyword=1"
       * being set whenever the visitor is matched to the activated audience
       * specified by audienceKeyword by the DCN.
       */
      for (const [key, values] of Object.entries(tdata || {})) {
        for (const seg of values) {
          fpd[key + seg] = "1";
        }
      }

      pbjs.mergeConfig({
        ix: {
          firstPartyData: fpd,
        },
      });
    });

    pbjs.requestBids(...);
  });
</script>

RTD module

buildRTD() builds the config behind the Optable RTD provider, which merges cached EIDs into the auction's ortb2Fragments with per-source bidder routing and merge strategies. With waitForTargeting: true it waits — bounded by Prebid's auctionDelay — for the targeting response when the cache has no EIDs yet, and an isControlGroup callback gates serving for split tests:

import { buildRTD } from "@optable/web-sdk/lib/dist/core/prebid/rtd";

const rtd = buildRTD({ waitForTargeting: true, isControlGroup: () => isControlGroup });

For the auction flow and the full option list, see the RTD module README.

Identifying visitors arriving from Email newsletters

If you send Email newsletters that contain links to your website, then you may want to automatically identify visitors that have clicked on any such links via their Email address.

Insert oeid into your Email newsletter template

To enable automatic identification of visitors originating from your Email newsletter, you first need to include an oeid parameter in the query string of all links to your website in your Email newsletter template. The value of the oeid parameter should be set to the SHA256 hash of the lowercased Email address of the recipient. For example, if you are using Braze to send your newsletters, you can easily encode the SHA256 hash value of the recipient's Email address by setting the oeid parameter in the query string of any links to your website as follows:

oeid={{${email_address} | downcase | sha2}}

The above example uses various personalization tags as documented in Braze's user guide to dynamically insert the required data into an oeid parameter, all of which should make up a part of the destination URL in your template.

Call tryIdentifyFromParams SDK API

On your website destination page, you can call a helper method provided by the SDK which will attempt to parse and validate a given query string parameter as EID (defaults to oeid), when found, it will automatically trigger a call to Optable's identify API.

For example:

<!-- Optable SDK async load: -->
<script async src="https://cdn.optable.co/web-sdk/v0/sdk.js"></script>
<script>
  window.optable = window.optable || { cmd: [] };
  optable.cmd.push(function () {
    optable.instance = new optable.SDK({ host: "dcn.customer.com", site: "my-site" });

    // Identify using a valid EID (email SHA256) "oeid" query string parameter.
    optable.instance.tryIdentifyFromParams();

    // Or if the EID is being passed through a "email_sha" query string
    // like https://www.mysite.com?origin=newsletter&email_sha=abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789&foo=bar
    // optable.instance.tryIdentifyFromParams("email_sha");

    // Optionally, you can provide a custom prefix as the second argument to tryIdentifyFromParams.
    // This prefix will be used in the constructed identifier, allowing you to capture a value
    // from the URL parameter even if it may not be a SHA256-hashed email.
    // For example, optable.instance.tryIdentifyFromParams("email_md5", "c2");
    // You can find a list of supported prefixes at https://docs.optable.co/optable-documentation/dmp/reference/identifier-types#type-prefixes
  });
</script>

Identify and tokenize (hashed email)

identifyAndTokenize(sdk, id, options?) is the publisher-facing identity entry point: it normalizes a hashed email (bare ids get the e: prefix; already-prefixed and utiq: ids pass through), always calls identify, and — outside the control group — tokenizes the id and merges the resulting EIDs into the rolling cache, announcing the write with the optable-targeting:change event. It runs once per id per session (OPTABLE_TOKENIZE_DONE holds a fingerprint of the id, never the id itself, so signing in as someone else in the same tab resolves them), re-runnable with the optableForceTokenize flag, and the guard resets on error so a failed tokenize can retry:

import { identifyAndTokenize } from "@optable/web-sdk/lib/dist/core/identify-tokenize";

window.optable.identifyAndTokenize = (id) => identifyAndTokenize(sdk, id, { isControlGroup: () => isControlGroup });

options also controls the cache write: cacheKey (default OPTABLE_RESOLVED), and maxUidsPerEid and nonOverridingMatchers, both forwarded to mergeCache. Pass nonOverridingMatchers when tokenize runs alongside a targeting call that skipped the first-party matcher, so a first-party EID does not displace a third-party one already held on the same source:

identifyAndTokenize(sdk, id, { isControlGroup: () => isControlGroup, nonOverridingMatchers: ["mysite.com"] });

The returned { merged, staleUid2s } (null when skipped) lets the caller chain UID2 refreshes on the merged cache.

Passport and Visitor ID

The Optable DCN issues a passport (a signed JWT) that is cached in browser localStorage. The passport encodes a unique visitor ID that the DCN uses to anonymously identify the browser. Both values can be read synchronously from the SDK:

const passport = sdk.passport(); // string | null — the raw JWT as stored in localStorage
const visitorId = sdk.visitorId(); // string | null — the `id` claim decoded from the passport

Both methods return null until the passport has been populated in localStorage. By default (initPassport: true) the SDK triggers a /config call at construction time, and the DCN response populates the passport.

If the returned value is null, the SDK logs a one-time warning per instance to help diagnose the cause. The two expected reasons for a null return are:

  1. The method was called before the passport was cached (e.g. before sdk.site() resolved).
  2. The DCN is configured to not echo the passport in response bodies, in which case the client-side cache is never populated.

Optable Identity System (OIS)

The Optable Identity System is a cross-tenant identity system. On a DCN node configured to use it, the OIS ID replaces the visitor ID as the canonical profile identifier for collected events — the DCN makes that substitution itself, based on the node's identity selector.

An OIS-enabled node recognizes a browser two ways, and only one of them involves the SDK.

The cookie identity needs no SDK code

The DCN sets an OPTABLE_OID cookie and the browser attaches it to every call on its own, so identify() and profile() are already attributed to it with nothing enabled client-side.

That cookie is HttpOnly and scoped to optable.co, which has two conse