LiftCanary

SDKs

Website snippet

One script tag: flags, tests, auto-tracked goals and locations, with no flicker.

The snippet is a single script (about 7 KB gzipped) that does everything a website needs: decides flags, runs redirect tests, tracks goals set up in the dashboard, handles locations and their triggers, and fills in visitor attributes such as country, device and UTM source. For single-page apps built with a bundler you can use the npm package instead, or both.

Install#

Paste this at the very top of <head>, before other scripts and stylesheets:

index.html
<!-- 1. Anti-flicker: hide the page until flags are ready (1.5 s at most) -->
<style id="liftcanary-hide">body{opacity:0!important}</style>
<script>setTimeout(function(){var s=document.getElementById("liftcanary-hide");if(s)s.remove()},1500)</script>
<!-- 2. Lets the page call liftcanary before the SDK has loaded -->
<script>window.liftcanary=window.liftcanary||{q:[],onReady:function(f){this.q.push(f)},track:function(e,o){this.q.push(["track",e,o])},activate:function(k){this.q.push(["activate",k])},consent:function(g){this.q.push(["consent",g])}};</script>
<!-- 3. The SDK -->
<script src="https://cdn.liftcanary.com/sdk/v1/liftcanary.js" data-sdk-key="pk_..."></script>

The project's Install page has the snippet with your SDK key and your CDN and collector addresses filled in. Use the development key on staging and local sites, and the production key on your live site.

What each part does#

  1. Anti-flicker style. Hides the page until decisions are made, so visitors never see the original before their variation. The SDK removes it as soon as it's ready; the timer removes it after 1.5 s at the latest, even if the SDK is blocked.
  2. Inline stub. Defines window.liftcanary right away and queues onReady, track and activate calls until the SDK loads. If the script is blocked, onReady callbacks never run and visitors simply see your default page.
  3. The SDK. Loaded synchronously, like other testing snippets, so variations apply before first paint.

Script attributes#

data-sdk-keyrequired
pk_…
The environment's SDK key.
data-cdn-url
URL
Where datafiles are loaded from. Default: the address the script itself was loaded from.
data-events-url
URL
Where events are sent. Default: the LiftCanary collector.
data-geo-url
URL
Where country, region and city come from. Default: <script origin>/geo.
data-user-id
string
Use this id instead of the anonymous one, when the page knows who is logged in. Same as calling identify() before ready.
data-cookie-domain
string
Share the anonymous id with subdomains, e.g. .example.com for a landing page and an app on app.example.com. See From landing page to app.
data-consent
"required" | "banner"
Wait for cookie consent: nothing is stored on the visitor's device and no events are sent until the visitor accepts. required: your consent banner calls liftcanary.consent(true). banner: LiftCanary shows its own banner and remembers the answer. Any other value counts as required, so a setting added later never makes an older snippet store anything without consent; leave the attribute out when consent isn't needed. See Consent.
data-privacy-url
URL
With data-consent="banner": your cookie policy, linked from the banner. Wins over the link set under Project → Consent banner, where the rest of its design is.
data-spa
"off"
Don't apply page changes and redirects on single-page-app navigations; call applyChanges() yourself. See Single-page apps.
data-bucketing
"anonymous" | "user"
Whose id decides variations for logged-in users. anonymous keeps the anonymous id, so login never changes a variation. See logged-in users.
data-debug
"true"
Log decisions to the console and show the debug panel on every page. Like ?liftcanary_debug=1.

Using flags#

JavaScript
liftcanary.onReady((sk) => {
  if (sk.isEnabled("new_checkout")) document.body.classList.add("one-page-checkout");

  const label = sk.variable("new_checkout", "button_text", "Buy now");
  document.querySelector("#buy").textContent = label;
});

onReady runs once flags are loaded, or after 1.5 s if they can't be; in that case a returning visitor's browser uses the flags it saved on the last visit. Flags read before that, outside onReady, return defaults with the reason NOT_READY.

API reference#

