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:
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.
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.
| Field and type | When omitted in the browser | Use |
|---|---|---|
pathstring | Current 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 | null | document.referrer, or null. | The referring URL. Dashboard rules match a substring, ignoring case. |
utmSourcestring | null | URL parameter utm_source, or null. | Match a UTM source, ignoring case. |
utmMediumstring | null | URL parameter utm_medium, or null. | Match a UTM medium, ignoring case. |
utmCampaignstring | null | URL parameter utm_campaign, or null. | Match a UTM campaign, ignoring case. |
countrystring | null | Not supplied automatically. | Two-letter country code, such as AU or US. Matching ignores case and surrounding whitespace. |
isFirstVisitboolean | Not supplied automatically. | Set true when your integration knows this is the visitor's first visit. |
isReturningVisitorboolean | Not 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.
// 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.// 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.
| Field and type | Meaning |
|---|---|
projectIdstring · required | The project that owns these banners. |
hoststring · required | The approved website hostname this configuration was fetched for. |
environment"PRODUCTION" | "STAGING" | "DEVELOPMENT" · required | The environment represented by this configuration. |
messagesSpryUiSdkMessage[] · required | Banner records returned by SpryUI. An empty array is valid and means no banners to render from this configuration. |
bannerPolicyBannerPolicy | null · optional | Project rules for rotating or stacking banners. See the nested fields below. |
deliverySpryUiDeliveryStatus · optional | Delivery status and an optional reason, used by diagnostics. Older responses may omit it. |
What happens at startup
- The SDK consumes
initialConfigonce, 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
messagesarray is used as supplied; it does not trigger a fallback configuration fetch. sdk.refresh()makes a new request. Setenvto 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.
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.