Docs

JavaScript SDK

Documentation

JavaScript SDK Reference

Find the main SpryUI JavaScript initialization options and lifecycle methods for browser integrations, privacy controls, and navigation.

Initialize once

Install with the JavaScript guide, then call:

Snippetts
import { initSpryUi } from "@spryui/sdk";
const sdk = initSpryUi({ publicKey: "YOUR_PROJECT_PUBLIC_KEY" });

Common options

publicKey
Required. Your project’s public key.
env
PRODUCTION (default), STAGING, or DEVELOPMENT. Match the banner’s environment.
debug
Show the diagnostic panel while testing.
onReady / onError
Callbacks for loaded messages and initialization errors.
targetingContext
Override visitor information used for targeting. All targeting fields and an example.
initialConfig
Supply a configuration already fetched for this page. Configuration fields and an example.

The package includes TypeScript definitions for the full options and return types.

targetingContext

Type: Partial<SpryUiTargetingContext>. Every field is optional when passed to initSpryUi(). Supply only the values you want to override; the browser fills in the page, device, referrer, and UTM values listed below.

Snippetts
import { initSpryUi } from "@spryui/sdk";

const sdk = initSpryUi({
  publicKey: "YOUR_PROJECT_PUBLIC_KEY",
  targetingContext: {
    country: "AU", // Example: replace with this visitor's country.
  },
});

Use the same options with SpryUI.initSpryUi() for the hosted script. Obtain the actual country from your own server or visitor data; the example does not perform a location lookup.

All targetingContext fields
Field and typeWhen omitted in the browserUse
pathstringCurrent URL pathname, such as /pricing.Override the page path used for matching. Query strings and fragments are not part of the path.
device"mobile" | "tablet" | "desktop"Detected from the browser viewport.Override the device category used by audience rules.
referrerstring | nulldocument.referrer, or null.The referring URL. Dashboard rules match a substring, ignoring case.
utmSourcestring | nullURL parameter utm_source, or null.Match a UTM source, ignoring case.
utmMediumstring | nullURL parameter utm_medium, or null.Match a UTM medium, ignoring case.
utmCampaignstring | nullURL parameter utm_campaign, or null.Match a UTM campaign, ignoring case.
countrystring | nullNot supplied automatically.Two-letter country code, such as AU or US. Matching ignores case and surrounding whitespace.
isFirstVisitbooleanNot supplied automatically.Set true when your integration knows this is the visitor's first visit.
isReturningVisitorbooleanNot supplied automatically.Set true when your integration knows the visitor has visited before.

Missing values and matching

A restricted banner needs a matching value. Without a country, a country-restricted banner does not appear. A first-visit rule needs isFirstVisit: true; a returning-visitor rule needs isReturningVisitor: true. Unrestricted banners do not need these values. Persistent storage alone does not populate visitor flags.

Supplied fields replace the browser values, including null or undefined. Omit a property entirely to keep its browser default. Avoid overriding path for normal navigation: sdk.refresh() reads the current URL again, but an explicit path override still takes precedence.

These values describe the visitor; the rules belong in the dashboard’s audience settings. Server rendering has no browser defaults: provide the context your server knows. Unknown values cannot satisfy a restriction; device-only checks may be deferred until the browser.

initialConfig

Type: SpryUiSdkConfigResponse. Use this when your server has already fetched the banner configuration. Pass the result of fetchSpryUiConfig() unchanged, rather than assembling message records by hand. A normal browser installation can omit it.

Fetch on the serverts
// Server code
import { fetchSpryUiConfig } from "@spryui/sdk/server";

const config = await fetchSpryUiConfig({
  publicKey: "YOUR_PROJECT_PUBLIC_KEY",
  host: "www.example.com", // Your site's approved hostname.
  env: "PRODUCTION",
});

// Return config through your framework's safely serialized page payload.
Pass to the browserts
// Browser code
import { initSpryUi, type SpryUiSdkConfigResponse } from "@spryui/sdk";

