Guides
JavaScript SDK
Install the browser SDK, the full API, single-page apps and how to avoid flicker.
The SDK is a single dependency-free script, sdk.js, served by freeabtest.com. The shipped file is about 100 KB raw and under 30 KB gzipped. It exposes one global object, window.ABTest.
Install#
When you are signed in, Overview, Domains, and each experiment Setup tab show a pre-filled snippet with your public SDK key and https://www.freeabtest.com. Copy it as-is. Use the Production / Development toggle to swap keys; you do not paste a key yourself.
<script src="https://www.freeabtest.com/sdk.js" data-key="cro_pk_prod_..." async></script>Put the same tag on the control page and every variation page. The SDK reads the key from data-key, matches a running test by the current URL, and handles bucketing, redirects and click goals automatically.
Script tag only
The browser SDK is the script tag shown above; there is no npm package for it. To run tests from your backend, see Server-side testing.
What the snippet does on its own#
With data-key on the script tag, the SDK starts as soon as it loads. You do not call anything for a standard test:
- It matches the current URL to a running test and puts the visitor in a variation. The visitor keeps that variation on every visit.
- For a split URL test, it sends visitors in a variation with its own URL to that page.
- For a visual editor variation, it applies the changes before the page shows.
- It records the visit and counts click, form submit and page visit goals.
- It hides the page for at most 0.8 seconds while it decides, so visitors do not see the original flash first.
track(eventName, options)#
On paid plans, counts a custom event goal, such as a signup or purchase that happens in your own code. On the free plan it is refused with 403. It counts for every running test that has an event goal with this name, once per visitor. On paid plans, pass revenue to record the order value (see Revenue goals).
ABTest.track('signup');
ABTest.track('purchase', { revenue: 49.99 });trackConversion(experimentId, eventName)#
Paid plans. Records a conversion for one test, for the variation the visitor sees on this page. eventName is an optional label such as signup. It sends nothing if the visitor is not in that test on the current page. For most sites, an event goal with ABTest.track is simpler, because it also works on a thank-you page.
ABTest.trackConversion('exp_123', 'signup');bootstrap()#
Runs the same check the snippet runs on load and returns a promise with the reply. Use it when your own code needs to know the variation, or after a route change in a single-page app. Each call makes one request.
{
"matched": true,
"action": "stay", // "redirect" when the SDK is sending the visitor to a variation URL
"experiment_id": "exp_123",
"variation_id": "var_456",
"variation_name": "Variant B",
"is_control": false
}When no running test matches the page, or the visitor is not in it, matched is false. Network errors also resolve to { matched: false }, so your page always falls back to the original.
ABTest.bootstrap().then(function (r) {
if (r.matched && r.variation_name === 'Variant B') {
document.body.classList.add('variant-b');
}
});init(options)#
Only needed when you load sdk.js without data-key, for example in a test harness. It stores the settings and makes no request; call bootstrap() afterwards.
| Option | Description |
|---|---|
apiUrl | The base URL, with no trailing slash. Defaults to the host that served sdk.js. |
apiKey | An SDK key (cro_pk_<env>_...). The key decides which project and environment the data goes to. |
userId | Your own stable visitor ID, such as a logged-in user ID. If omitted, the SDK generates one and keeps it in localStorage under ab_user_id. |
Visitor IDs#
Generated IDs look like user_1728912345678_k3j9x0abc. They live in localStorage, so they survive reloads but not a different browser, device or cleared storage. When localStorage is blocked, a first-party cookie named ab_user_id holds the ID instead. Pass userId to init if you want the same person to see the same variation across devices.
getUserId()#
Returns the visitor ID the SDK is using. Handy for debugging, for joining with your own analytics, and for erasing one visitor when they ask (Settings, Privacy and data). Before consent it returns an empty string.
Consent and opt-out#
If your site asks visitors for consent before it stores anything in their browser, add data-consent="required" to the script tag. The SDK then stores, sends and hides nothing until you call consent(true) from your consent banner. Visitors who have not consented see your original page.
<script src="https://www.freeabtest.com/sdk.js" data-key="cro_pk_prod_..." data-consent="required" async></script>// In your consent banner's callback
window.ABTest.consent(true); // start testing this visitor
window.ABTest.consent(false); // send nothing more on this pageWithout data-consent, the SDK starts right away. Either way, optOut() opts the browser out for good: the visitor ID is forgotten and the visitor is never tested or tracked again until optIn(). isOptedOut() tells you which state the browser is in.
| Method | What it does |
|---|---|
| consent(granted) | true starts the SDK on this page when the script tag has data-consent="required"; false stops all sending. |
| optOut() | Opts this browser out and removes the stored visitor ID. |
| optIn() | Undoes optOut(). Testing starts again on the next page load. |
| isOptedOut() | true when this browser has opted out. |
Google Analytics 4#
On every plan, when a visitor sees a version of a running test, the snippet tells Google Analytics 4 once per page. With gtag.js on the page it sends a GA4 experience_impression event. With Google Tag Manager it pushes the same event to dataLayer, so you can forward it with a GA4 event tag. If neither is on the page, nothing is sent.
| Parameter | Example |
|---|---|
exp_variant_string | FABT-exp_123-var_456 |
experiment_id | exp_123 |
variation_id | var_456 |
variation_name | Annual first |
is_control | false |
To compare versions in GA4, register variation_name (or exp_variant_string) as an event-scoped custom dimension. Test names are not sent, so internal names stay private. To turn this off, add data-analytics="off" to the script tag.
A GA4 audience for each version#
To follow people who saw one version through the rest of GA4 (or use them in Google Ads), build an audience from the event:
- 1
Register the dimension
In GA4, open Admin, Custom definitions and create an event-scoped custom dimension for
exp_variant_string. - 2
Create the audience
Open Admin, Audiences, New audience, Create a custom audience. Add the condition: event
experience_impressionwhereexp_variant_stringexactly matches the value for the version, such asFABT-exp_123-var_456. The test id is in the address of the test in the dashboard, and the version ids are in the results CSV (see Downloading results). - 3
Repeat per version
Make one audience per version, including the control, so you can compare them.
Audiences only fill from the day you create them, so set them up before or right when the test starts.
Single-page apps#
The snippet checks the page once, when it loads. If your app changes the URL without a full page load, call ABTest.bootstrap() after the route change so a test on the new URL runs. Visitors keep their variation. Any framework works the same way; here is an example for a React router.
useEffect(() => {
window.ABTest?.bootstrap();
}, [pathname]);Avoiding flicker#
The SDK hides the page until it knows the variation, for at most 0.8 seconds. To keep that short:
- Put the script tag in the
<head>, not at the end of the body. - Prefer changes that do not shift layout, such as text and color.
Rate limits and errors#
Requests are limited per SDK key and client IP. SDK calls catch their own errors and log them to the console with an [ABTest] prefix, so a failure never breaks your page.