Skip to content

JavaScript API reference

Every method of the browser global, the pre-load queue, the query parameters and storage keys, and the server SDK.

The lift global#

The snippet exposes one object, window.lift. It is installed before anything else the snippet does, so it exists as soon as the script has run.

MemberDescription
lift.track(name, props?)Record a custom event. Converts every custom goal whose event name equals name, for the experiments the visitor is in. props.value (a finite number) is sent as the event value.
lift.revenue(amount)Record revenue against every revenue goal. amount is a positive, finite number in the site's currency; anything else is ignored.
lift.consent(granted)Tell the snippet the visitor's decision. With consent mode "opt_in" nothing happens until consent(true). consent(false) stops tracking, reverts applied variants and deletes the snippet's storage.
lift.getVariant(experimentKey)The variant this visitor is in for an experiment key on this page — { experimentId, experimentKey, variantId, isControl } — or null.
lift.onReady(callback)Run callback(api) once the snippet has finished deciding for this page view, whether or not a variant was applied. Runs immediately when already ready. An exception thrown by the callback is swallowed.
lift.debug(enable?)Return a snapshot of the snippet's state, or null before the config has loaded. debug(true) also turns console logging on and opens the QA panel; debug(false) turns logging off.
lift.versionThe snippet version, a string.

Three guarantees hold for every member:

  • Nothing throws. Wrong arguments are ignored. Your page cannot be broken by a call to the global, whatever state the snippet is in.
  • Calls made early are not lost. track, revenue and consent are buffered until the snippet is ready and then replayed in order (the most recent 100 calls).
  • It is safe when the snippet is off. In preview and editor mode, for visitors who opted out, and with lift_off=1, calls to track and revenue are accepted and record nothing.

track and revenue#

lift.track(name, props?)js
// Converts every custom goal whose event name is "signup_completed".
lift.track('signup_completed');

// Only the name and a numeric "value" are used. Any other property is ignored:
// it is not sent to Avenue Lift and not forwarded to your analytics integrations.
lift.track('plan_selected', { value: 49 });
lift.revenue(amount)js
// On the order confirmation page, in the site's currency.
lift.revenue(129.0);

What these convert, and how conversions are attributed, is described in Goals and conversion tracking. Event names are limited to 128 characters.

getVariant and onReady#

Use these to make your own code depend on a visitor's variant — loading a different component, tagging a support chat, annotating a session recording.

js
lift.onReady(function (api) {
  var variant = api.getVariant('hero-headline');
  // null when this visitor is not in the experiment on this page
  if (variant && !variant.isControl) {
    // { experimentId, experimentKey, variantId, isControl }
    loadLongFormTestimonials();
  }
});
  • The argument is the experiment's key, the short identifier shown on the experiment page, not its id or name.
  • getVariant answers for the current page. It returns null until the snippet has decided, and when the visitor is not in the experiment here: not targeted, outside the traffic share, or the experiment is not running.
  • onReady is the place to call it. The callback runs once per page load, after variants have been applied or the snippet has decided there is nothing to apply. In a single-page app, call getVariant again after a navigation.

Keep experiment logic in the variant when you can

A variant made of mutations can be previewed, reviewed, reverted and promoted without a deployment. Branching in your own code on getVariant is the right tool when the change is behaviour rather than content.

debug#

lift.debug() returns a plain object describing the snippet's state on the page, or null before the configuration has loaded:

json
{
  "version": "0.1.0",
  "mode": "live",
  "siteKey": "lift_pk_YOUR_SITE_KEY",
  "configVersion": 42,
  "url": "https://www.example.com/pricing",
  "visitorId": "k3J9…",
  "sessionId": "s8Qz…",
  "privacy": { "consentMode": "none", "blocked": false, "decision": null },
  "experiments": 2,
  "goals": 3,
  "active": [
    {
      "experimentId": "0198c1de-…",
      "experimentKey": "pricing-headline",
      "variantId": "0198c1df-…",
      "isControl": false,
      "forced": false,
      "status": { "total": 2, "applied": 2, "pending": 0, "failed": [] }
    }
  ],
  "events": [{ "t": "pv", "ts": 1767225600000 }]
}