export function startBanners(config: SpryUiSdkConfigResponse) {
  return initSpryUi({
    publicKey: "YOUR_PROJECT_PUBLIC_KEY",
    env: config.environment,
    initialConfig: config,
  });
}

// Call startBanners with the config received in your page payload.

The helper returns the configuration object itself. If calling the HTTP API directly, use the response’s results object, not the full response envelope. Use your framework’s payload serialization; do not concatenate banner JSON into an inline script.

All initialConfig fields
Field and typeMeaning
projectIdstring · requiredThe project that owns these banners.
hoststring · requiredThe approved website hostname this configuration was fetched for.
environment"PRODUCTION" | "STAGING" | "DEVELOPMENT" · requiredThe environment represented by this configuration.
messagesSpryUiSdkMessage[] · requiredBanner records returned by SpryUI. An empty array is valid and means no banners to render from this configuration.
bannerPolicyBannerPolicy | null · optionalProject rules for rotating or stacking banners. See the nested fields below.
deliverySpryUiDeliveryStatus · optionalDelivery status and an optional reason, used by diagnostics. Older responses may omit it.

What happens at startup

  • The SDK consumes initialConfig once, skipping the initial browser token and configuration requests before rendering. Analytics can still require a token request.
  • Targeting, scheduling, frequency, dismissal, and variant checks still run in the browser. Supplying configuration does not force every banner to appear.
  • An empty messages array is used as supplied; it does not trigger a fallback configuration fetch.
  • sdk.refresh() makes a new request. Set env to the configuration’s environment so later requests use the same environment.

Fetch for the correct project and host, and keep visitor-specific pages out of shared caches. For Nuxt, the Nuxt module handles this handoff and delivery state for you; do not add a second initialization.

Nested bannerPolicy and delivery fields

defaults contains a policy for each of the four positions. rules optionally overrides a position on matching paths. intervalMs controls carousel timing; maxVisible limits stacked banners. Manage these in project banner behavior.

Snippetts
type BannerPosition =
  | "TOP_FIXED" | "BOTTOM_FIXED"
  | "TOP_RELATIVE" | "BOTTOM_RELATIVE";

interface BannerPositionPolicy {
  mode: "auto" | "carousel" | "stack";
  transition: "slide" | "fade";
  intervalMs?: number | null;
  maxVisible?: number | null;
}

interface BannerPolicy {
  defaults: Record<BannerPosition, BannerPositionPolicy>;
  rules?: Array<BannerPositionPolicy & {
    position: BannerPosition;
    paths: string[];
  }>;
}

delivery.status is READY, EMPTY, PAUSED, or BLOCKED. Optional delivery.reason is IMPRESSION_LIMIT, DOMAIN_NOT_ALLOWED, PROJECT_UNAVAILABLE, ACCOUNT_UNAVAILABLE, or NO_ACTIVE_MESSAGES. Keep these server-provided values unchanged; they explain delivery status in debug mode.

What messages contains

Each SpryUiSdkMessage contains identity (id or messId, projectId, name), delivery settings (environment, type, position, enabled, priority), and dashboard-authored content, targeting, schedule, and frequency objects.

Records also have createdAt and updatedAt; startAt, endAt, variants, selectedVariantId, and selectedVariantLabel are optional. These are returned banner data, not additional initialization switches. Preserve the full records from the server. The package exports SpryUiSdkMessage for inspecting their nested TypeScript types.

Lifecycle methods

  • sdk.refresh(): request current banners again, for example after a client-side route change.
  • sdk.destroy(): remove this instance and its banners when your integration unmounts.

Privacy controls

privacyMode defaults to anonymous. Use persistent only when your site intends to retain browser delivery history.

To record analytics only after consent, initialize with consentRequired: true and your current hasConsent value. Update it with sdk.setConsent(true) or sdk.setConsent(false). Use sdk.setOptOut(true) to stop analytics event recording for the visitor.

These controls affect analytics, not whether banners render. If your site requires consent before loading SpryUI at all, wait for that consent before initializing the SDK.