onReady(callback)
(sk) => void
Runs when flags are ready (or after 1.5 s). Safe to call before the SDK loads.
ready()
Promise<Api>
The same, as a promise: await liftcanary.ready().
isEnabled(flagKey)
boolean
Whether the feature is on for this visitor.
variable(flagKey, name, fallback)
T
A variable's value, or the fallback when the flag or variable is missing or of another type.
decide(flagKey)
Decision
Full decision: variationKey, ruleKey, reason, variables, inExperiment.
track(eventKey, options?)
void
Records an event. { value?: number, properties?: object }. Safe before ready.
identify(id, attributes?, options?)
void
Switch to a known user id after login. Remembered on this browser until reset(). options.bucketing: "anonymous" keeps variations on the anonymous id.
reset()
void
Logout: forget the identified user and the attributes you set, and start a new anonymous id.
setAttributes(attributes)
void
Add your own targeting attributes (plan, company size…).
attributes()
object
The visitor's current attributes, built-in and your own.
userId()
string
The current user id (anonymous or identified).
activate(locationKey?)
void
Activate a manual location, or all manual locations on the page. See triggers.
consent(granted)
void
With data-consent: true stores the visitor's id and sends held events; false drops them and removes what LiftCanary stored. Safe to call before the SDK loads and on every page.
showConsent()
void
With data-consent="banner": shows LiftCanary's banner again so the visitor can change their answer, e.g. from a "Cookie settings" link in your footer (needed when the banner's cookie button is off).
consentState()
"pending" | "granted" | "denied"
Whether the snippet may store and send.
applyChanges()
void
Re-apply no-code page changes for the current URL. Automatic on single-page-app navigations unless data-spa="off".
whenActive(locationKey, callback)
() => void
Runs the callback now if the visitor is in the location, and on every later activation. Returns a function that removes it: call it when a component that registered it unmounts.
onActivate(callback)
() => void
Runs the callback with the key of every location that activates. Returns a function that removes it.
client
Client
The underlying client (SDK reference), e.g. client.datafile.
version
string
SDK version.

Users and identity#

Anonymous visitors#

On the first visit the snippet creates a random id (a UUID) and stores it in a first-party cookie, liftcanary_anon, and in localStorage under liftcanary:anonymous_id. Later visits on the same browser reuse it, so the visitor keeps their variation; your server can read the cookie too. Nothing is stored on our side to remember the assignment: the variation is computed from the id every time. If localStorage is blocked (some private modes), the id lives only as long as the page.

Logged-in users#

When the visitor logs in, tell the snippet who they are. It remembers the user on this browser (under liftcanary:identity) until they log out:

JavaScript
// After login
liftcanary.identify("user_8812", { plan: "pro" });

// After logout
liftcanary.reset();

If your pages are rendered with the user known, data-user-id="user_8812" on the script tag does the same without code. The order is: data-user-id, then the remembered identify(), then the anonymous id. Attributes passed to identify or setAttributes are not stored (they can be personal); set them again on each page.

Identifying also links the anonymous id to the user (once per browser), so results count the visit before sign-in and everything after it as one person. See From landing page to app.

Which id decides the variation#

Choose per site, depending on where your tests start:

BucketingLogged-in users are assigned byBest for
usertheir user id: the same variation on every device, in your app and on your serverTests that only logged-in users see: account pages, the app itself
anonymousthe anonymous id of this browser: login never changes the variationTests that start before login: landing pages, pricing, signup and checkout flows
JavaScript
liftcanary.identify("user_8812", {}, { bucketing: "anonymous" });
// or for the whole site: <script … data-bucketing="anonymous">

With user bucketing (the default), someone who saw B before logging in may see A afterwards. Results stay correct, because users who saw two variations are left out, but those users aren't counted. Events are always recorded under the user id once known, whichever bucketing you choose, and the anonymous exposure before login is joined to them through the link.

Attributes#

The snippet collects country, region, city, device, OS, browser, platform, language, new or returning visitor, UTM parameters, referrer domain, path and URL by itself; add your own with setAttributes(). See Built-in attributes.

Single-page apps#