The possible values of mode are live, preview, editor, blocked, waiting_consent and off. See QA debug mode for what they mean.

The pre-load queue#

If your code may run before the snippet — because the snippet is loaded by a tag manager, or your code sits above it — define the global as an array and push commands to it. When the snippet starts it takes the array over, runs the commands in order, and replaces the array with the real object. push keeps working afterwards, so the same code is correct before and after load.

html
<script>
  window.lift = window.lift || [];
  lift.push(['track', 'signup_completed']);
  lift.push(['revenue', 129.0]);
  lift.push(['onReady', function (api) { console.log(api.version); }]);
</script>

A command is an array of a method name followed by its arguments. The methods that can be queued are track, revenue, consent and onReady. Malformed commands are ignored.

Query parameters#

The snippet reads four parameters from the page URL, all starting with lift_. They are meant for your team, not for visitors.

ParameterLastsEffect
lift_preview=<experimentId>:<variantId>Sticky for the tabShow a variant without recording anything. Several pairs can be separated by commas; lift_preview=off ends the preview.
lift_debug=1Sticky for the tabTurn console logging on and open the QA panel. lift_debug=0 turns it off.
lift_off=1This page view onlyDo nothing at all: the original page, no storage, no events.
lift_editor=<token>Sticky for the tabOpen the visual editor. Added by the dashboard; the token is removed from the address bar as soon as it is read.

Cookies and storage#

KeyWherePurpose
_lift_vidFirst-party cookie, mirrored in localStorageA random visitor id, so a returning visitor keeps their variant.
_lift_asgFirst-party cookie, mirrored in localStorageWhich variant the visitor was assigned in each experiment (experiment id → variant id).
_lift_sidsessionStorageA random id for the tab session.
_lift_consentlocalStorageThe consent decision given through consent(): "1" granted, "0" denied. The only key written without consent, because it is the consent record.
_lift_newsessionStorageMarks a visitor id created in this session (new versus returning).
_lift_expsessionStorageExperiments whose exposure was already reported in this session.
_lift_previewsessionStorageThe active preview, so it survives navigation in the tab. Set only by a preview link.
_lift_debugsessionStorageDebug mode for the tab. Set only by the debug link or debug(true).
_lift_editorsessionStorageThe visual-editor session token. Set only when you open the editor from the dashboard.

When and whether these are written is covered in Consent and privacy.

Analytics integrations#

The snippet can tell the analytics tools already on your page which variant a visitor saw, so you can segment their reports by variant. Each integration is a switch in the site's settings. The snippet calls the tool's own global if it exists; it loads no vendor code and stores no vendor keys.

IntegrationCallProperties
Google Analytics 4gtag('event', 'experiment_impression', …)experiment_id, variant_id, exp_variant_string
PostHogposthog.capture('lift_exposure', …)experimentId, experimentKey, variantId, isControl
Segmentanalytics.track('Experiment Viewed', …)experiment_id, experiment_name, variation_id
Data layerdataLayer.push({ event, lift })event: the name you configure; lift: experimentId, experimentKey, variantId, isControl

The call is made once per experiment and session, at the moment the exposure is recorded. Properties you pass to lift.track() are not forwarded to our servers.

Server SDK#

Not on a package registry yet

@lift/sdk is not published. This reference describes the package as it will ship; until then use the HTTP endpoints POST /api/v1/assign and POST /api/v1/e.

@lift/sdk assigns variants on the server and reports events without a browser. It has no dependencies beyond the shared core and runs wherever fetch exists. A Next.js walkthrough is in Installing the snippet; this is the general shape:

Server-side assignmentts
import {
  buildVisitorCookies,
  createLiftClient,
  generateVisitorId,
  readVisitorCookies,
} from '@lift/sdk';

