npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

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

About

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

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

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

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

Open Software & Tools

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

© 2026 – Pkg Stats / Ryan Hefner

@sesamy/sesamy-js

v1.121.0

Published

The Sesamy browser JavaScript API.

Readme

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/stable.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).

Bootstrap loader (recommended)

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/stable.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 | 'stable' | Version channel served by scripts-host. | | 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(),
});

BFF / cookie-based authentication

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/stable.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>;
  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 | — | Single custom Auth0 domain. | | 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.

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 }).

consent

| 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 default Sesamy auth domain.

{
  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
  • 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
    • delete: delete a tally by id
    • 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>

Links

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: '[email protected]',
  },
};

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: '[email protected]',
  },
};

// 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: '[email protected]',
  },
};

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);
  });

entitlements.signedLinks()

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;
};

generateLink(params: GenerateAccountLink | GenerateChangePaymentLink | GenerateConsumeLink | GenerateCheckoutLink | GenerateChangePlanLink)

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 (strings, optional): Analytics tracking cookies.
    • 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: '[email protected]',
  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: '[email protected]',
  payerEmail: '[email protected]',
  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) 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: '[email protected]