The snippet notices history.pushState, replaceState and popstate and treats a change of path or query (not just the #hash) as a new page view, handled right after your router's own code and before the screen is drawn, so the new view never shows without its tests. A burst of changes (a search box writing ?q= on every keystroke) is handled once more when the URL has settled for 150 ms, not on every keystroke: no-code tests and personalizations are applied or removed for the new page, split URL tests redirect, the next decision uses the new page for path, URL and location targeting, page-visit and scroll goals count it, and location triggers start over. Then it fires a liftcanary:navigate event on window (event.detail.url). Re-read flags in your code when your router changes the page.

data-spa="off" turns the automatic page changes and redirects off; call liftcanary.applyChanges() after each navigation instead. Goals and targeting still follow the URL.

Debugging#

Add ?liftcanary_debug=1 to any page. The console shows the visitor's id and attributes, every decision with its variation and reason, redirect tests, goals as they fire and location activations.

A debug panel also opens in the corner of the page. It shows whether the datafile loaded (and which revision), the visitor, consent and any preview, then every no-code and redirect test: whether it runs on this page (or is waiting for its location's trigger), the variation it gives this visitor and why (in the test, not in the audience, switched off), and each visual change with the number of elements its selector finds, so a change that stopped matching after a site update stands out. Copy copies it as text for a support request. The panel only reads: it works out each test's variation without counting a view.

Debugging stays on in the tab as you go from page to page, until Turn off or ?liftcanary_debug=0. With data-debug="true" on the script tag it's always on.

A page opened with ?liftcanary_preview=hero_test:b shows variation b of that test in this tab, whatever its state or audience, sends nothing, and shows a small banner to switch variations or exit. The dashboard makes these links; see Preview before you start.

Visual editor#

The visual editor runs on your own page, loaded by the snippet: a page opened with #liftcanary_editor=… loads editor.js from the snippet's origin, shows the original page with no tests applied, and keeps the editor on while you browse in that tab (until Exit). Nothing extra to install. Through your own domain (below) the editor works too, as long as every path is forwarded.

Serve it from your own domain#

Ad and tracker blockers block well-known testing domains. Served from your own domain, the snippet, flags and events look like your site's own files, so far fewer visitors fall out of your tests. Forward a neutral path, such as /_sk, to LiftCanary and point the snippet at it:

import { NextResponse, type NextRequest } from "next/server";

const API = "https://cdn.liftcanary.com";
const EVENTS = "https://events.liftcanary.com";

// Forwards /_sk/* to LiftCanary, with the visitor's location for country targeting.
export function middleware(req: NextRequest) {
  const { pathname, search } = req.nextUrl;
  const isEvents = pathname.startsWith("/_sk/e/");
  const path = pathname.slice(isEvents ? "/_sk/e".length : "/_sk".length);
  const headers = new Headers(req.headers);
  headers.set("x-country-code", req.headers.get("x-vercel-ip-country") ?? "");
  headers.set("x-region", req.headers.get("x-vercel-ip-country-region") ?? "");
  headers.set("x-city", req.headers.get("x-vercel-ip-city") ?? "");
  return NextResponse.rewrite(new URL((isEvents ? EVENTS : API) + path + search), { request: { headers } });
}

export const config = { matcher: "/_sk/:path*" };

The SDK keeps the path prefix of its own address, so it loads flags from /_sk/datafiles/… and location from /_sk/geo, and sends events to /_sk/e/v1/batch. The dashboard's Install page generates this for Next.js, Cloudflare Workers and Nginx with your own addresses. Avoid path names blockers look for, like track, analytics, collect or ab-test.

Performance#

The snippet is built to stay out of the way of your page, even on long single-page-app sessions and when events can't be sent:

  • About 17 KB gzipped, compiled in about a millisecond. Tests and settings come in a separate, small datafile (a few KB) that browsers revalidate with an ETag.
  • Visual changes watch the page for 15 seconds after each page view to cover content rendered later; on a page that keeps changing (a carousel, a clock) they check at most every 100 ms, and put a change back at most 10 times per element. When two tests change the same element, the last one applied wins; they never overwrite each other back and forth.
  • Elements watched for visibility triggers are released once they've been seen or leave the page.
  • Events are sent in batches every 5 seconds. When the collector can't be reached (an ad blocker, an outage) the snippet backs off from 1 second up to a minute, with jitter, and honors Retry-After; events are kept, up to 1,000 in memory and the newest 200 in storage, written at most once a second.
  • In tests on a demo shop, 1,500 page views in one single-page-app session kept memory flat (about 2–3 MB of JavaScript heap), and pages that change the DOM heavily ran about 5–10% slower with the snippet during the first 15 seconds of a page view.

Privacy#

  • The full page address (with query string) is used for location matching on the device only and never sent; the url attribute has no query or hash.
  • Country, region and city come from the CDN's headers; the SDK never sees the visitor's IP address.
  • Events are kept in localStorage until sent, so a page reload doesn't lose them. The last datafile is kept there too, and used when the flags can't be loaded within 1.5 s; it contains configuration only, no personal data.