`init()` and InitConfig reference
Reference every supported Apex SDK InitConfig field with its type, default, and intended use.
Call init(config) once per page load or app shell. The SDK accepts inline experiments through experiments, or it fetches running experiments when both shopId and endpoint are present.
import { init } from "@drip-apex/sdk";
const assignments = init({
shopId: "demo-shop",
endpoint: "https://events.drip-apex.com",
antiFlickerMode: "scoped",
trackingStart: "idle"
});init() returns the assignments available immediately. When the SDK fetches config asynchronously, the first return value can be an empty array; read later assignments with getAssignments() or listen for the drip_initialized browser event.
Core fields
Note: Data layer triggers were extended in the release
6f8189cto support curated named-event properties, mapping transforms, and ordered fallback paths. See the SDK "triggers" runtime-settings and trigger-simulation fixtures in the repository for behavior and examples.
| Field | Type | Default | When to use |
|---|---|---|---|
experiments | Experiment[] | Not set | Provide inline, code-owned experiments instead of fetching by shopId. An empty array is valid and still initializes analytics. |
signals | RuntimeSignalDefinition[] | [] | Define custom runtime signals that targeting can capture from URLs, DOM, globals, data layer events, or SDK events. |
shopId | string | Not set | Fetch published config from the Worker and attribute events to an Apex shop. Required for hosted config fetches. |
storeOrigin | string | Not set | Set the canonical storefront origin used to resolve host-agnostic redirect source rules. Worker-hosted config normally supplies this automatically. |
storeOrigins | string[] | [] | List registered public storefront origins that may resolve host-agnostic redirect source rules. When present, this takes priority over storeOrigin. |
endpoint | string | Not set | Base Worker URL for /config, /events, handover minting, and order identity calls. A trailing /events is normalized away. |
auditEndpoint | string | Apex production audit endpoint | Override signed storefront audit snapshots when using the audit build. Most installs leave this unset. |
editorBundleUrl | string | Derived from the installed SDK script | Versioned URL for the lazy on-site editor bundle. Apex-hosted snippets provide this automatically; custom delivery setups can point it at their matching editor.js asset. |
replayRecorderUrl | string | Derived from the installed SDK script | Versioned URL for the lazy session-replay recorder artifact. Apex-hosted snippets provide this automatically; custom delivery setups can point it at their matching recorder asset. |
ingestShopId | string | shopId | Send a different shop identifier in event ingestion headers when Worker-delivered config needs a separate ingest identity. |
ingestSignature | string | Not set | Sign event ingestion, handover minting, and order identity requests when the Worker provides a signature. Do not hardcode secrets in page code. |
proxyEventDelivery | { enabled: boolean; path?: string } | Disabled | Use same-origin Shopify App Proxy event delivery with automatic direct fallback. Apex sets this per shop; merchants do not configure it. |
assignmentCookieSync | boolean | true | When Shopify's analytics bus is unavailable (bus-less headless storefronts), write the assignment sync into a first-party cookie on the registrable domain so the checkout pixel can attribute purchases. Set false to disable the fallback; controlled per shop via runtime settings. |
assetFallback | boolean | false | Marks every event from this boot with asset_fallback when the loader recovered the SDK through the store's own /apps/apex path. Set by the Apex loader; merchants do not configure it. |
attributes | Record<string, unknown> | {} | Add targeting attributes for this page or visitor, merged with runtime signal-derived attributes. |
userId | string | Generated visitor ID | Override the visitor/bucketing identity, for example with a stable logged-in user identifier. |
url | string | location.href | Evaluate targeting against a supplied URL instead of the current browser location. Useful for tests and controlled rendering. |
autoTrack | boolean | true | Set to false when you do not want automatic assignment exposure events. Manual event calls still work when tracking is available. |
storefrontVitalsSampleRate | number from 0 to 1 | 0.1 | Set the per-page sampling rate for storefront Core Web Vitals and delivery-timing measurements. |
configCache | boolean | true | Set to false to disable localStorage config cache for fetched shop config. Cache is also disabled when storage is blocked. |
configCacheTtlMs | number | 300000 | Change the freshness window for cached fetched config. Values must be positive numbers. |
cartAttributeWrite | "sdk" or "external" | "sdk" | Select the cart-attribute write owner. With "external", the SDK does not write cart attributes itself; the storefront owns the write. |
cartAttributeScope | "consented" or "all" | "consented" | This is an admin-managed setting. "consented" (default) writes cart attributes only after tracking consent is granted. "all" behaves the same once consent is granted; while tracking is unavailable it additionally maintains a stamp that contains the experiment-arm label only, with no identifiers, in both SDK-owned and external integration modes. |
lateConfigPolicy | "skip" or "apply" | "skip" | Choose whether fetched config that arrives after the anti-flicker reveal deadline should still apply. QA and screenshot forcing uses "apply". |
onExperimentViewed | (assignment: Assignment) => void | Not set | Run a callback for each viewed assignment after the SDK has assigned and started exposure tracking. |
holdout_v1_enabled | boolean | false | Enable the global program holdout gate. When enabled with a valid percentage, holdout visitors receive no experiment assignments. |
holdout_pct | number | Not set | Set the global holdout percentage above 0 and up to 10. The gate remains inactive unless holdout_v1_enabled is true. |
holdout_config_updated_at | string or null | Not set | Carry the server-issued holdout configuration timestamp so cached assignments and later events remain bound to the cohort-producing configuration epoch. |
geo | { country?: string } | Not set | Request-scoped edge geography supplied by the Apex Worker (from Cloudflare geo) so geo.country targeting can match. Set by the runtime on Worker-delivered config; you do not normally set this by hand. |
Runtime modes
| Field | Type | Default | When to use |
|---|---|---|---|
executionMode | "auto", "edge", or "client" | "auto" | Keep "auto" for edge-first delivery with client fallback. Use "edge" only when an edge runtime has already initialized the page. |
platformHint | "auto", "shopify", "spa", or "shopware" | Auto-detected | Hint platform-specific router and surface behavior when auto-detection cannot identify the storefront. |
routerMode | "auto", "history", "navigation", or "none" | "auto" | Top-level SPA route observation mode. spa.routerMode takes priority when present. |
activationMode | "auto", "observer", or "manual" | "observer" | Top-level mutation activation mode. spa.activationMode takes priority when present. |
antiFlickerMode | "scoped", "full", "custom", or "off" | "scoped" | Control how Apex hides content before variants apply. Use custom with antiFlickerCustomCss. |
antiFlickerTimeoutMs | number | 1200 | Auto-reveal timeout for anti-flicker protection. Non-positive or invalid values fall back to 1200. |
antiFlickerCustomCss | string | Not set | CSS injected only when antiFlickerMode is "custom". |
trackingStart | "idle" or "immediate" | "idle" | Decide whether analytics setup waits for idle time or starts immediately after initialization. |
trackingIdleTimeoutMs | number | 2000 | Fallback timeout for trackingStart: "idle". Non-positive or invalid values fall back to 2000. |
customJsPolicy | "strict" or "hybrid" | "hybrid" | Control variation and project custom JavaScript execution. Use "strict" to block custom JS in production-sensitive installs. |
requireConsent | boolean | false | Gate tracking and persistent storage until consent is granted. Variants can still render under strict consent mode. |
hasConsent | boolean | Consent cookie or provider state | Seed the initial consent state when using requireConsent or custom consent controls. |
deferTracking | boolean | Deprecated alias | Deprecated. true maps to trackingStart: "idle" and false maps to "immediate". |
antiFlicker | boolean | Deprecated alias | Deprecated. true maps to antiFlickerMode: "full" and false maps to "off". |
antiFlickerTimeout | number | Deprecated alias | Deprecated. Maps to antiFlickerTimeoutMs. |
Settings objects
| Field | Type | Default | When to use |
|---|---|---|---|
profile | ConfigProfile | Not set | Server-provided profile metadata. The SDK currently reads profile.platform after platformHint. |
projectPrerequisites | ProjectPrerequisites | No prerequisite rules | Gate variation display and tracking with project-level showVariationsRule and startTrackingRule expressions. |
exclusionGroups | ExclusionGroupConfig[] | [] | Server-provided mutual-exclusion groups. When multiple member experiments match, Apex keeps one weighted winner per group and suppresses the others. |
consentMode | ConsentModeSettings | Disabled | Configure provider-backed consent detection for custom, OneTrust, Usercentrics, Cookiebot, CCM19, Pandectes, or CookieScript. |
debug | DebugSettings | Disabled | Enable restricted SDK console diagnostics by query parameter, user ID, always-on mode, or active server state. |
spa | SpaSettings | Auto router, observer activation | Configure SPA router observation, DOM re-evaluation, debounce timing, iframe allowance, and reinit-only mode. |
pageTrigger | PageTriggerSettings | { defaultMode: "direct" } | Switch initial activation and route behavior to URL change, DOM change, or manual page triggers. |
externalTracking | ExternalTrackingSettings | Disabled | Preserve bucketing across external checkout, booking, or lead-flow domains by rewriting configured links and forms. |
dataLayerTriggers | DataLayerTriggerSettings[] | [] | Listen to data layer events, map event fields into runtime signals, re-evaluate assignments, and optionally track pageviews or revenue. |
exposureDestinations | ExposureDestinationsSettings | Disabled | Send assignment exposure metadata to dataLayer, Hotjar, or custom queue globals. |
projectCode | ProjectCodeSettings | Disabled | Apply advanced project-level CSS, helper JS, or startup JS before or after assignments. |
environments | RuntimeEnvironmentSettings | Production | Select an environment key for fetched config and config-cache isolation. |
bucketingCleanup | BucketingCleanupSettings | Enabled with 180 day retention | Clean stale Apex goal and config-cache storage. Set enabled: false to opt out. |
dataProtection | DataProtectionSettings | localStorage, no encoding, DNT off | Choose visitor storage mode, encoded storage values, Do Not Track behavior, and cookie domain. |
semanticTracking | SemanticTrackingSettings | Disabled | Capture sampled semantic visibility or click events for configured selectors. |
aggregateMode | AggregateModeSettings | Disabled | Server-managed flags for the order attribution rail. Read-only from the served config. Cart-attribute behavior is controlled by cartAttributeScope, not by this setting. |
commerce | CommerceSettings | Not set | Server-provided, presentation-only commerce settings. commerce.price carries the versioned price-plane projection rendered on product pages. commerce.shipping carries assigned display-only free-shipping thresholds, treatment types, and progress/reached copy rendered from the live Shopify cart subtotal. |
runtimeControl | RuntimeControlSettings | Enabled runtime | Server-authoritative kill-switch state. When disabled is true, runtime diagnostics show the disabled state. |
deliveryState | "no_visual_tests", "non_critical_visual", "critical_visual", "edge_managed", or string | Not set | Worker/snippet metadata included in SDK performance telemetry. |
scriptCacheSource | "edge", "kv", "origin", "precompile", "precompiled", or string | Not set | Worker/cache source label included in SDK performance telemetry. |
installSurface | "direct_script", "shopify_app_embed", "legacy_shopify_redirect", or string | Not set | Install surface label included in SDK performance telemetry. |
snippetUrl | string | Not set | Worker-provided snippet URL used for the per-visitor debug-build handoff in restricted debug modes. |
sdkVersion | string | Not set | Worker-provided immutable SDK artifact version for release-attributed performance telemetry. |
sdkDeliveryMode | "global", "pinned", "canary", or string | Not set | Worker-provided SDK policy mode for release-attributed performance telemetry. |
sdkDeliverySource | "embedded", "external", or string | Not set | Worker-provided artifact source for distinguishing embedded and immutable external delivery. |
sdkPolicyRevision | string | Not set | Worker-provided global SDK delivery policy revision used to compile the snippet. |
runtimeProfile | "full", "empty_project", "nonvisual_assignment", or string | "full" | Server-authoritative runtime profile included in performance telemetry. Unknown profiles retain full behavior. |
delivery | SnippetDeliveryManifest | Not set | Worker-compiled delivery manifest for precompiled critical mutation delivery. Most hand-written installs omit it. |
runtimeFeatures | Runtime feature profile object | Not set | Worker-selected feature profile for live, heatmap, debug, QA, harness, or audit builds. |
perfFlags | PerfFeatureFlags | All current perf flags enabled | Runtime kill-switch flags for staged performance features. |
qa_warnings | Array of forced-experiment warning objects | Not set | Server-classified QA diagnostics for forced experiments missing from the served config (archived, runtime-disabled, or not found). QA mode only; the QA assistant renders them. |
setupCapture | SetupCaptureSettings | Not set | Worker-provided time-gated diagnostic capture settings (enabled, expiresAt, urlPatterns, layerNames, maxEventsPerSession). When active and unexpired, the SDK lazily loads the capture module and emits shape-token diagnostics; raw merchant or customer values never leave the browser. |
setupCaptureUrl | string | Not set | Worker-provided URL of the lazily loaded setup-capture module artifact. Only fetched while setupCapture is active. |
Data layer trigger mappings
Each dataLayerTriggers[].when entry is a payload condition: { path, op, value? } with op one of eq, neq, gt, lt, exists, or not_exists. A trigger may carry one to five entries; all of them must match before the trigger maps signals, queues a replay, or tracks an event. path is a payload-only dot path with the same property and numeric-index grammar as mapping paths. eq, neq, gt, and lt require value (gt/lt a number; the SDK converts the payload value to the configured type before comparison); exists and not_exists forbid it.
exists matches values other than undefined and null. not_exists matches undefined or null. A missing or unconvertible path fails eq, neq, gt, and lt. Thus, neq does not fire a trigger when the configured path is missing.
Number conditions use the same conversion as signal mappings. They accept comma decimals such as 19,90 and grouped comma decimals such as 1.234,56.
Each dataLayerTriggers[].mappings[].from value reads a path from the matching data layer entry. The mapping writes that value to the runtime signal named by to. Use an array of one to five paths for ordered fallback. Apex uses the first path with a raw value. It selects that path before value transforms or type conversion.
Named events and pageviews can define a top-level properties array. When this array exists, the event contains only source, dataLayerEvent, and resolved mapped properties. Without this array, Apex keeps the full data layer payload. Mappings cannot replace source or dataLayerEvent.
Revenue and named-event property mappings use payload paths by default. Prefix a property source with signal: to read a stored or runtime signal instead:
dataLayerTriggers: [{
eventName: "purchase",
trackEventName: "purchase_complete",
properties: [
{
from: ["customer.type", "signal:customer_type"],
to: "customerType",
valueType: "string",
transform: {
trim: true,
lowercase: true,
map: { vip: "wholesale" },
default: "retail"
}
}
],
trackRevenue: {
enabled: true,
revenueFrom: ["ecommerce.value", "value"],
properties: [
{
from: ["order.margin", "signal:estimated_margin"],
to: "margin",
valueType: "number",
transform: { scale: 0.01 }
}
]
}
}]A mapping transform runs in this order: resolve the raw path or signal, trim and lowercase strings, apply map, convert to valueType, apply numeric scale, then use a converted default if no value remains. A map accepts at most 20 exact-match entries. Map keys and values accept at most 100 characters. A scale must be finite and non-zero.
Number conversion accepts standard JavaScript numeric strings. It also accepts comma decimals such as 19,90 and grouped comma decimals such as 1.234,56. Ambiguous forms such as 1,2,3 stay unresolved.
A plain path such as customer_type reads only the matching data layer entry. Missing sources do not add a property unless the mapping defines a valid default.
Custom dimensions from dataLayer
The SDK can now capture configured custom dimensions from matching dataLayer entries and stamp their current values onto analytics events (dimensions are sent as event-level metadata). Configure these captures via your runtime signals and dataLayerTriggers mappings; the SDK resolves the mapped value at event time and includes it on any tracked event that matches the trigger. See the release ddf5a2c for the implementing change and ticket #4184.
The signal: prefix does not apply to mappings[], revenueFrom, orderIdFrom, currencyFrom, costFrom, or profitFrom. Each element in these fallback arrays must be a payload path. Mapping transforms never apply to the five revenue anchors.
Redirect experiments
Redirect experiments run before visual mutations. Apex persists the assigned arm,
queues an experiment_viewed exposure using navigation-safe delivery, preserves
the source query string and hash (destination parameters win), and then replaces
the current location. A loop guard keeps a visitor on the page when it already
matches the destination.
Mutations, variation CSS, and variation JavaScript may coexist with a redirect destination, but they are source-page artifacts only. If the assignment is preserved on the destination for attribution, the SDK does not apply those artifacts there: the destination document itself is the treatment.
For destinations on another hostname, Apex adds the temporary
_apex_assignment query parameter with the fresh visitor and assignment handover.
This name is reserved for Apex redirect tests. Do not add _apex_assignment to
merchant-authored destination URLs; when it is already present, Apex preserves
the merchant value and does not add its assignment carry. Carry is consumed only
on the configured destination entry path, not on other pages of the same host.
The destination must install the same shop's Apex snippet so the SDK can import
that identity and assignment, keep conversion attribution sticky, and avoid
rebucketing or recording a second exposure. Consent mode deliberately omits this
cross-origin carry until consent is granted: the destination mints its own visitor
identity. Activity across the two origins before consent is granted cannot be linked. If the
destination config is temporarily unavailable, Apex retains an eligible carry in
session storage only until a later config can validate it or the handover TTL expires.