npm.io
1.142.0 • Published 5d ago

@sesamy/sesamy-js

Licence
—
Version
1.142.0
Deps
7
Size
1.0 MB
Vulns
0
Weekly
0

sesamy-js

The Sesamy browser JavaScript API.

@sesamy/sesamy-js is the publisher-side runtime that powers paywalls, authentication, content gating, and analytics on Sesamy-integrated sites. It exposes a single window.sesamy object (the namespace is configurable) with ~30 namespaced services backed by the Sesamy API, plus ready-made handlers for URL/hash triggers, content selectors, DOM transforms, consent, and DCA (Capsule) decryption.

Installation

npm install @sesamy/sesamy-js
# or
pnpm add @sesamy/sesamy-js

The package ships several entry points so you can pick the build that fits your integration:

Import Purpose
@sesamy/sesamy-js Core library — init() and the SesamyAPI surface (ESM/CJS).
@sesamy/sesamy-js/auth0-plugin Auth0 SPA auth plugin. Required for SPA login unless using BFF cookies.
@sesamy/sesamy-js/capsule-plugin Capsule (DCA) decryption plugin. Required when capsule.enabled is true.
@sesamy/sesamy-js/bootstrap Tiny inline loader (sesamyBootstrap + renderBootstrapScript) that orchestrates the script chain and prefetches /auth/userinfo.

Pre-built IIFE bundles for classic <script> tags are also published:

  • dist/sesamy-js.iife.js — core, all-in-one (loadable directly without ESM).
  • dist/auth0-plugin.iife.js — auth plugin as an IIFE that registers window.auth0Plugin.createAuth0Plugin.
  • dist/capsule-plugin.iife.js — capsule plugin as an IIFE that registers window.capsulePlugin.createCapsulePlugin.
  • dist/bootstrap.iife.js — bootstrap loader as an IIFE.

Publishers using Sesamy's hosted scripts host typically don't reference these files directly; instead they let the bootstrap loader resolve them from https://scripts.sesamy.com/s/{clientId}/{name}/{version}.js.

Quick start

The recommended way to embed sesamy-js on a publisher site is via the bootstrap loader. It downloads the auth/capsule plugins, the components package, and the core bundle in parallel (in the right execution order) and prefetches /auth/userinfo so the user's session is hydrated by the time the core finishes loading.

Drop this in <head>:

<script type="application/json" id="sesamy-js">
  {
    "clientId": "your-client-id",
    "environment": "prod"
  }
</script>
<script src="https://scripts.sesamy.com/s/your-client-id/bootstrap/auto.js"></script>

The bootstrap script auto-detects the <script id="sesamy-js"> config element and pulls forward clientId, environment, version, src, plugin-version overrides, fallback options, and the plugin/component flags below. No extra inline call is needed.

Once the chain finishes, sesamy-js is reachable as window.sesamy (or the namespace you set in api.namespace) and the sesamyJsReady event fires.

window.addEventListener('sesamyJsReady', () => {
  console.log('Authenticated?', window.sesamy.auth.isAuthenticated());
});

Integration modes

sesamy-js supports several distinct integration shapes. Pick the one that matches your stack — they are not mutually exclusive (e.g. you can use the bootstrap loader together with BFF cookie auth).

Use when: you embed sesamy-js on a server-rendered publisher site and want a single <script> in <head> that handles everything. Sets window.__sesamyBoot with a parallel userinfo prefetch promise that the core reuses, eliminating a round-trip from the critical path.

The bootstrap loader (@sesamy/sesamy-js/bootstrap) ships a sesamyBootstrap(options) function that:

  1. Optionally fetches /auth/userinfo in parallel with the bundle download when the sesamy_is_authenticated=true hint cookie is present (or skips if skipAuthPrefetch is true).
  2. Injects the auth0-plugin, capsule-plugin (if enabled), sesamy-components, and the sesamy-js core as <script async=false> tags so they execute in order while downloading in parallel.
  3. Falls back to fallbackSrc if the primary core never installs window[namespace] within fallbackTimeoutMs (default 3000ms).

Auto-run from the config element:

<script type="application/json" id="sesamy-js">
  { "clientId": "demo", "environment": "prod" }
</script>
<script src="https://scripts.sesamy.com/s/demo/bootstrap/auto.js"></script>

Or call it manually (useful from SSR templates, before the config element is in the DOM):

<script>
  sesamyBootstrap({
    clientId: 'demo',
    environment: 'prod',
    version: 'stable',
    fallbackSrc: 'https://scripts-fallback.sesamy.com/.../sesamy-js.iife.js',
    debug: false,
  });
</script>

For server-rendered pages, use renderBootstrapScript() to serialise the function plus its options into an inline script body:

import { renderBootstrapScript } from '@sesamy/sesamy-js/bootstrap';

const inline = renderBootstrapScript({
  clientId: 'demo',
  environment: 'prod',
  skipAuthPrefetch: false,
});
// emit `<script>${inline}</script>` in your HTML response

BootstrapOptions

Option Type Default Purpose
clientId string — Resolves script chain URLs to https://scripts.sesamy.com/s/{clientId}/{name}/{version}.js. Required unless src is set.
version string 'auto' Version channel served by scripts-host. auto lets the server pick from your publisher config (falling back to stable); naming a tag (stable, beta, latest, 1.2.3) is obeyed verbatim.
componentsVersion string version Per-entry override for sesamy-components.
auth0PluginVersion string version Per-entry override for auth0-plugin.
capsulePluginVersion string version Per-entry override for capsule-plugin.
src string — Override the core bundle URL. Disables plugin/component chaining (escape hatch for self-contained bundles).
environment 'dev' | 'prod' 'prod' Origin to resolve clientId against (scripts.sesamy.com vs scripts.sesamy.dev).
fallbackSrc string — Secondary bundle URL loaded if the core fails or doesn't install window[namespace] in time.
fallbackTimeoutMs number 3000 Timeout before the fallback fires.
apiBaseUrl string inferred Base URL for the userinfo prefetch. When unset, falls back to auth.baseUrl from the page config (so the prefetch matches the runtime BFF plugin) and then to same-origin.
namespace string 'sesamy' Window namespace the core installs onto.
skipAuthPrefetch boolean false Skip the /auth/userinfo prefetch (e.g. when injecting the id-token via SSR).
skipComponents boolean false Skip loading sesamy-components.
loadAuth0Plugin boolean inferred Force auth0-plugin loading on/off. Default: load unless auth.useHttpCookies === true in the config element.
loadCapsulePlugin boolean inferred Force capsule-plugin loading on/off. Default: load when capsule.enabled === true in the config element.
debug boolean false Emit [sesamy-boot] log lines for chain decisions, prefetch source, load/error events, and fallback triggers.

Auto-init from <script id="sesamy-js">

Use when: you've already loaded the core bundle some other way (custom CDN, self-host) and just want sesamy-js to bootstrap itself from a JSON config block.

The core looks for a <script type="application/json" id="sesamy-js"> element and, if found, calls init() with the parsed config. Only clientId is required.

<script type="application/json" id="sesamy-js">
  {
    "clientId": "demo",
    "environment": "prod",
    "auth": { "domain": "auth.example.com" },
    "api": { "namespace": "sesamy" }
  }
</script>
<script src="/path/to/sesamy-js.iife.js"></script>

Programmatic init(config)

Use when: your app is an SPA that already manages its own bootstrapping (e.g. you import sesamy-js from npm and want full control over when it initialises).

import { init } from '@sesamy/sesamy-js';

const sesamy = await init({
  clientId: 'demo',
  vendorId: 'demo',
  environment: 'prod',
  auth: { domain: 'auth.example.com' },
});

if (await sesamy.auth.isAuthenticated()) {
  const profile = await sesamy.profile.get();
}

init() returns the SesamyAPI object and also installs it on window[namespace] for parity with the auto-init path. Pass awaitAllServices: true in the config to make the returned promise wait for analytics, auth, content, transforms, and capsule to finish initialising; the default is to return early and run those services in the background.

You can also pass plugins explicitly instead of relying on window.auth0Plugin / window.capsulePlugin auto-detection:

import { init } from '@sesamy/sesamy-js';
import { createAuth0Plugin } from '@sesamy/sesamy-js/auth0-plugin';
import { createCapsulePlugin } from '@sesamy/sesamy-js/capsule-plugin';

await init(config, {
  authPlugin: createAuth0Plugin(),
  capsulePlugin: createCapsulePlugin(),
});