const lift = createLiftClient({
  siteKey: 'lift_pk_YOUR_SITE_KEY',
  apiBase: 'https://lift.example.com',
});

export async function handle(request: Request): Promise<Response> {
  const cookies = readVisitorCookies(request.headers.get('cookie'));
  const visitorId = cookies.visitorId ?? generateVisitorId();

  // Never rejects: if the service cannot be reached there are no assignments
  // and `result.error` is set — render the original page.
  const result = await lift.getAssignments({
    visitorId,
    url: request.url,
    userAgent: request.headers.get('user-agent'),
    sticky: cookies.sticky,
    isNewVisitor: cookies.visitorId === null,
  });

  const hero = result.assignments.find((a) => a.experimentKey === 'hero-headline');
  const response = render({ headline: hero && !hero.isControl ? 'B' : 'A' });

  // Only when your consent rules allow storage for this visitor.
  for (const cookie of buildVisitorCookies({ visitorId, sticky: result.sticky })) {
    response.headers.append('set-cookie', cookie);
  }
  return response;
}

createLiftClient(options)

OptionDefaultMeaning
siteKey—The site's public key. Required.
apiBase—Origin of the app. Required.
mode'remote''remote': one request per getAssignments call; the service assigns and records exposures. 'local': the SDK caches the site configuration and assigns in-process with the same functions, then reports exposures itself.
timeoutMs2000Abort a request after this long.
configTtlMs30000Local mode: how long a fetched configuration is reused.
fetchglobal fetchA fetch implementation to use instead.
onError—Called with every failure the client swallowed.
waitUntil—Local mode: hand the exposure report to the platform instead of awaiting it, for example ctx.waitUntil on an edge runtime.

Client methods

getAssignments(visitor, options?)
The variants the visitor gets for visitor.url. Resolves { v, assignments, sticky, error? } and never rejects. Each assignment has experimentId, experimentKey, variantId, variantName, isControl, sticky and the variant's mutations. Options: experimentKeys to restrict the result, track: false to report exposures yourself.
getVariant(visitor, experimentKey, options?)
Shorthand for one experiment: its assignment, or null.
track(visitor, events)
Report one or more events: pageview, exposure, conversion or custom. Resolves true when every request was accepted; never rejects.
getConfig(options?)
The site's runtime configuration, or null when it cannot be loaded.

A visitor is { visitorId, url } plus optional facts used for targeting: userAgent, device, referrer, country, isNewVisitor, sessionId and the sticky map of earlier assignments.

Reporting a conversionts
// Report a conversion from your server (for example after a payment succeeds).
await lift.track(
  { visitorId, url: 'https://www.example.com/checkout/complete' },
  {
    type: 'conversion',
    experimentId: assignment.experimentId,
    variantId: assignment.variantId,
    goalId: 'GOAL_ID_FROM_THE_DASHBOARD',
    value: 129.0, // revenue goals only
  },
);

Helpers

readVisitorCookies(cookieHeader)
Read the snippet's cookies from a request: { visitorId, sticky }. Never throws.
buildVisitorCookies(input, options?)
Set-Cookie header values that persist the visitor id and sticky map in the format the snippet reads. Options: domain, secure, maxAgeSeconds.
generateVisitorId()
A new random visitor id.
assignFromConfig(…)
Assign in-process from a configuration you obtained yourself. Pure; what local mode runs.

React bindings: @lift/sdk/react

<LiftProvider assignments onExposure?>
Makes the assignments computed on the server available to the tree. onExposure is called in the browser the first time an experiment is actually rendered — use it when you requested assignments with track: false.
<Variant experiment id | control>
Renders its children only for visitors in that variant. The control branch also renders for visitors who are not in the experiment, so it doubles as the default.
useVariant(experimentKey)
The assignment for an experiment, or null. Counts as rendering it.
useLift()
All assignments and a getVariant lookup that does not count as an exposure.

Failures are reported as a LiftSdkError with a code: invalid_options (the only one that is thrown, by createLiftClient), invalid_input, network, timeout, http or malformed_response.