# Javascript (/docs/getting-started/javascript)

For a complete overview of features in the [Javascript SDK](/docs/sdk/javascript) check out the docs regarding those. For getting started read on.

## Install [#install]

```bash
npm i @obelism/improve-sdk
```

## Setup [#setup]

## Server setup [#server-setup]

### Configure the client [#configure-the-client]

```ts
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](/docs/api#without-a-stored-token).

### Get the visitor ID [#get-the-visitor-id]

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

```ts
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;

```ts
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 [#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;

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

#### Serverless [#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.

```bash
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 [#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.

```bash
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 [#client-setup]

### Configure the client [#configure-the-client-1]

#### Sync loading [#sync-loading]

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

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

#### Async loading [#async-loading]

```ts
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 [#get-the-visitor-id-1]

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.

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

### (optional) Consume the test value [#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.

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

### Post an analytic event [#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.

```ts
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.

<Callout type="info">
	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](/docs/guides/events#default-track-page-views-like-google-analytics);
	it's the default start event for tests and powers the Events dashboard's
	Popular pages report.
</Callout>