Use when: your backend already terminates Sesamy auth (the API proxy's Token Handler) and you want sesamy-js to use HttpOnly cookies instead of the SPA Auth0 plugin. The auth0-plugin is not loaded; login/logout/refresh go through /auth/login, /auth/callback, /auth/logout, and /auth/userinfo on the same origin by default.

<script type="application/json" id="sesamy-js">
  {
    "clientId": "demo",
    "vendorId": "demo",
    "auth": { "useHttpCookies": true },
    "api": { "endpoint": "" }
  }
</script>

To namespace auth under a sub-path (e.g. when running behind a first-party proxy that reserves the top-level /auth/* path for something else), set auth.baseUrl:

<script type="application/json" id="sesamy-js">
  {
    "clientId": "acme",
    "auth": { "useHttpCookies": true, "baseUrl": "/sesamy" }
  }
</script>

The plugin then calls /sesamy/auth/userinfo, /sesamy/auth/{vendor}/login, and /sesamy/auth/logout. auth.baseUrl is independent of api.endpoint — the API and auth proxies may live on different sub-paths or hosts.

Notes:

  • When useHttpCookies is true and no api.endpoint is set, sesamy-js defaults the API endpoint to /api on the current origin (cross-origin cookies can't reach api2.sesamy.com).
  • For SSR, set auth.idToken to a server-injected id-token and sesamy-js treats the user as authenticated immediately, skipping /auth/userinfo. Alternatively include <script type="application/json" id="sesamy-server-state">{"idToken":"eyJ..."}</script> — the cookie-auth plugin reads it automatically.
  • The bootstrap loader detects useHttpCookies === true in the config element and skips the auth0-plugin entry in the chain.

Capsule (DCA) decryption

Use when: your articles ship as encrypted DCA payloads and you need sesamy-js to fetch unlock tokens, decrypt the manifest, and inject the plaintext into data-dca-content-name="..." placeholders.

<script type="application/json" id="sesamy-js">
  {
    "clientId": "demo",
    "auth": { "useHttpCookies": true },
    "capsule": { "enabled": true, "autoProcess": true }
  }
</script>

<!-- Register the capsule plugin before sesamy-js auto-inits -->
<script type="module">
  import { createCapsulePlugin } from '@sesamy/sesamy-js/capsule-plugin';
  window.capsulePlugin = { createCapsulePlugin };
</script>
<script src="/path/to/sesamy-js.iife.js"></script>

When autoProcess is true (the default), sesamy-js detects the DCA manifest on page load, calls the unlock endpoint, decrypts every data-dca-content-name block, and starts a MutationObserver for SPA navigation. To process content manually call sesamy.capsule.processPage(), or call sesamy.content.unlock(selector) for per-article control.

IIFE / classic <script> tag

Use when: the host site has no build step. Drop the IIFE bundle in directly:

<script type="application/json" id="sesamy-js">
  { "clientId": "demo" }
</script>
<script src="https://scripts.sesamy.com/s/demo/sesamy-js/auto.js"></script>

The IIFE bundle assumes the auth0-plugin / capsule-plugin IIFEs (if needed) have already executed and registered their factories on window. The bootstrap loader automates that ordering — using IIFEs without the bootstrap means you're responsible for inserting plugin scripts before the core script.

Configuration

init() and the auto-init JSON block accept the same Config shape:

interface Config {
  clientId: string; // required
  vendorId: string; // required
  environment?: 'dev' | 'prod';
  organization?: string; // Auth0 org id
  api?: Partial<ApiConfig>;
  analytics?: Partial<AnalyticsConfig>;
  errors?: Partial<ErrorReportingConfig>;
  auth?: Partial<AuthConfig>;
  content?: ContentNode[];
  transform?: TransformConfig;
  capsule?: CapsuleConfig;
  consent?: ConsentConfig;
  awaitAllServices?: boolean; // default: false
}

api

Field Type Default Purpose
namespace string 'sesamy' Property on window where the API is installed.
endpoint string https://api2.sesamy.com Absolute URL or relative path. Use a relative path (e.g. /api) when proxying through your own backend.
environment 'dev' | 'prod' inherits Config.environment Picks api2.sesamy.com vs api2.sesamy.dev.

When auth.useHttpCookies is true the API client switches to credentials: 'include' and drops the Authorization header.

auth

Field Type Default Purpose
enabled boolean true Disable auth entirely (anonymous-only mode).
domain string <vendorId>.token.sesamy.com Custom auth domain. By default the vendor's own AuthHero tenant is addressed by subdomain: <vendorId>.token.sesamy.com, or <vendorId>.token.sesamy.dev when environment is 'dev'.
domains string[] — Multiple auth domains for multi-tenant / white-label setups. The library picks the entry whose top-level domain matches the current page; falls back to domain.
useRefreshTokens boolean false Enable refresh-token rotation in the auth0-plugin.
useHttpCookies boolean false Switch to cookie-based BFF auth. Skips the auth0-plugin even if registered.
baseUrl string "" Base URL the BFF plugin prepends to its /auth/* paths. Set when running behind a first-party proxy that namespaces auth under a sub-path (e.g. "/sesamy" → /sesamy/auth/userinfo, /sesamy/auth/{vendor}/login). Independent of api.endpoint.
idToken string — Server-injected id-token for SSR. When set, sesamy-js treats the user as authenticated without calling /auth/userinfo.

See Cross-domain authentication below for how the library picks between popup and redirect login on cross-domain setups.

analytics

Field Type Default Purpose
enabled boolean true Toggle the analytics service.
environment 'dev' | 'prod' inherits Picks logs.sesamy.com vs logs.sesamy.dev.

The analytics service is built on GetAnalytics and ships these events to the Sesamy interaction endpoint:

  • Page views, triggered on router updates.
  • Scroll events at 25%, 50%, 75%, 100%.
  • Active vs idle duration.
  • Custom events emitted via analytics.track(name, properties).
  • All events emitted through events.emit(...) (prefixed with event:).

When consent.enabled is true, analytics storage is gated on the statistics consent flag — see Consent below.

errors

Field Type Default Purpose
enabled boolean true Report failures inside sesamy-js to Sesamy.
environment 'dev' | 'prod' inherits Picks logs.sesamy.com/errors vs logs.sesamy.dev/errors.

sesamy-js reports its own failures so problems on a publisher's site show up without a reader having to report them:

  • API requests that never complete, such as a blocked request or a failed CORS preflight. Browsers only expose these to JavaScript as a generic network error, so the report records whether the request was cross-origin.
  • API responses with a 5xx status, after retries. 4xx responses are normal answers and are not reported.
  • Failures while initialising auth or the other services.
  • Uncaught errors and unhandled promise rejections thrown from sesamy-js. Errors from other scripts on the page are ignored.

Reports are batched and sent as text/plain, so they need no CORS preflight. Query strings and fragments are removed from URLs, and tokens are redacted from messages and stacks before sending. A page load sends at most 20 reports. Each report carries the session id, and the persistent anonymous id only when statistics consent allows it.

content

An array of ContentNode objects describing how to discover articles in the DOM and (optionally) what paywall rules apply. Each node currently has type: 'article' and supports the following matchers and selectors:

{
  type: 'article',
  // Matchers — all optional, AND-ed together
  path?: string,                           // current URL contains this path
  queryParam?: { key: string; value: string },
  headers?: { name: string; contains: string },
  userAgentContains?: string,
  // Pricing / paywall metadata (forwarded to checkout)
  pass?: string,
  price?: { amount: number; currency: string },
  paywallUrl?: string,
  enablePaywallSettingsUrlFallback?: boolean,
  // DOM selectors (defaults provided — override per site)
  selectors?: {
    article?:     { selector: string; attribute?: string },
    image?:       { selector: string; attribute?: string },
    title?:       { selector: string; attribute?: string },
    excerpt?:     { selector: string; attribute?: string },
    price?:       { selector: string; attribute?: string },
    currency?:    { selector: string; attribute?: string },
    accessLevel?: { selector: string; attribute?: string },
    url?:         { selector: string; attribute?: string },
    pass?:        { selector: string; attribute?: string },
    id?:          { selector: string; attribute?: string },
    paywallUrl?:  { selector: string; attribute?: string },
  }
}

See the Content section below for content.list/get/hasAccess/unlock and the modal/notification-bar UI helpers.

transform

Selector-based DOM rules applied after content discovery (and after Capsule decryption when DCA is enabled).

{
  enabled?: boolean,
  rules: Array<{
    selector: string,
    transform: 'insert' | 'replace' | 'remove' | 'gradient' | 'wrap',
    contentType: 'html' | 'selector' | 'url',
    content?: string,
    insertionPoint?: 'before' | 'after' | 'inside',
    path?: string,                       // only apply on matching URLs
    entitlement?: string,                // only apply when user has this entitlement
    authenticated?: boolean,             // only apply for logged-in users
  }>
}

See Transforms below for full semantics and examples.

capsule

Field Type Default Purpose
enabled boolean false Initialise the DCA client. Required for any decryption to happen.
clientBound boolean false Wrap the unlock key with RSA-OAEP for client-bound transport.
rsaKeySize 2048 | 4096 2048 RSA key size when clientBound is true.
autoProcess boolean true Auto-detect DCA manifests and decrypt on page load + observe for SPA navigation.

When enabled is true the bootstrap loader pulls in @sesamy/sesamy-js/capsule-plugin automatically. If you self-host, register the plugin on window.capsulePlugin before sesamy-js auto-inits or pass it via init(config, { capsulePlugin }).

Field Type Default Purpose
enabled boolean — Required. When true, analytics storage is gated on consent.
cmp 'cookiebot' | 'onetrust' | 'google-consent-mode' — Auto-integrate with the named consent management platform.
defaultConsent Partial<ConsentState> { statistics: false, marketing: false } Initial consent state before the CMP responds.
onConsentChange (update: (c: Partial<ConsentState>) => void) => void — Custom CMP integration — the callback receives a function to push consent updates into sesamy-js.

ConsentState has two fields: statistics and marketing. Read/write at runtime via sesamy.consent.get/set/has — see Consent below.

awaitAllServices

When true, the promise returned by init() resolves only after analytics, auth, content, transforms, and capsule have finished initialising. Default false so the page can keep rendering while those services start in the background.

Authentication configuration

Custom domains

For a single custom Auth0 domain:

{
  auth: {
    clientId: 'your-client-id',
    domain: 'auth.example.com',
  },
}

Multiple domains (multi-tenant / white-label)

For applications that operate across multiple domains, use the domains array. The library extracts the top-level domain from the current page URL and picks the matching entry; if no entry matches, it falls back to domain, then to the vendor's tenant domain (<vendorId>.token.sesamy.com, or <vendorId>.token.sesamy.dev when environment is 'dev').

{
  auth: {
    clientId: 'your-client-id',
    domains: [
      'auth.brand1.com',
      'auth.brand2.com',
      'auth.example.co.uk',
    ],
    domain: 'default-auth.example.com',  // fallback if no match
  },
}

Cross-domain authentication

When the application domain differs from the auth domain's top-level domain, the library automatically uses popup-based login on Safari/iOS and Android to handle the cross-domain cookies properly. Desktop browsers stay on redirect-based login regardless.

App domain Auth domain Mobile Desktop
app.example.com auth.different.com Popup Redirect
app.example.com auth.example.com Redirect Redirect

API reference

All services hang off window[namespace] (default window.sesamy) and the object returned by init(). The following methods are available — full per-method documentation follows below.

  • amendments
    • create: create an amendment to a contract
    • confirm: confirms a created amendment for a contract
  • analytics
    • track: tracks an event with optional properties
  • attribution
    • get: get the attributions for a user
    • set: set the attributions for a user
  • auth
    • getUser: fetches the user's profile
    • getTokenSilently: retrieves a token without user interaction
    • isAuthenticated: checks if the user is authenticated
    • login: smart login that automatically chooses popup or redirect based on browser context
    • loginWithPopup: opens a popup window to complete the login
    • loginWithRedirect: redirects the user to the login page
    • logout: logs the user out
    • refresh: re-checks the authentication state from the auth provider
    • setToken: stores a token in local storage and triggers the authenticated event
  • bills
    • get: get a bill by id
    • list: lists all the user's bills
  • browser
    • detectAdblock: detects if an ad blocker is enabled
    • isInAppBrowser: detects if the browser is an in-app browser
    • isIncognito: detects if the browser is in incognito mode
  • capsule
    • getClient: returns the underlying DCA client (when capsule.enabled is true)
    • processPage: detect and decrypt every DCA manifest on the current page
  • checkouts
    • create: creates a checkout session
    • get: gets a checkout session by id
    • update: updates a checkout session
  • clearCache: clears the cache for the sesamy-js library
  • consent
    • get: returns the current consent state
    • has: checks whether a specific consent flag is granted
    • set: updates the consent state and re-evaluates analytics storage
  • content
    • get: get an article based on an element or a selector
    • getLanguage: get the current language
    • getPropertyFromHTML: extracts a property from HTML content
    • hasAccess: checks if the user has access to a specific article element
    • list: get all articles based on the configured selectors
    • showModal: opens the paywall modal (requires sesamy-components)
    • showNotificationBar: shows an inline notification bar above/below content
    • unlock: retrieves the locked content using an element or a css selector
  • contracts
    • cancel: cancel a contract by id
    • get: get a contract by id
    • list: lists all the user's contracts
  • diagnostics
    • collect: gathers a snapshot of profile, entitlements, contracts, tags, and tallies for support tickets
    • send: collects diagnostics and uploads them to the Sesamy diagnostics endpoint
  • entitlements
    • access: fetches the user's access URL for an entitlement
    • get: gets a single entitlement by id
    • hasAccess: checks if the user has access to a specific item
    • list: lists the user's entitlements
    • signedLinks: lists signed links registered in the current session
  • events
    • cancel: cancels a cancelable event with an optional reason message
    • emit: emits a custom event that can optionally be canceled by listeners
  • flags
    • get: gets a feature flag value
    • set: sets a feature flag value
    • list: lists all feature flags
    • delete: deletes a feature flag
  • fulfillments
    • list: list the user's fulfillments for a SKU
    • requestDelivery: requests delivery for a fulfillment by SKU and delivery method
  • licenses
    • get: gets the user's most recent license key in a pool (expired keys included), or null when nothing has been claimed
    • claim: claims a license key from a pool. Returns the existing key while it is unexpired, a new one after it expires
  • generateLink: creates a link to a Sesamy hosted service such as account, change-payment, consume, or checkout. If the user is authenticated, the link will be signed so that the user can access the service without logging in again.
  • getPaymentIssues: returns a list of failed payments and cards that will expire
  • getVersion: returns the version of the sesamy-js library
  • init: Initializes the sesamy-js library
  • isReady: returns a boolean indicating whether the initialization process has completed
  • log: logs a message to the console (only when debug mode is enabled)
  • paywalls
    • get: get a paywall by id
  • products
    • autoOnboard: trigger the auto-onboarding process for a product by SKU
    • get: get a product by SKU
    • linkSpotify: links a Spotify account to a product
  • profile
    • get: fetches the user's profile
    • isSpotifyLinked: returns true if the user has linked their Spotify account
    • openHostedAccountPage: opens the hosted account page
    • unlinkSpotify: unlinks the user's Spotify account
    • update: updates the user's profile
  • proxy
    • getContent: retrieves locked content using an access token and URL.
  • subscriptions (deprecated, use contracts instead)
    • list: lists all the user's subscriptions
  • tags
    • delete: deletes a tag for the user
    • get: fetches the user's tags
    • set: sets a tag for the user
  • tallies
    • get: get a tally for a user by id
    • list: list all tallies for a user
    • push: push an item to a tally
  • transactions
    • get: get a transaction by id
    • list: lists all the user's transactions
  • userMetadata
    • delete: deletes the user's metadata by id
    • get: get the user's metadata by id
    • list: list all the user's metadata
    • set: sets the user's metadata
  • vendors
    • get: get the settings for the current vendor
    • list: list all publishers connected to the user. This is not available for publisher tokens

Events

The following events are emitted by the sesamy-js library:

  • sesamyJsReady - Emitted when the sesamy-js library is ready to be used
  • sesamyJsAuthenticated - Emitted when the user is authenticated
  • sesamyJsClearCache - Emitted when the cache is cleared
  • sesamyJsLogout - Emitted when the user logs out
  • sesamyJsPurchase - Emitted after a purchase is completed and passes an itemSrc property with the source of the purchase

Url triggers

Query parameters

The library can trigger actions based on query parameters. The following query parameters are supported:

  • sesamy-refresh. If present, the library will clear the cache and emit a sesamyJsClearCache event.
  • sesamy-user. If present, the library will validate that the user is authenticated with the correct email. If not, the user will be logged out and a new login with be initiated.
  • sesamy-login. If present, the library will validate that the user is authenticated. If not, the user will be logged out and a new login with be initiated.
  • sesamy-purchase. Triggers a sesamyJsPurchase event.
  • sesamy-token. If present, the library parse the token and add any content permissions that the token grants.

Hash triggers

The library can read the access token from the hash. It is not the preferred way of logging in a user but can be used when redirecting the user across domains where a cookie-based solution is not possible. The hash is not sent to the server so the is no risk of leaking the token. The token hash is passed like this: #access_token=<token>

Custom HTML Attributes

Visibility

Overview

The sesamy-visibility attribute allows dynamic visibility control of HTML elements based on the authentication state of a user.

Usage

This attribute can be added to HTML elements to automatically show or hide them based on authentication status.

Example
<div sesamy-visibility="logged-in">Welcome, User!</div>
<div sesamy-visibility="not-logged-in">Please log in.</div>
Overview

The sesamy-link attribute attaches a click handler to an element that redirects the user.

Usage

This attribute can be added to HTML elements to redirect the user to the following targets: login, logout and account.

Example
<div sesamy-link="login">Login</div>
<div sesamy-link="logout">Logout</div>
<div sesamy-link="account">Account</div>

Core API

isReady()

Checks if the initialization process of the Sesamy library has completed. This function allows you to determine when it's safe to use the library's features that depend on initialization being complete.

Returns

  • boolean: Returns true if initialization has completed, otherwise it returns false.
Example
// Check if the Sesamy library is ready
if (window.sesamy.isReady()) {
  // Safe to use Sesamy APIs that require initialization
  console.log('Sesamy is ready to use');
} else {
  console.log('Sesamy is still initializing');
}

You can also use it with an event listener to perform actions when the library is ready:

// Alternative approach using the ready event
window.addEventListener('sesamyJsReady', () => {
  // This will be true at this point
  console.log('Sesamy initialized status:', window.sesamy.isReady());
  // Perform actions that require Sesamy to be initialized
});

log(message: string)

Logs a message to the console, but only when debug mode is enabled. This is useful for debugging purposes without cluttering the console for end users.

Parameters
  • message (string): The message to log to the console.
Example
// Log a debug message
window.sesamy.log('Testing the checkout process');
Note

The log function only outputs messages when debug mode is enabled. Debug mode can be enabled by:

  1. Adding ?sesamy-debug=true to the URL
  2. Setting localStorage.debug = true

Auth API

isAuthenticated()

Checks if the user is currently authenticated. This function verifies the existence of a valid session by checking both the local storage for an access token and the state of the Auth0 client.

Returns

  • boolean: Returns true if the user is authenticated either via local storage tokens or the Auth0 client; otherwise, it returns false.
Example

The following example demonstrates how to check if a user is currently authenticated:

import { isAuthenticated } from '@sesamy/sesamy-js';

isAuthenticated()
  .then((isAuth) => {
    if (isAuth) {
      console.log('User is authenticated.');
    } else {
      console.log('User is not authenticated.');
    }
  })
  .catch((error) => {
    console.error('Error checking authentication status:', error);
  });

login(options?: RedirectOptions)

Initiates a smart login flow that automatically chooses the best authentication method based on the user's browser context. This function detects if the user is in incognito mode and adapts accordingly:

  • Incognito mode: Uses popup-based authentication (loginWithPopup) which works better in private browsing sessions, especially on Safari mobile browsers
  • Normal browsing: Uses redirect-based authentication (loginWithRedirect) which is the standard approach for regular browsing

This is the recommended login method as it provides the best user experience across different browser scenarios without requiring manual detection of the browsing context.

Parameters
  • options (optional): An object containing customization options for the login flow.
    • appState: (optional, object) Used to store state before doing the redirect.
    • authorizationParams: (optional, object) Additional parameters to include in the authorization request.
      • audience: (optional, string) The audience to request access to.
      • scope: (optional, string) The scope of the access request.
      • login_hint: (optional, string) A hint to pre-fill the username on the login page.
      • organization: (optional, string) The organization to authenticate with.
      • redirect_uri: (optional, string) The URL to redirect the user to after login.
Returns

This function returns a Promise that resolves when the login flow is successfully initiated.

Example

The following example demonstrates how to use the smart login function:

import { login } from '@sesamy/sesamy-js';

// Smart login that adapts to browser context
const loginOptions = {
  authorizationParams: {
    login_hint: 'user@example.com',
  },
};

login(loginOptions)
  .then(() => {
    console.log('Login initiated successfully');
  })
  .catch((error) => {
    console.error('Login failed:', error);
  });
Browser Compatibility Notes
  • Incognito Mode: Automatically uses popup authentication which provides better compatibility in private browsing mode
  • Normal Browsing: Uses redirect authentication which is more reliable for standard browsing sessions
  • Cross-Browser: Works consistently across different browsers and mobile devices

loginWithRedirect(options?: LoginWithRedirectOptions)

Initiates a login flow that redirects the user to an Auth0 hosted login page. Once the user authenticates, they will be redirected back to the specified redirect_uri within your application.

This is the most common login method and works well for most browsers and scenarios. However, it may have limitations in incognito mode on certain browsers (particularly Safari on mobile devices).

Parameters
  • options (optional): An object containing customization options for the login flow.
    • appState: (optional, object) Used to store state before doing the redirect.
    • authorizationParams: (optional, object) Additional parameters to include in the authorization request.
      • audience: (optional, string) The audience to request access to.
      • scope: (optional, string) The scope of the access request.
      • login_hint: (optional, string) A hint to pre-fill the username on the login page.
      • organization: (optional, string) The organization to authenticate with.
      • redirect_uri: (optional, string) The URL to redirect the user to after login.
Returns

This function returns a Promise that resolves when the redirect is successfully initiated.

Example

The following example demonstrates how to use loginWithRedirect to initiate a login flow with an email address pre-filled:

import { loginWithRedirect } from '@sesamy/sesamy-js';

// Optionally pass the user's email to pre-fill on the login form
const loginOptions = {
  authorizationParams: {
    login_hint: 'user@example.com',
  },
};

// Redirect the user to the login page
loginWithRedirect(loginOptions);

loginWithPopup(options?: LoginWithPopupOptions)

Initiates a login flow using a popup window instead of redirecting the current page. This method can provide better user experience in certain scenarios and may work better in incognito mode on some browsers where redirect-based authentication has limitations.

Important: After successful authentication, the popup method will trigger a page refresh by default. To prevent this refresh, you must listen for the sesamyJsAuthenticated event and call preventDefault() on it.

When to Use Popup Login
  • When you want to maintain the user's current page state
  • In incognito mode scenarios where redirect-based authentication may not work properly
  • When integrating with single-page applications where full page redirects are undesirable
  • When you need more control over the authentication flow
Parameters
  • options (optional): An object containing customization options for the login flow.
    • appState: (optional, object) Used to store state before doing the redirect.
    • authorizationParams: (optional, object) Additional parameters to include in the authorization request.
      • audience: (optional, string) The audience to request access to.
      • scope: (optional, string) The scope of the access request.
      • login_hint: (optional, string) A hint to pre-fill the username on the login page.
      • organization: (optional, string) The organization to authenticate with.
      • redirect_uri: (optional, string) The URL to redirect the user to after login.
Returns

This function returns a Promise that resolves when the popup authentication is completed.

Example

The following example demonstrates how to use loginWithPopup and prevent the automatic page refresh:

import { loginWithPopup } from '@sesamy/sesamy-js';

// Listen for authentication event to prevent page refresh
window.addEventListener('sesamyJsAuthenticated', (event) => {
  // Prevent the automatic page refresh
  event.preventDefault();

  // Handle the successful authentication
  console.log('User authenticated successfully!');

  // Perform any custom actions after authentication
  // e.g., update UI, redirect to a specific section, etc.
});

// Initiate popup login
const loginOptions = {
  authorizationParams: {
    login_hint: 'user@example.com',
  },
};

loginWithPopup(loginOptions)
  .then(() => {
    console.log('Popup login completed');
  })
  .catch((error) => {
    console.error('Popup login failed:', error);
  });
Browser Compatibility Notes
  • Incognito Mode: loginWithPopup may provide better compatibility in incognito/private browsing mode, especially on Safari mobile browsers where redirect-based authentication can fail.
  • Popup Blockers: Some browsers or extensions may block popups. Always provide fallback options or user instructions.
  • Mobile Browsers: Popup behavior may vary on mobile devices. Test thoroughly across different mobile browsers.

logout(options?: LogoutOptions)

Terminates the user's session and optionally redirects the user to a specified URL after logout. This function clears any local session tokens and interacts with the Auth0 API to end the session.

Parameters
  • options (optional): An object containing customization options for the logout process.
    • returnTo: (optional, string) The URL to redirect users to after logging out. Defaults to the current page URL if not provided.
Returns

This function does not return a value. It causes a redirect to the specified returnTo URL or performs a page refresh if no URL is provided.

Example

The following example demonstrates how to log out a user and redirect them to the homepage:

import { logout } from '@sesamy/sesamy-js';

// Specify the URL to redirect to after logout
const logoutOptions = {
  returnTo: 'https://www.yourdomain.com',
};
// Redirects the user to the auth server to log out
logout(logoutOptions);

setToken(accessToken: string)

Stores the provided access token in local storage. This function parses the access token to extract user information and triggers an authentication event.

Parameters
  • accessToken (string): The access token to store and use for session management.
Returns

This function does not return a value but triggers an event indicating that a user has been authenticated with the new token.

Example

The following example demonstrates how to store an access token:

import { setToken } from '@sesamy/sesamy-js';

// Example access token
const accessToken = 'your.access.token';

setToken(accessToken)
  .then(() => {
    console.log('Token set successfully and user authenticated.');
  })
  .catch((error) => {
    console.error('Failed to set token:', error);
  });

getTokenSilently(throwOnUnauthorized?: boolean, forceRefresh?: boolean)

Retrieves a valid access token for the current user session without requiring user interaction. This function attempts to get the token from local storage or, if not available or expired, from the Auth0 client. It can optionally force a refresh or throw on unauthorized errors.

Parameters
  • throwOnUnauthorized (boolean, optional): If true, throws an error if the user is not authorized. Defaults to true.
  • forceRefresh (boolean, optional): If true, forces a refresh of the token if it is close to expiring. Defaults to false.
Returns
  • Promise<string | null>: Resolves to the access token string if available, or null if not authenticated and throwOnUnauthorized is false.
Example
import { getTokenSilently } from '@sesamy/sesamy-js';

// Get the current access token
getTokenSilently()
  .then((token) => {
    if (token) {
      console.log('Access token:', token);
    } else {
      console.log('No access token available');
    }
  })
  .catch((error) => {
    console.error('Error retrieving token:', error);
  });
Security & Storage Notes
  • The access token is stored in local storage by default. This is necessary because many publishers use multi-page applications, and JavaScript running on the publisher's site can access the token anyway.
  • If the publisher uses a custom domain for authentication (so the auth domain matches the publisher's top-level domain), the session token will be stored in an httpOnly cookie. In this case, malicious scripts can only access short-lived access tokens, not the session token itself.
  • Always ensure you trust third-party scripts running on your site, as they may be able to access tokens stored in local storage.

auth.refresh()

Forces sesamy-js to re-check the authentication state from the configured auth plugin (Auth0 SPA or BFF cookie). Useful after an external login or logout has changed cookies/storage outside the SDK's awareness, or after a window re-focus where you suspect the session may have been invalidated server-side.

Returns

Promise<void> — resolves once the auth state has been re-evaluated and any state-change events (sesamyJsAuthenticated, sesamyJsLogout) have fired.

Example
window.addEventListener('focus', async () => {
  await window.sesamy.auth.refresh();
});

Entitlements API

entitlements.get(entitlementId: string)

Fetches a specific entitlement by its ID.

Parameters

  • entitlementId (string): The ID of the entitlement to retrieve.
Returns
  • Promise<Entitlement | undefined>: The entitlement object if found, otherwise undefined.
Example
// Fetch a specific entitlement by its ID
window.sesamy.entitlements
  .get('entitlement-id')
  .then((entitlement) => {
    if (entitlement) {
      console.log('Entitlement:', entitlement);
    } else {
      console.log('Entitlement not found');
    }
  })
  .catch((error) => {
    console.error('Error fetching entitlement:', error);
  });

entitlements.list(params: GetEntitlementsOptions)

Fetches the list of entitlements, with optional filters and inclusion of signed links.

Parameters
  • params (GetEntitlementsOptions): Optional parameters for fetching entitlements.
    • includeSignedLinks (boolean, optional): Whether to include signed links. Default is true.
    • waitForEntitlementAfter (Date, optional): If provided, waits for an entitlement that is available after the given date.
Returns
  • Promise<Entitlement[]>: An array of entitlements.
Example
// Fetch all entitlements, including signed links
window.sesamy.entitlements
  .list({ includeSignedLinks: true })
  .then((entitlements) => {
    console.log('Entitlements:', entitlements);
  })
  .catch((error) => {
    console.error('Error fetching entitlements:', error);
  });

entitlements.access(entitlementId: string)

Fetches the access details for a specific entitlement by its ID.

Parameters
  • entitlementId (string): The ID of the entitlement to access.
Returns
  • Promise<Access>: The access details for the given entitlement.
Example
// Fetch access details for a specific entitlement
window.sesamy.entitlements
  .access('entitlement-id')
  .then((access) => {
    console.log('Access details:', access);
  })
  .catch((error) => {
    console.error('Error fetching entitlement access:', error);
  });

Fetches signed links for the current session's entitlements.

Parameters

None.

Returns
  • SignedLink[]: An array of signed links for the current entitlements.
Example
// Fetch signed links for the current entitlements
const signedLinks = window.sesamy.entitlements.signedLinks();
console.log('Signed links:', signedLinks);

Types
  • GetEntitlementsOptions: An object containing optional parameters for fetching entitlements.

    • includeSignedLinks (boolean, optional): Whether to include signed links. Defaults to true.
    • waitForEntitlementAfter (Date, optional): A date to filter entitlements that are available after the given date.
  • Entitlement: Represents an entitlement object.

  • Access: Represents the access details for an entitlement.

  • SignedLink: Represents a signed link for accessing an entitlement.

Services

getProfile()

Fetches the user's profile information from the Sesamy-hosted service. If the user is authenticated, the profile data will be retrieved.

Returns

Promise<Profile | null>: A promise that resolves to the user's profile information if the user is authenticated, otherwise it resolves to null.

Example

The following example demonstrates how to fetch the user's profile information:

import { getProfile } from '@sesamy/sesamy-js';

// Fetch the user's profile information
getProfile()
  .then((profile) => {
    if (profile) {
      console.log('User profile:', profile);
    } else {
      console.log('User is not authenticated');
    }
  })
  .catch((error) => {
    console.error('Error fetching profile:', error);
  });
Profile Type
export type Profile = {
  userId: string;
  firstName?: string;
  lastName?: string;
  emailVerified: boolean;
  email: string;
  name?: string;
  locale?: string;
  picture?: string;
  createdAt: string;
  updatedAt: string;
  mobilePhone?: string;
  tags: string[];
  user_metadata?: { [id: string]: string | number };
  billingAddress?: Address;
  deliveryAddress?: Address;
};
Address Type
export type Address = {
  street: string;
  co?: string;
  city: string;
  state: string;
  postalCode: string;
  country: string;
};

updateProfile(profile: Partial<Profile>)

Updates the user's profile information on the Sesamy-hosted service. After updating, the cache is cleared to ensure that the latest profile information is available.

Parameters
  • profile (Partial): An object containing the profile fields to be updated. Only the provided fields will be updated.
Returns

Promise<boolean>: A promise that resolves to true if the profile update is successful, otherwise false.

Example

The following example demonstrates how to update the user's profile information:

import { updateProfile } from '@sesamy/sesamy-js';

// Define the profile fields to be updated
const updatedProfile = {
  firstName: 'John',
  lastName: 'Doe',
  locale: 'en-US',
  mobilePhone: '+1234567890',
};

// Update the user's profile information
updateProfile(updatedProfile)
  .then((success) => {
    if (success) {
      console.log('Profile updated successfully');
    } else {
      console.log('Profile update failed');
    }
  })
  .catch((error) => {
    console.error('Error updating profile:', error);
  });
Profile Type
export type Profile = {
  userId: string;
  firstName?: string;
  lastName?: string;
  emailVerified: boolean;
  email: string;
  name?: string;
  locale?: string;
  picture?: string;
  createdAt: string;
  updatedAt: string;
  mobilePhone?: string;
  tags: string[];
  user_metadata?: { [id: string]: string | number };
  billingAddress?: Address;
  deliveryAddress?: Address;
};
Address Type
export type Address = {
  street: string;
  co?: string;
  city: string;
  state: string;
  postalCode: string;
  country: string;
};

Generates a link to a Sesamy-hosted service such as account or consume. If the user is authenticated, the link will be signed so that the user can access the service without logging in again.

Parameters
  • params (GenerateAccountLink | GenerateConsumeLink):
    • The parameters for generating the link. attribute. Common parameters:

      • target (string, required): The target service. Valid values:
        • 'account': Generate link to account page
        • 'change-payment': Generate link to payment change page
        • 'change-plan': Generate link to payment plan page
        • 'consume': Generate link to consume content
        • 'checkout': Generate link to checkout page
      • shorten (boolean, optional): If true, the link will be shortened
      • ttl (number, optional): The time-to-live for the shortened link in seconds
      • redirectUrl (string, optional): The URL to redirect to after the link is accessed
      • language (string, optional): The language for the link. Defaults to HTML element's lang attribute
    • Target-specific parameters: For target='consume':

      • sku (string, required): The SKU of the product to consume
      • episodeId (string, optional): The ID of the episode to consume
    • For target='change-payment|change-plan':

      • contractId (string, required): The ID of the contract to change payment or plan for
Returns

string: The generated link URL. If shorten is true, the shortened URL is returned.

Example

The following example demonstrates how to generate a link to the Sesamy account page:

import { generateLink } from '@sesamy/sesamy-js';

// Generate a link to the account page
const linkParams = {
  target: 'account',
  shorten: true,
  ttl: 3600, // 1 hour in seconds
  redirectUrl: 'https://www.yourdomain.com/account',
};

generateLink(linkParams)
  .then((link) => {
    console.log('Generated link:', link);
  })
  .catch((error) => {
    console.error('Error generating link:', error);
  });

And here is an example for generating a link to consume a specific product:

import { generateLink } from '@sesamy/sesamy-js';

// Generate a link to consume a product
const linkParams = {
  target: 'consume',
  sku: 'sid:eUv45QXTrcGNhMJpaCQNe',
  episodeId: 'episode-id',
  shorten: true,
  ttl: 3600, // 1 hour in seconds
  redirectUrl: 'https://www.yourdomain.com/consume',
};

generateLink(linkParams)
  .then((link) => {
    console.log('Generated link:', link);
  })
  .catch((error) => {
    console.error('Error generating link:', error);
  });

checkouts.create(params: CreateCheckoutParams)

Creates a checkout session with Sesamy. This function initializes a checkout process by sending the necessary parameters to the Sesamy API.

Parameters
  • params (CreateCheckoutParams): The parameters for creating the checkout session.
    • items (Array of objects, required): An array of items to be included in the checkout.
      • sku (string, optional): The SKU of the product to be purchased.
      • url (string, optional): The URL of the item.
      • purchaseOptionId (string, optional): The ID of the purchase option for the product.
      • price (number, optional): The price of the item.
      • currency (string, optional): The currency code (e.g., 'USD').
      • geoRestrictions (object, optional): Geographic restrictions for the item.
        • type ('ALLOW' | 'BLOCK'): Type of restriction.
        • countries (Array of strings): List of country codes.
    • redirectUrl (string, required): The URL to redirect to after the checkout process is completed.
    • language (string, optional): The language for the checkout session. If not set, it will be automatically fetched from the HTML element's lang attribute.
    • givenName (string, optional): The given name of the customer.
    • familyName (string, optional): The family name of the customer.
    • email (string, optional): The email address of the customer.
    • phoneNumber (string, optional): The phone number of the customer.
    • birthDate (string, optional): The birth date of the customer in ISO format.
    • country (string, optional): The country of the customer (country code).
    • address (Address, optional): The billing address for the checkout session.
      • street (string, optional): The street address.
      • city (string, optional): The city.
      • zip (string, optional): The postal code.
      • country (string, optional): The country code.
    • businessAddress (Address, optional): The business address for B2B transactions.
    • isBusiness (boolean, optional): Indicates if the checkout is for a business.
    • price (number, optional): Override price for the entire order (takes precedence over item prices).
    • currency (string, optional): Override currency for the entire order.
    • paymentMethodsFilter (Array of objects, optional): Filter available payment methods in the checkout.
      • provider (string): The payment provider (e.g., 'stripe', 'klarna').
      • methods (Array of strings, optional): Specific payment methods for the provider.
    • requestedDiscountCodes (Array of strings, optional): Discount codes to apply to the checkout.
    • attribution (object, optional): Attribution and tracking data.
      • utmSource (string, optional): UTM source parameter.
      • utmMedium (string, optional): UTM medium parameter.
      • utmCampaign (string, optional): UTM campaign parameter.
      • utmTerm (string, optional): UTM term parameter.
      • utmContent (string, optional): UTM content parameter.
      • ref (string, optional): Referral identifier.
      • referrer (string, optional): Referrer URL.
      • itemSrc (string, optional): Source of the item.
      • publisherContentId (string, optional): Publisher content ID.
      • source ('CHECKOUT' | 'PAYWALL' | 'OTHERS', optional): Source of the checkout.
      • sourceId (string, optional): Source identifier.
      • _ga, _gid, _fbp, _fbc, _pk_id (strings, optional): Analytics tracking cookies. _pk_id carries the Matomo visitor cookie, whose real name is _pk_id.<idsite>.<domainhash>.
    • referralEmail (string, optional): Email of the referrer.
    • payerEmail (string, optional): Email of the payer (person paying for the purchase).
    • requireAddress (boolean, optional): If true, requires the customer to provide an address during checkout.
    • giftMode (boolean, optional): If true, enables gift mode for the checkout.
    • metadata (Record<string, string>, optional): Custom metadata to store with the checkout (e.g., { "campaign": "summer2024", "source": "mobile" }).
Returns

Promise<Checkout>: A promise that resolves to the response JSON object from the Sesamy API, which contains details about the created checkout session.

Checkout Response Schema
  • id (string): The unique identifier of the checkout session.
  • checkoutUrl (string): The URL where the user should be redirected to complete the checkout.
  • status ('PENDING' | 'PAID'): The status of the checkout session.
  • type ('RECURRING' | 'SINGLE'): The type of checkout session.
  • createdAt (string): ISO timestamp of when the checkout was created.
  • updatedAt (string): ISO timestamp of when the checkout was last updated.
  • items (Array of objects): The items included in the checkout session.
    • sku (string): The SKU of the product.
    • url (string): The URL of the item.
    • purchaseOptionId (string, optional): The ID of the purchase option.
    • price (number, optional): The price of the item.
    • currency (string, optional): The currency of the item.
  • itemsOwned (Array of objects): Items already owned by the user.
    • sku (string): The SKU of the product.
    • purchaseOptionId (string): The purchase option ID.
    • title (string): The title of the product.
  • appliedDiscountCodes (Array of objects): Discount codes applied to the checkout.
    • name (string): Name of the discount.
    • description (string): Description of the discount.
    • id (string): ID of the discount code.
    • code (string): The discount code.
    • status ('APPLIED' | 'UNAPPLICABLE'): Status of the discount code.
  • availablePaymentMethods (Array of objects): Available payment methods for checkout.
    • provider (string): The payment provider.
    • methods (Array of strings, optional): Available payment methods for the provider.
  • email (string, optional): The email address for the checkout session.
  • language (string): The language used for the checkout session.
  • currency (string): The currency used for the checkout session.
  • country (string): The country associated with the checkout session.
  • redirectUrl (string): The redirect URL after completion.
  • fieldSettings (object, optional): Field visibility and requirement settings.
Example

The following example demonstrates how to create a checkout session with Sesamy:

import { init } from '@sesamy/sesamy-js';

const sesamy = await init({ clientId: 'your-client-id' });

// Create a simple checkout with one item
const checkout = await sesamy.checkouts.create({
  items: [
    {
      sku: 'premium_monthly',
      purchaseOptionId: 'po_123',
      price: 9.99,
      currency: 'USD',
    },
  ],
  email: 'customer@example.com',
  redirectUrl: 'https://yoursite.com/checkout-complete',
  requireAddress: true,
  metadata: {
    campaignId: 'summer_2024',
    source: 'mobile_app',
  },
});

// Redirect to checkout
window.location.href = checkout.checkoutUrl;

Advanced example with gift mode and payer email:

const checkout = await sesamy.checkouts.create({
  items: [
    {
      sku: 'premium_gift',
      purchaseOptionId: 'po_gift',
      price: 49.99,
      currency: 'USD',
    },
  ],
  email: 'recipient@example.com',
  payerEmail: 'sender@example.com',
  redirectUrl: 'https://yoursite.com/checkout-complete',
  giftMode: true,
  language: 'en',
  metadata: {
    giftMessage: 'Happy Birthday!',
    giftFrom: 'John',
  },
});
Additional Notes
  • The items array must contain at least one item.
  • The redirectUrl is required and will be used after the checkout is completed.
  • The language parameter is optional. If not provided, it will be determined from the HTML document's lang attribute.
  • Attribution data is automatically enhanced with tracking cookies (_ga, _gid, _fbp, _fbc, and the Matomo _pk_id.* cookie, forwarded as _pk_id) if available.
  • Discount codes validation happens on the Sesamy backend; invalid codes will be marked as 'UNAPPLICABLE' in the response.

checkouts.update(id: string, params: Partial<CreateCheckoutParams>)

Updates an existing checkout session with Sesamy. You can update customer information, items, or other checkout details.

Parameters
  • id (string): The unique identifier of the checkout session to update.
  • params (Partial): The parameters to update. All fields are optional.
    • items (Array of objects, optional): Updated array of items.
      • sku (string, optional): The SKU of the product.
      • url (string, optional): The URL of the item.
      • purchaseOptionId (string, optional): The ID of the purchase option.
      • price (number, optional): The price of the item.
      • currency (string, optional): The currency code.
    • redirectUrl (string, optional): Updated redirect URL.
    • language (string, optional): Updated language for the checkout session.
    • email (string, optional): Updated email address.
    • givenName (string, optional): Updated given name.
    • familyName (string, optional): Updated family name.
    • phoneNumber (string, optional): Updated phone number.
    • birthDate (string, optional): Updated birth date.
    • country (string, optional): Updated country.
    • address (Address, optional): Updated billing address.
    • businessAddress (Address, optional): Updated business address.
    • isBusiness (boolean, optional): Updated business status.
    • price (number, optional): Updated order price.
    • currency (string, optional): Updated order currency.
    • paymentMethodsFilter (Array of objects, optional): Updated payment method filters.
    • requestedDiscountCodes (Array of strings, optional): Updated discount codes to apply.
    • attribution (object, optional): Updated attribution and tracking data.
    • payerEmail (string, optional): Updated payer email.
    • requireAddress (boolean, optional): Updated address requirement.
    • giftMode (boolean, optional): Updated gift mode status.
    • metadata (Record<string, string>, optional): Updated metadata.
Returns

Promise<Checkout>: A promise that resolves to the updated checkout session object.

Example

Basic update example:

import { init } from '@sesamy/sesamy-js';

const sesamy = await init({ clientId: 'your-client-id' });

const updated = await sesamy.checkouts.update('checkout_123', {
  email: 'newemail@example.com',
  givenName: 'Jane',
});

console.log('Checkout updated:', updated);

Update with new discount codes:

const updated = await sesamy.checkouts.update('checkout_123', {
  requestedDiscountCodes: ['NEWCODE', 'SUMMER20'],
});

console.log('Applied discount codes:', updated.appliedDiscountCodes);
Additional Notes
  • Only provide the fields you want to update; omitted fields will remain unchanged.
  • Discount codes are validated on the Sesamy backend.
  • Changes to payment method filters will be reflected in the checkout session immediately.
  • country (string): The country associated with the checkout session.
  • language (string): The language used for the checkout session.
  • items (Array of objects): The items included in the checkout session.
    • sku (string): The SKU of the product.
    • purchaseOptionId (string, optional): The ID of the purchase option for the product.
    • title (string): The title of the product.
    • cover (string): The cover image URL of the product.
  • itemsOwned (Array of strings): The SKUs of the items already owned by the user.
  • discountCodes (Array of strings): The discount codes applied to the checkout session.
  • paymentOptions (Array of objects): The available payment options.
    • provider (string): The payment provider.
    • methods (Array of strings): The payment methods supported by the provider.

checkouts.get(id: string)

Retrieves the details of a specific checkout session from Sesamy.

Parameters
  • id (string): The unique identifier of the checkout session to retrieve.
Returns

Promise<Checkout>: A promise that resolves to the checkout session object with all details.

Example
import { init } from '@sesamy/sesamy-js';

const sesamy = await init({ clientId: 'your-client-id' });

const checkout = await sesamy.checkouts.get('checkout_123');
console.log('Checkout status:', checkout.status);
console.log('Checkout URL:', checkout.checkoutUrl);
console.log('Applied discounts:', checkout.appliedDiscountCodes);
console.log('Items owned:', checkout.itemsOwned);
Additional Notes
  • The id parameter is required and must be a valid checkout session identifier.
  • Returns the complete checkout session data including status, items, and applied discounts.

Browser API

detectAdblock()

Detects the presence of an ad blocker in the browser by dynamically creating and checking the visibility of several ad-related HTML elements.

Parameters

None

Returns

Promise: A promise that resolves to a boolean value indicating whether an ad blocker is enabled (true) or not (false).

Example

The following example demonstrates how to use the detectAdblock function to detect if an ad blocker is enabled:

import { detectAdblock } from '@sesamy/sesamy-js';

// Detect if an ad blocker is enabled
detectAdblock()
  .then((isAdblockEnabled) => {
    if (isAdblockEnabled) {
      console.log('Adblocker is enabled');
    } else {
      console.log('Adblocker is not enabled');
    }
  })
  .catch((error) => {
    console.error('Error detecting adblock:', error);
  });
Details
  • The function creates a set of HTML <div> elements with IDs typically used by ad containers (e.g., 'AdHeader', 'AdContainer', etc.).
  • These elements are appended to the body of the document and their visibility is checked after a short delay (100 milliseconds).

isIncognito()

Synchronously checks if the browser is running in incognito mode by reading from session storage. This function returns the cached incognito status without performing any detection.

Parameters

None

Returns

boolean | undefined: Returns true if incognito mode is confirmed, false if not incognito, or undefined if the incognito status hasn't been determined yet.

Example

The following example demonstrates how to use the isIncognito function:

import { isIncognito } from '@sesamy/sesamy-js';

// Check cached incognito status
const incognitoStatus = isIncognito();

if (incognitoStatus === true) {
  console.log('Incognito mode is enabled');
} else if (incognitoStatus === false) {
  console.log('Incognito mode is not enabled');
} else {
  console.log('Incognito status not yet determined');
  // You may want to call detectAndCacheIncognito() first
}

detectAndCacheIncognito()

Detects incognito mode using the detectincognitojs library and persists the result to session storage. This function only performs detection if the result is not already cached in session storage.

Parameters

None

Returns

Promise<boolean>: A promise that resolves to true if the browser is running in incognito mode, or false if not.

Example

The following example demonstrates how to use the detectAndCacheIncognito function:

import { detectAndCacheIncognito, isIncognito } from '@sesamy/sesamy-js';

// Detect and cache incognito status (typically called once during app initialization)
detectAndCacheIncognito().then((isIncognitoEnabled) => {
  if (isIncognitoEnabled) {
    console.log('Incognito mode detected and cached');
  } else {
    console.log('Normal browsing mode detected and cached');
  }

  // Now you can use the synchronous isIncognito() function
  console.log('Cached status:', isIncognito());
});
Usage Pattern

The recommended usage pattern is to call detectAndCacheIncognito() once during application initialization, then use the synchronous isIncognito() function throughout your application:

// During app initialization
await detectAndCacheIncognito();

// Throughout your app - fast synchronous checks
if (isIncognito() === true) {
  // Handle incognito mode
} else if (isIncognito() === false) {
  // Handle normal mode
}

isInAppBrowser()

Detects if the current browsing context is an in-app browser and identifies the browser name if applicable.

Parameters

None

Returns

Object: An object containing two properties:

  • isInAppBrowser (boolean): Indicates whether the current browsing context is an in-app browser (true) or not (false).
  • browserName (string | null): The name of the in-app browser if detected, or null if not detected.
Example

The following example demonstrates how to use the isInAppBrowser function to check if the current context is an in-app browser and log the browser name if applicable:

import { isInAppBrowser } from '@sesamy/sesamy-js';

// Detect if the current context is an in-app browser
const result = isInAppBrowser();

if (result.isInAppBrowser) {
  console.log(`Running inside an in-app browser: ${result.browserName}`);
} else {
  console.log('Not running inside an in-app browser');
}
Details
  • A predefined list of common in-app browsers (e.g., Facebook, Instagram, LinkedIn, etc.) is checked against the user agent.
  • If a match is found, the function returns isInAppBrowser: true and the corresponding browserName.
  • If no known in-app browser signatures are detected, the function returns isInAppBrowser: false and browserName: null.

Transforms

The transform module allows for dynamic content manipulation based on specified rules. This can include inserting, replacing, or removing elements on a webpage.

Configuration

The transform configuration is defined within the Config interface. The following properties are available:

  • enabled (boolean, optional): Enables or disables the transform module.
  • rules (array): An array of rule objects that define the transformations to apply.

Each rule object contains the following properties:

  • selector (string): A CSS selector to target elements on the page.
  • transform (string): The type of transformation to apply. Valid values are 'insert', 'replace', 'remove', 'gradient', and 'wrap'.
  • content (string, optional): The content to insert or replace. Required for 'insert' and 'replace' transforms.
  • 'insertPosition' (string, optional): The position to insert the content. Valid values are 'before', 'after' and 'insider'.
  • contentType (string, optional): Specifies the type of content. Valid values are 'html', 'selector', and 'url'.
  • path (string, optional): A regular expression to match the URL path. If provided, the rule will only apply when the path matches the current URL.
  • entitlement (string, optional): Specifies an entitlement required for the rule to apply.
  • authenticated (boolean, optional): Specifies if the rule should only apply to authenticated users.

Example Configuration

Below is an example configuration for the transform module:

{
  "transform": {
    "enabled": true,
    "rules": [
      {
        "selector": "#example",
        "transform": "replace",
        "content": "<p>New content</p>",
        "contentType": "html"
      },
      {
        "selector": ".ad-banner",
        "transform": "remove"
      },
      {
        "selector": ".insert-content",
        "transform": "insert",
        "content": "#source-element",
        "contentType": "selector"
      },
      {
        "selector": ".load-from-url",
        "transform": "insert",
        "content": "https://example.com/content",
        "contentType": "url"
      }
    ]
  }
}
Usage

To use the transform module, include the configuration in your initialization script:

<script type="application/json" id="sesamy-js">
  {
    "clientId": "demo",
    "transform": {
      "enabled": true,
      "rules": [
        {
          "selector": "#example",
          "transform": "replace",
          "content": "<p>New content</p>",
          "contentType": "html"
        },
        {
          "selector": ".ad-banner",
          "transform": "remove"
        },
        {
          "selector": ".insert-content",
          "transform": "insert",
          "content": "#source-element",
          "contentType": "selector"
        },
        {
          "selector": ".load-from-url",
          "transform": "insert",
          "content": "https://example.com/content",
          "contentType": "url"
        }
      ]
    }
  }
</script>

This configuration will replace the content of the element with the ID example, remove elements with the class ad-banner, insert the content of the element with the ID source-element into elements with the class insert-content, and load content from a URL into elements with the class load-from-url.

Content

The content module allows you to extract dynamic article data from a webpage based on specific selectors. This can include elements like the title, image, excerpt, price, and more.

content.getPropertyFromHTML(options: { publisherContentId?: string, key: string, defaultValue?: string })

Searches for a specified property in the HTML content, following a specific lookup hierarchy:

  1. First, it looks for a <sesamy-content-data> element with the given publisherContentId and checks for the property as an attribute.
  2. If not found, it checks for meta tags in the document head with the formats sesamy:{key}, og:{key}, or just {key}.
  3. If still not found, it returns the provided default value (empty string if no default specified).

Parameters

  • options (object): Options for retrieving the property.
    • publisherContentId (string, optional): The ID of the content to search for.
    • key (string): The name of the property to retrieve.
    • defaultValue (string, optional): The default value to return if the property is not found. Defaults to an empty string.
Returns
  • string: The value of the property if found, or the default value.
Example
// Get the title from HTML content
const title = window.sesamy.content.getPropertyFromHTML({
  publisherContentId: 'article-123',
  key: 'title',
  defaultValue: 'Untitled Article',
});

console.log('Article title:', title);

Configuration

The content configuration is defined within the Config json. The following properties are available:

Content Node Properties
  • article (object): Defines the selector for the article element itself.
  • image (object): Specifies the selector and attribute for extracting article images.
  • title (object): Specifies the selector and attribute for extracting the article title.
  • excerpt (object): Specifies the selector and attribute for extracting the article excerpt.
  • price (object): Specifies the selector and attribute for extracting the article price.
  • currency (object): Specifies the selector and attribute for extracting the article currency.
  • url (object): Specifies the selector and attribute for extracting the article URL.
  • id (object): Specifies the selector and attribute for extracting the article ID.

Each field object contains the following properties:

  • selector (string): A CSS selector to target elements on the page.
  • attribute (string, optional): The attribute to retrieve from the selected element. If not specified, the text content of the element is used.
Feature Flags
enablePaywallSettingsUrlFallback

Type: boolean Default: false Location: Per content node in content[].enablePaywallSettingsUrlFallback

When enabled on a content node, this feature flag allows the content module to fall back to checking for a settings-url attribute on <sesamy-paywall> elements when no paywallUrl is found through the standard detection methods (meta tags or article attributes).

Use Case: This is useful for pages that use the <sesamy-paywall> custom element but don't explicitly set the paywall URL in meta tags or on the article element. The paywall component may have a settings-url attribute that points to the paywall configuration.

Priority Order:

  1. Article element paywall-url attribute
  2. Content configuration paywallUrl property
  3. Meta tags (sesamy:paywall-url, og:paywall-url, etc.)
  4. If enablePaywallSettingsUrlFallback is true: <sesamy-paywall settings-url="..."> attribute

Example:

// Enable the fallback feature
{
  clientId: "demo",
  content: [
    {
      type: 'article',
      enablePaywallSettingsUrlFallback: true,
      selectors: {
        article: { selector: 'sesamy-article' }
      }
    }
  ]
}
<!-- Page with sesamy-paywall element -->
<sesamy-paywall settings-url="https://example.com/api/paywalls/123"></sesamy-paywall>
<sesamy-article item-src="https://example.com/article/456">
  <!-- Article content -->
</sesamy-article>

<script>
  // The content.get() method will now find the paywall URL from the sesamy-paywall element
  const article = window.sesamy.content.get('sesamy-article');
  console.log(article.paywallUrl); // "https://example.com/api/paywalls/123"
</script>
Example Configuration

Below is an example configuration for the content module:

{
  "content": {
    "article": {
      "selector": "article"
    },
    "image": {
      "selector": "img",
      "attribute": "src"
    },
    "title": {
      "selector": "h1",
      "attribute": "textContent"
    },
    "excerpt": {
      "selector": "p",
      "attribute": "textContent"
    },
    "price": {
      "selector": "article",
      "attribute": "data-price"
    },
    "currency": {
      "selector": "article",
      "attribute": "data-currency"
    },
    "url": {
      "selector": "link",
      "attribute": "href"
    },
    "id": {
      "selector": "article",
      "attribute": "data-id"
    }
  }
}
Usage

To use the content module, initialize it with the appropriate configuration:

import { init } from '@sesamy/sesamy-js';

init({
  content: {
    article: { selector: 'article' },
    image: { selector: 'img', attribute: 'src' },
    title: { selector: 'h1', attribute: 'textContent' },
    excerpt: { selector: 'p', attribute: 'textContent' },
    price: { selector: 'article', attribute: 'data-price' },
    currency: { selector: 'article', attribute: 'data-currency' },
    url: { selector: 'link', attribute: 'href' },
    id: { selector: 'article', attribute: 'data-id' },
  },
});
Methods
list()

Returns an array of article objects containing the extracted data for each article on the page.

Each article object contains the following properties:

  • title (string, optional): The title of the article.
  • excerpt (string, optional): The article's excerpt.
  • image (string, optional): The source URL of the article's image.s
  • price (number, optional): The price of the article.
  • currency (string, optional): The currency of the article price.
  • url (string, optional): The URL of the article.
  • id (string, optional): The article's unique ID.
  • element (Element): The original DOM element for the article.
Example Usage
import { init } from '@sesamy/sesamy-js';

const sesamyjs = await init({ ...config });

// Extract and log all content
const articles = sesamy.content.list();
console.log(articles);

In this example, content.list() will return an array of articles extracted from the page based on the configured selectors. Each article object contains fields such as title, excerpt, image, price, currency, URL, and ID.

get(articleElementOrSelector: Element | string)

Extracts article data from a specific element on the page.

Parameters
  • articleElementOrSelector (Element | string): Either a DOM element or a CSS selector string identifying the article element.
Returns
  • Article | null: An article object containing the extracted data, or null if the element is not found.

The returned article object contains the following properties:

  • title (string, optional): The title of the article.
  • excerpt (string, optional): The article's excerpt.
  • image (string, optional): The source URL of the article's image.
  • price (number, optional): The price of the article.
  • currency (string, optional): The currency of the article price.
  • url (string, optional): The URL of the article.
  • id (string, optional): The article's unique ID.
  • pass (string, optional): Comma-separated list of passes required for access.
  • paywallUrl (string, optional): URL to the paywall configuration.
  • accessLevel ('public' | 'logged-in' | 'entitlement', optional): The access level required for the content.
  • selector (string): The CSS selector for the article element.
  • element (Element): The original DOM element for the article.
  • hasAccess (boolean, optional): Whether the user has access to the content. Set by hasAccess() method.
  • entitlement (Entitlement, optional): The entitlement object if access is granted via entitlement. Set by hasAccess() method.
Example Usage
// Get article data by CSS selector
const article = window.sesamy.content.get('article.premium-content');
console.log('Article:', article);

// Get article data by DOM element
const element = document.querySelector('.my-article');
const article = window.sesamy.content.get(element);
console.log('Article:', article);
hasAccess(articleElementOrSelector: Element | string)

Checks if the current user has access to the specified article. This method intelligently determines the access requirements based on the article's paywall configuration and decorates the article with access status and entitlement information.

Parameters
  • articleElementOrSelector (Element | string): Either a DOM element or a CSS selector string identifying the article element.
Returns
  • Promise<Article>: A promise that resolves to the article object decorated with access information:
    • hasAccess (boolean): true if the user has access, false otherwise
    • entitlement (Entitlement, optional): The entitlement object if access is granted via entitlement
    • All other article properties (title, url, etc.)
Behavior
  1. Paywall-based Access: If the article has a paywallUrl, the method fetches the paywall configuration to determine the access type based on the paywall template:

    • Login Paywall (template: 'LOGIN'): Sets accessLevel to 'logged-in', checks if the user is authenticated, and sets hasAccess accordingly.
    • Entitlement Paywall (template: 'BOXES'): Sets accessLevel to 'entitlement', checks for entitlement, and sets both hasAccess and entitlement.
  2. Standard Entitlement Check: If no paywallUrl is specified, the method uses the article's url and pass properties to check for entitlement access, setting both hasAccess and entitlement.

Example Usage
// Check access for an article
const entitlement = await window.sesamy.content.hasAccess('.premium-article');

if (entitlement) {
  console.log('User has access via entitlement:', entitlement.id);
  // Show premium content
} else {
  console.log('User does not have access');
  // Show paywall or login prompt
}

// Use with async/await
async function checkArticleAccess() {
  try {
    const entitlement = await window.sesamy.content.hasAccess('article#main');

    if (entitlement) {
      // Unlock or display content
      console.log('Access granted');

      // Access entitlement details if available
      console.log('Entitlement type:', entitlement.type);
      console.log('Entitlement SKU:', entitlement.sku);
    } else {
      // Redirect to paywall
      const article = window.sesamy.content.get('article#main');
      console.log('Access denied, redirect to:', article.paywallUrl);
    }
  } catch (error) {
    console.error('Error checking access:', error);
  }
}
unlock(articleElementOrSelector: Element | string, lockedContentSelector?: string)

Retrieves and unlocks premium content for an article that the user has entitlement access to.

Parameters
  • articleElementOrSelector (Element | string): Either a DOM element or a CSS selector string identifying the article element.
  • lockedContentSelector (string, optional): A CSS selector for the specific locked content to retrieve. If not provided, uses the parent element of the article.
Returns
  • Promise<string>: A promise that resolves to the unlocked HTML content.
Throws
  • Error if the article element cannot be found.
  • Error if the article doesn't have a URL.
  • Error if the user doesn't have access to the content.
  • Error if the access token cannot be retrieved.
Example Usage
// Unlock content and replace the locked element
async function unlockArticle() {
  try {
    const unlockedContent = await window.sesamy.content.unlock('.premium-article');

    // Replace the locked content with the unlocked content
    const article = document.querySelector('.premium-article');
    if (article && article.parentElement) {
      article.parentElement.innerHTML = unlockedContent;
    }
  } catch (error) {
    console.error('Failed to unlock content:', error);
  }
}

// Unlock specific content within an article
async function unlockSpecificContent() {
  const unlockedContent = await window.sesamy.content.unlock('article.premium', '.locked-section');

  const lockedSection = document.querySelector('.locked-section');
  if (lockedSection) {
    lockedSection.innerHTML = unlockedContent;
  }
}
content.showModal(options: ModalOptions)

Opens the Sesamy paywall modal. Requires sesamy-components to be loaded (included by the bootstrap loader by default; otherwise load @sesamy/open-web-components yourself).

Parameters
  • options (ModalOptions):
    • articleElementOrSelector (Element | string, optional): Article whose metadata seeds the modal. Defaults to the first matched article.
    • paywallId (string, optional): Paywall configuration to render. Falls back to the article's paywallUrl selector.
    • onClose (() => void, optional): Called when the user dismisses the modal.
Returns
  • Promise<ModalResult>: Resolves with { action: 'purchased' | 'closed' | 'login' } when the modal is closed.
Example
const result = await window.sesamy.content.showModal({
  articleElementOrSelector: 'article#main',
});

if (result.action === 'purchased') {
  await window.sesamy.content.unlock('article#main');
}
content.showNotificationBar(options: NotificationBarOptions)

Shows an inline notification bar pinned to the top or bottom of the viewport. Useful for unobtrusive prompts (e.g. "Subscribe for unlimited access") that don't block reading.

Parameters
  • options (NotificationBarOptions):
    • position ('top' | 'bottom'): Where to attach the bar.
    • articleElementOrSelector (Element | string, optional): Source of metadata.
    • paywallId (string, optional): Paywall configuration.
    • onClose (() => void, optional): Called on dismissal.
Returns
  • Promise<NotificationBarResult>: Resolves with the user action when the bar is dismissed.
Example
window.sesamy.content.showNotificationBar({
  position: 'bottom',
  articleElementOrSelector: 'article#main',
});
Flags API

The Flags API allows for client-side feature flag management. These flags are stored in the browser's localStorage and can be used to enable or disable features for specific users.

flags.get(key: string)

Retrieves the value of a specific feature flag.

Parameters
  • key (string): The name of the flag to retrieve.
Returns
  • Promise<boolean | string | number | undefined>: A promise that resolves to the flag's value if found, or undefined if the flag doesn't exist.
Example
// Check if a specific feature flag is enabled
window.sesamy.flags.get('my-feature-flag').then((value) => {
  if (value === true) {
    console.log('Feature is enabled');
  } else {
    console.log('Feature is disabled or not set');
  }
});

flags.set(key: string, value: boolean | string | number)

Sets the value of a specific feature flag.

Parameters
  • key (string): The name of the flag to set.
  • value (boolean | string | number): The value to assign to the flag.
Returns
  • Promise<void>: A promise that resolves when the flag has been set.
Example
// Enable a feature flag
window.sesamy.flags.set('my-feature-flag', true).then(() => {
  console.log('Feature flag has been enabled');
});

// Set a numeric flag value
window.sesamy.flags.set('max-items', 5).then(() => {
  console.log('Max items value has been set');
});

flags.list()

Retrieves all feature flags.

Returns
  • Promise<Record<string, boolean | string | number>>: A promise that resolves to an object containing all flag key-value pairs.
Example
// List all feature flags
window.sesamy.flags.list().then((flags) => {
  console.log('All feature flags:', flags);
});

flags.delete(key: string)

Deletes a specific feature flag.

Parameters
  • key (string): The name of the flag to delete.
Returns
  • Promise<void>: A promise that resolves when the flag has been deleted.
Example
// Delete a feature flag
window.sesamy.flags.delete('my-feature-flag').then(() => {
  console.log('Feature flag has been deleted');
});

Amendments API

The Amendments API allows for managing contract amendments, such as adding discounts to existing contracts.

amendments.create(params: { contractId: string; discountCode: string; amendmentType: 'DISCOUNT' })

Creates an amendment for a contract, such as applying a discount code.

Parameters

  • params (object): The parameters for creating the amendment.
    • contractId (string): The ID of the contract to amend.
    • discountCode (string): The discount code to apply.
    • amendmentType (string): The type of amendment, currently only 'DISCOUNT' is supported.
Returns
  • Promise<object>: A promise that resolves to the created amendment object.
Example
// Apply a discount code to a contract
window.sesamy.amendments
  .create({
    contractId: 'contract-123',
    discountCode: 'SUMMER2023',
    amendmentType: 'DISCOUNT',
  })
  .then((amendment) => {
    console.log('Amendment created:', amendment);
  })
  .catch((error) => {
    console.error('Error creating amendment:', error);
  });

amendments.confirm(amendmentId: string)

Confirms a previously created amendment.

Parameters
  • amendmentId (string): The ID of the amendment to confirm.
Returns
  • Promise<boolean>: A promise that resolves to true if the amendment was successfully confirmed.
Example
// Confirm an amendment
window.sesamy.amendments
  .confirm('amendment-123')
  .then((success) => {
    if (success) {
      console.log('Amendment confirmed successfully');
    }
  })
  .catch((error) => {
    console.error('Error confirming amendment:', error);
  });

Products API

The Products API provides methods for working with Sesamy products, including retrieving product information and linking accounts.

products.get(sku: string)

Retrieves detailed information about a product by its SKU.

Parameters

  • sku (string): The Stock Keeping Unit (SKU) identifier for the product.
Returns
  • Promise<Product>: A promise that resolves to the product object.
Example
// Get product information by SKU
window.sesamy.products
  .get('sid:eUv45QXTrcGNhMJpaCQNe')
  .then((product) => {
    console.log('Product details:', product);
    console.log('Product name:', product.name);
    console.log('Product price:', product.price);
  })
  .catch((error) => {
    console.error('Error fetching product:', error);
  });

products.autoOnboard(sku: string)

Triggers the auto-onboarding process for a product by SKU, which helps users get started with a product they've purchased.

Parameters
  • sku (string): The Stock Keeping Unit (SKU) identifier for the product.
Returns
  • Promise<boolean>: A promise that resolves to true if the auto-onboarding process was successfully initiated.
Example
// Trigger auto-onboarding for a product
window.sesamy.products
  .autoOnboard('sid:eUv45QXTrcGNhMJpaCQNe')
  .then((success) => {
    if (success) {
      console.log('Auto-onboarding process initiated successfully');
    }
  })
  .catch((error) => {
    console.error('Error triggering auto-onboarding:', error);
  });

products.linkSpotify()

Links a user's Spotify account to enable Sesamy products that integrate with Spotify.

Returns
  • Promise<boolean>: A promise that resolves to true if the Spotify account was successfully linked.
Example
// Link the user's Spotify account
window.sesamy.products
  .linkSpotify()
  .then((success) => {
    if (success) {
      console.log('Spotify account linked successfully');
    }
  })
  .catch((error) => {
    console.error('Error linking Spotify account:', error);
  });

Tags API

The Tags API allows for managing user tags, which can be used for user segmentation and personalization.

tags.list()

Fetches all tags associated with the current user.

Returns

  • Promise<string[]>: A promise that resolves to an array of tag strings.
Example
// Get all tags for the current user
window.sesamy.tags
  .list()
  .then((tags) => {
    console.log('User tags:', tags);
  })
  .catch((error) => {
    console.error('Error fetching tags:', error);
  });

tags.set(tag: string)

Sets a tag for the current user. If the tag already exists, it won't create a duplicate.

Parameters
  • tag (string): The tag to associate with the user.
Returns
  • Promise<boolean>: A promise that resolves to true if the tag was successfully set.
Example
// Set a tag for the current user
window.sesamy.tags
  .set('premium-subscriber')
  .then((success) => {
    if (success) {
      console.log('Tag set successfully');
    }
  })
  .catch((error) => {
    console.error('Error setting tag:', error);
  });

tags.delete(tag: string)

Deletes a specific tag from the current user.

Parameters
  • tag (string): The tag to remove from the user.
Returns
  • Promise<boolean>: A promise that resolves to true if the tag was successfully deleted.
Example
// Delete a tag from the current user
window.sesamy.tags
  .delete('trial-user')
  .then((success) => {
    if (success) {
      console.log('Tag deleted successfully');
    }
  })
  .catch((error) => {
    console.error('Error deleting tag:', error);
  });

Tallies API

The Tallies API allows for tracking counts of various user activities or metrics.

tallies.list()

Lists all tallies for the current user.

Returns

  • Promise<Tally[]>: A promise that resolves to an array of tally objects.
Example
// List all tallies for the current user
window.sesamy.tallies
  .list()
  .then((tallies) => {
    console.log('User tallies:', tallies);
  })
  .catch((error) => {
    console.error('Error listing tallies:', error);
  });

tallies.get(id: string)

Retrieves a specific tally by its ID.

Parameters
  • id (string): The ID of the tally to retrieve.
Returns
  • Promise<Tally>: A promise that resolves to the tally object.
Example
// Get a specific tally by ID
window.sesamy.tallies
  .get('article-views')
  .then((tally) => {
    console.log('Tally:', tally);
    console.log('Current count:', tally.count);
  })
  .catch((error) => {
    console.error('Error getting tally:', error);
  });

tallies.push(id: string, item: any)

Adds an item to a specific tally, incrementing its count.

Parameters
  • id (string): The ID of the tally to update.
  • item (any): The item to add to the tally.
Returns
  • Promise<Tally>: A promise that resolves to the updated tally object.
Example
// Increment an article view tally
window.sesamy.tallies
  .push('article-views', { articleId: 'sid:eUv45QXTrcGNhMJpaCQNe', timestamp: new Date() })
  .then((updatedTally) => {
    console.log('Updated tally:', updatedTally);
    console.log('New count:', updatedTally.count);
  })
  .catch((error) => {
    console.error('Error updating tally:', error);
  });

User Metadata API

The User Metadata API allows for storing and retrieving custom metadata associated with users.

userMetadata.list()

Lists all metadata items for the current user.

Returns

  • Promise<Record<string, any>>: A promise that resolves to an object containing all metadata key-value pairs.
Example
// List all user metadata
window.sesamy.userMetadata
  .list()
  .then((metadata) => {
    console.log('User metadata:', metadata);
  })
  .catch((error) => {
    console.error('Error listing user metadata:', error);
  });

userMetadata.get(id: string)

Retrieves a specific metadata item by its ID.

Parameters
  • id (string): The ID of the metadata item to retrieve.
Returns
  • Promise<any>: A promise that resolves to the value of the metadata item.
Example
// Get a specific metadata item
window.sesamy.userMetadata
  .get('preferences')
  .then((value) => {
    console.log('User preferences:', value);
  })
  .catch((error) => {
    console.error('Error getting metadata:', error);
  });

userMetadata.set(id: string, value: any)

Sets a metadata item for the current user.

Parameters
  • id (string): The ID of the metadata item to set.
  • value (any): The value to assign to the metadata item.
Returns
  • Promise<boolean>: A promise that resolves to true if the metadata item was successfully set.
Example
// Set a user preference metadata item
window.sesamy.userMetadata
  .set('preferences', { theme: 'dark', fontSize: 'large' })
  .then((success) => {
    if (success) {
      console.log('User preferences saved successfully');
    }
  })
  .catch((error) => {
    console.error('Error setting metadata:', error);
  });

userMetadata.delete(id: string)

Deletes a specific metadata item by its ID.

Parameters
  • id (string): The ID of the metadata item to delete.
Returns
  • Promise<boolean>: A promise that resolves to true if the metadata item was successfully deleted.
Example
// Delete a metadata item
window.sesamy.userMetadata
  .delete('temporary-setting')
  .then((success) => {
    if (success) {
      console.log('Metadata item deleted successfully');
    }
  })
  .catch((error) => {
    console.error('Error deleting metadata:', error);
  });

Vendors API

The Vendors API provides methods for retrieving information about vendors (publishers) connected to a user.

vendors.get()

Fetches settings for the current vendor based on the authenticated user context.

Returns

  • Promise<VendorSettings>: A promise that resolves to the vendor settings object.
Example
// Get current vendor settings
window.sesamy.vendors
  .get()
  .then((settings) => {
    console.log('Vendor settings:', settings);
    console.log('Vendor name:', settings.name);
    console.log('Vendor currency:', settings.currency);
  })
  .catch((error) => {
    console.error('Error fetching vendor settings:', error);
  });

vendors.list()

Lists all publishers connected to the user. This method is not available for publisher tokens.

Returns
  • Promise<Vendor[]>: A promise that resolves to an array of vendor objects.
Example
// List all vendors connected to the user
window.sesamy.vendors
  .list()
  .then((vendors) => {
    console.log('Connected vendors:', vendors);
    vendors.forEach((vendor) => {
      console.log('Vendor name:', vendor.name);
      console.log('Vendor ID:', vendor.id);
    });
  })
  .catch((error) => {
    console.error('Error listing vendors:', error);
  });

Contracts API

The Contracts API provides methods for managing user contracts, including subscription services.

contracts.list()

Lists all contracts associated with the current user.

Returns

  • Promise<Contract[]>: A promise that resolves to an array of contract objects.
Example
// List all user contracts
window.sesamy.contracts
  .list()
  .then((contracts) => {
    console.log('User contracts:', contracts);
    contracts.forEach((contract) => {
      console.log('Contract ID:', contract.id);
      console.log('Contract status:', contract.status);
      console.log('Contract start date:', contract.startDate);
    });
  })
  .catch((error) => {
    console.error('Error listing contracts:', error);
  });

contracts.get(id: string)

Retrieves a specific contract by its ID.

Parameters
  • id (string): The ID of the contract to retrieve.
Returns
  • Promise<Contract>: A promise that resolves to the contract object.
Example
// Get a specific contract by ID
window.sesamy.contracts
  .get('contract-123')
  .then((contract) => {
    console.log('Contract details:', contract);
    console.log('Contract status:', contract.status);
    console.log('Contract type:', contract.type);
  })
  .catch((error) => {
    console.error('Error fetching contract:', error);
  });

contracts.cancel(id: string)

Cancels a specific contract by its ID.

Parameters
  • id (string): The ID of the contract to cancel.
Returns
  • Promise<Contract>: A promise that resolves to the updated contract object with its status set to canceling or canceled.
Example
// Cancel a contract
window.sesamy.contracts
  .cancel('contract-123')
  .then((contract) => {
    console.log('Contract canceled successfully');
    console.log('Updated contract status:', contract.status);
  })
  .catch((error) => {
    console.error('Error canceling contract:', error);
  });

Bills API

The Bills API allows for retrieving information about user bills.

bills.list()

Lists all bills associated with the current user.

Returns

  • Promise<Bill[]>: A promise that resolves to an array of bill objects.
Example
// List all user bills
window.sesamy.bills
  .list()
  .then((bills) => {
    console.log('User bills:', bills);
    bills.forEach((bill) => {
      console.log('Bill ID:', bill.id);
      console.log('Amount:', bill.amount);
      console.log('Due date:', bill.dueDate);
      console.log('Status:', bill.status);
    });
  })
  .catch((error) => {
    console.error('Error listing bills:', error);
  });

bills.get(id: string)

Retrieves a specific bill by its ID.

Parameters
  • id (string): The ID of the bill to retrieve.
Returns
  • Promise<Bill>: A promise that resolves to the bill object.
Example
// Get a specific bill by ID
window.sesamy.bills
  .get('bill-123')
  .then((bill) => {
    console.log('Bill details:', bill);
    console.log('Amount:', bill.amount);
    console.log('Status:', bill.status);
    console.log('Due date:', bill.dueDate);
  })
  .catch((error) => {
    console.error('Error fetching bill:', error);
  });

Transactions API

The Transactions API allows for retrieving information about user transactions.

transactions.list()

Lists all transactions associated with the current user.

Returns

  • Promise<Transaction[]>: A promise that resolves to an array of transaction objects.
Example
// List all user transactions
window.sesamy.transactions
  .list()
  .then((transactions) => {
    console.log('User transactions:', transactions);
    transactions.forEach((transaction) => {
      console.log('Transaction ID:', transaction.id);
      console.log('Amount:', transaction.amount);
      console.log('Date:', transaction.createdAt);
      console.log('Status:', transaction.status);
    });
  })
  .catch((error) => {
    console.error('Error listing transactions:', error);
  });

transactions.get(id: string)

Retrieves a specific transaction by its ID.

Parameters
  • id (string): The ID of the transaction to retrieve.
Returns
  • Promise<Transaction>: A promise that resolves to the transaction object.
Example
// Get a specific transaction by ID
window.sesamy.transactions
  .get('transaction-123')
  .then((transaction) => {
    console.log('Transaction details:', transaction);
    console.log('Amount:', transaction.amount);
    console.log('Status:', transaction.status);
    console.log('Date:', transaction.createdAt);
  })
  .catch((error) => {
    console.error('Error fetching transaction:', error);
  });

Capsule (DCA) API

Available when capsule.enabled is true in the config and the capsule plugin is registered (auto-loaded by the bootstrap, or registered via window.capsulePlugin / init(config, { capsulePlugin })).

capsule.processPage()

Detects every DCA manifest currently in the DOM, calls the unlock endpoint for each, decrypts the payload, and injects the plaintext into the matching data-dca-content-name placeholder. Called automatically on page load when capsule.autoProcess is true (default) and again whenever the SPA mutates new DCA blocks into the DOM.

Returns

Promise<void> — resolves once every detected manifest has been processed (or has failed gracefully).

Example
// Manually retry decryption after a login completes
window.addEventListener('sesamyJsAuthenticated', async () => {
  await window.sesamy.capsule.processPage();
});

capsule.getClient()

Returns the underlying @sesamy/capsule DCA client. Use this if you need lower-level access (custom resource fetchers, manual decryption, advanced introspection). Returns undefined when capsule is disabled or the plugin failed to load.

Example
const dca = window.sesamy.capsule.getClient();
const decoded = dca?.decodeManifest(rawManifest);

Available always; gates analytics storage when consent.enabled is true in the config. Integrate with your CMP via the consent.cmp config or the onConsentChange callback, or drive consent imperatively from these functions.

consent.get()

Returns the current consent state — an object with statistics and marketing booleans.

Example

const state = window.sesamy.consent.get();
if (state.statistics) {
  // analytics storage is allowed
}

consent.set(state: Partial<ConsentState>)

Updates one or more consent flags and re-evaluates analytics storage immediately.

Parameters
  • state (Partial<ConsentState>): Partial consent object — only the keys you want to change need to be provided.
Example
// User accepted statistics but not marketing
window.sesamy.consent.set({ statistics: true, marketing: false });

consent.has(type: 'statistics' | 'marketing')

Returns true when the named consent flag is granted.

Example
if (window.sesamy.consent.has('marketing')) {
  loadMarketingPixel();
}

Diagnostics API

Tools to capture a snapshot of the user's runtime state for support tickets. Both methods read profile, entitlements, contracts, tags, and tallies via the already-initialised API.

diagnostics.collect(fallbackId?: string)

Returns the diagnostics payload as an object without uploading it — useful if you want to render it in your own support form.

Parameters

  • fallbackId (string, optional): Identifier used in the payload when no authenticated user id is available.
Returns

Promise<DiagnosticsPayload> — profile, entitlements, contracts, tags, tallies, library version, and environment metadata.

diagnostics.send(fallbackId?: string)

Collects diagnostics and uploads them to the Sesamy diagnostics endpoint. Returns the diagnostics id you can paste into a support ticket.

Parameters
  • fallbackId (string, optional): Same as collect.
Returns

Promise<{ id: string }>.

Example
async function reportProblem() {
  const { id } = await window.sesamy.diagnostics.send();
  alert(`Diagnostics submitted — reference: ${id}`);
}

You can also trigger this without writing any code by appending ?sesamy-user-diagnostics=true to the URL — sesamy-js will collect and submit automatically once initialisation completes.

Polyfills

The library polyfills the following methods for compatibility with older browsers:

  • URL
  • URLSearchParams
  • fetch

Notes

  • The content property is required for 'insert' and 'replace' transforms.
  • The contentType property specifies how to interpret the content property: as raw HTML, a CSS selector, or a URL to fetch content from.
  • The path property can be used to apply rules conditionally based on the current URL.
  • The authenticated property ensures that rules only apply to authenticated users if set to true.

Attribution

The library tracks the following data for attribution purposes and pass it on to the checkout when initiating a purchase:

  • utm_source: The source of the traffic.
  • utm_medium: The medium of the traffic.
  • utm_campaign: The campaign associated with the traffic.
  • utm_term: The term associated with the traffic.
  • utm_content: The content associated with the traffic.
  • ref: The referrer passed in the querystring.
  • referrer: The referrer URL of the initial page load.
  • item-src: The url of the last locked article viewed.

Events API

The Events API allows for emitting custom events that can be listened to and optionally canceled by other scripts on the page.

events.emit(eventName: string, data?: Record<string, any>, cancelable?: boolean)

Emits a custom event that can optionally be canceled by event listeners.

Parameters

  • eventName (string): The name of the event to emit.
  • data (Record<string, any>, optional): Additional data to include with the event.
  • cancelable (boolean, optional): Whether the event can be canceled by listeners. Defaults to false.
Returns
  • { canceled: boolean, message?: string }: An object indicating if the event was canceled and any cancellation message.
Example
// Emit a non-cancelable event
window.sesamy.events.emit('article-viewed', { articleId: '12345' });

// Emit a cancelable event and check if it was canceled
const result = window.sesamy.events.emit('purchase-initiated', { productId: 'premium-sub' }, true);

if (result.canceled) {
  console.log(`Purchase was canceled: ${result.message}`);
} else {
  // Proceed with purchase flow
  proceedWithPurchase();
}

events.cancel(event: CustomEvent<CancelableEventDetail>, message?: string)

Cancels an event with an optional message explaining the reason.

Parameters
  • event (CustomEvent): The event to cancel.
  • message (string, optional): A message explaining why the event was canceled.
Returns
  • void
Example
// Listen for a cancelable event
window.addEventListener('purchase-initiated', (event) => {
  // Check if user already owns the product
  if (userOwnsProduct(event.detail.data.productId)) {
    // Cancel the event with a message
    window.sesamy.events.cancel(event, 'User already owns this product');
  }
});
Use Cases

The Events API can be used for various scenarios where you need to communicate between different components or scripts:

  1. Purchase Flow Interception: Allow third-party scripts to intercept and potentially cancel purchase flows.
  2. Content Locking: Emit events when content is about to be locked/unlocked and allow other scripts to modify this behavior.
  3. User Authentication: Notify when users are about to be authenticated and allow other scripts to intervene.
  4. Analytics: Emit events for key user interactions that other scripts might want to track.

Events emitted through this API are also automatically tracked in analytics with the prefix event:.

While sesamy-js provides generateLink which automatically signs links if the user is authenticated, you can also use the @sesamy/sdk package directly to generate unsigned links without requiring authentication. This is useful for generating shareable links or links for unauthenticated users.

import { client } from '@sesamy/sdk';

// Generate a checkout link (no authentication required)
const checkoutUrl = client.checkout.generateLink(
  { apiUrl: 'https://api-proxy.example.com' },
  {
    items: [{ sku: 'premium-monthly' }],
    email: 'user@example.com',
    language: 'en',
    redirectUrl: 'https://example.com/success',
    requireAddress: true,
    giftMode: false,
    metadata: {
      campaignId: 'summer_2024',
      source: 'newsletter',
    },
  }
);

// Generate account management links
const accountUrl = client.links.generateAccountLink(
  { baseUrl: 'https://app.example.com', clientId: 'your-client-id' },
  { language: 'en', redirectUrl: 'https://example.com' }
);

// Generate change payment link
const changePaymentUrl = client.links.generateChangePaymentLink(
  { baseUrl: 'https://app.example.com', clientId: 'your-client-id' },
  { contractId: 'contract-123', language: 'en' }
);

// Generate consume content link
const consumeUrl = client.links.generateConsumeLink(
  { baseUrl: 'https://app.example.com', clientId: 'your-client-id' },
  { sku: 'product-123', language: 'en' }
);
  • sesamy-js generateLink: Includes authentication token in hash if user is authenticated, automatically includes tracking cookies and attribution data, supports link shortening via TTL
  • SDK links.*: Pure URL generation without authentication, useful for generating shareable links, links for unauthenticated users, or backend link generation

Debugging

sesamy-js has several debug surfaces that are off by default and zero-cost when off:

  • Verbose runtime logs. Append ?sesamy-debug=true to the URL or set localStorage.debug = true. Calls to sesamy.log(...) and the SDK's internal logger flush to the console.
  • Bootstrap logs. Pass debug: true to sesamyBootstrap(...) (or the bootstrap config element). Emits [sesamy-boot] lines for chain entry selection, userinfo prefetch source, script load/error events, and fallback trigger reasons. Useful for diagnosing chain regressions without a HAR capture.
  • User diagnostics. Append ?sesamy-user-diagnostics=true to collect a snapshot of profile, entitlements, contracts, tags, and tallies and upload it to the Sesamy diagnostics endpoint. The payload id is logged to the console for support tickets — see Diagnostics API.
  • Library version. sesamy.getVersion() returns the running version, in case multiple bundles end up on the page.