Skip to Content

Getting started

Javascript

Install the JavaScript SDK and run your first A/B test on the server and in the browser.

4 min read

For a complete overview of features in the Javascript SDK check out the docs regarding those. For getting started read on.

Install

npm i @obelism/improve-sdk

Setup

Server setup

Configure the client

import { ImproveServerSDK } from '@obelism/improve-sdk/server'

const improveSdk = new ImproveServerSDK({
	organizationId: process.env.IMPROVE_ORGANIZATION_ID,
	environment: process.env.IMPROVE_ENVIRONMENT,
	token: process.env.IMPROVE_API_TOKEN,
})

On Vercel or in GitHub Actions, token: vercelOidc() (or githubOidc()) from @obelism/improve-sdk/oidc replaces the stored token: see Without a stored token.

Get the visitor ID

In the request handler it's possible to generate a visitor ID with the function;

improveSdk.generateVisitorId()

It's recommended to save this value in a cookie so it's possible to keep track of specific visitors and serve them the same version of the AB test for each request. This could look like this;

export const GET = async (request: Request) => {
	const visitorCookieName = improveSdk.getVisitorCookieName()
	const visitorId =
		request.cookies.get(visitorCookieName)?.value ||
		improveSdk.generateVisitorId()

	// ...

	return new Response('...', {
		headers: {
			'Set-Cookie': `${visitorCookieName}=${visitorId}; Secure; Max-Age=2592000`,
		},
	})
}

We're not marking the cookie HttpOnly, this way we can read the value from the client and use it for analytic tracking.

Get the visitor value

Now that we know who the visitor is on the server we can get them a value for the AB test that we're running;

const userAgent = request.headers.get('user-agent')
improveSdk.getTestValue('example-test-slug', visitorId, userAgent)

Serverless

Running serverless you need to also set the test value in a response cookie, since the next request the same user makes to your serverless function might hit a different instance which has no recollection of the given value.

export const GET = async (request: Request) => {
    // ...

    const userAgent = request.headers.get('user-agent')
    const value = request.cookies.get('example-test-slug')?.value ||
        improveSdk.getTestValue('example-test-slug', visitorId, userAgent)

    // Alter the response based on the value
    const responseMessage = value === 'b' ? "alteration" : "original"

    return new Response(responseMessage, {
        headers: {
            'Set-Cookie': `example-test-slug=${value}; Secure; Max-Age=2592000`,
        },
    })
}

Serverfull

When having a long running server, you can utilize the cache within the SDK, this way setting the response cookie is not required. However, if you want to send analytic events from the client you probably still want to.

export const GET = async (request: Request) => {
    // ...

    const userAgent = request.headers.get('user-agent')
    const value = improveSdk.getTestValue('example-test-slug', visitorId, userAgent)

    // Alter the response based on the value
    const responseMessage = value === 'b' ? "alteration" : "original"

    return new Response(responseMessage)
}

Client setup

Configure the client

Sync loading

import { ImproveClientSDK } from '@obelism/improve-sdk/client'

const client = new ImproveClientSDK({
	organizationId: process.env.IMPROVE_ORGANIZATION_ID,
	environment: process.env.IMPROVE_ENVIRONMENT,
})

Async loading

const { ImproveClientSDK } = await import('@obelism/improve-sdk/client')

const client = new ImproveClientSDK({
	organizationId: process.env.IMPROVE_ORGANIZATION_ID,
	environment: process.env.IMPROVE_ENVIRONMENT,
})

Get the visitor ID

Now that the client is setup it's time to get the config and setup the visitor. This will grab the values from the cookies and use them internally in the client.

await client.fetchConfig()
client.setupVisitor(window.navigator.userAgent)

(optional) Consume the test value

Getting the value for a test in the client is usually only needed for client side test where you can skip the Server setup. However it can happen that for a server test you want a tiny adjustment in some client side logic.

const value = client.getTestValue('example-test-slug')

Post an analytic event

Last up is pushing analytic events, these are required for the monitoring. Events are test-independent: you post an event name + scope and the server attributes it to whichever tests/flags the visitor was exposed to.

client.postAnalytic('page_view', 'homepage')

scope (the second argument) is required — a short, stable identifier for where/what the event refers to, not display text.

For an event to be attributed to a test, the visitor must have been exposed to it first: reading the variant with getTestValue (see above) emits the exposure beacon that the server joins events against. Audience-excluded and holdout visitors are never exposed, so their events aren't attributed to the test.

Note

Recommended default: fire page_view once per page load with the current path as its scope (client.postAnalytic('page_view', pathname)). See Track page views like Google Analytics; it's the default start event for tests and powers the Events dashboard's Popular pages report.

On this page

Marks in the margin

  • Note
  • Watch out
  • Updated

Scribes marked doubtful lines in the margin. That practice is called obelism.