GamebeastDocs
Dashboard
JavaScript SDK

JavaScript SDK

Use this section to review setup, options and lifecycle methods for the Gamebeast JavaScript SDK, which runs in the browser.

The JavaScript SDK, @gamebeast/js, runs in the browser for one user: the person using the page. Configurations are evaluated for them, and markers are attributed to them automatically. Use an SDK Key with it.

Refer to the Installation section for installation information. For your backend, use the Node.js SDK instead.

Calling into Gamebeast

gamebeast.ts
import { GamebeastClient } from "@gamebeast/js";

export const gamebeast = new GamebeastClient({
  apiKey: "abcd-efgh-1234-5678",
  configurations: ["game-settings"],
});

await gamebeast.configs.ready({ timeoutMs: 3_000 });
const speed = gamebeast.configs.get("game-settings.PlayerSpeed", 16);
gamebeast.markers.send("level_completed", { level: 3 });

Methods

new GamebeastClient(options)

GamebeastClientreturn type

Creates the SDK. Create one instance per page; a module-level singleton works well. The constructor throws when apiKey is missing or environment is invalid. Nothing else in the SDK throws.

optionsGamebeastClientOptions

The settings for the SDK. Only apiKey is required.

Types

interface GamebeastClientOptions {
  // Your SDK Key. Required.
  apiKey: string;

  // Environment name from the dashboard: "production" (default), "development",
  // or a custom one such as "staging".
  environment?: string;

  // Configurations to load immediately, by ID. They gate configs.isReady / onReady.
  // Any other configuration loads the first time it is read.
  configurations?: string[];

  // The signed-in user's id. When omitted, the SDK generates an anonymous id on
  // first visit and keeps it in localStorage.
  distinctId?: string;

  // Targeting properties for the current user, e.g. { plan: "pro" }.
  properties?: Record<string, PropertyValue>;

  // Your app's version, sent as the appVersion targeting property. Cached
  // configurations from a different version are discarded.
  appVersion?: string;

  // How often (seconds) to re-check configurations while the page is visible.
  // 0 disables background refresh. Defaults to 60.
  configRefreshIntervalSeconds?: number;

  // Minutes of inactivity before a new session starts. Sessions are shared
  // across tabs. 0 keeps one session until storage is cleared. Defaults to 30.
  sessionTimeoutMinutes?: number;

  // Where to keep the anonymous id, session and caches. Defaults to localStorage
  // (memory where it is unavailable). null keeps nothing beyond the page.
  storage?: KeyValueStorage | null;

  // Read deeplink and UTM attribution from the page URL on start. Defaults to true.
  // See /sdk/javascript/api/attribution.
  captureAttribution?: boolean;

  // Remove utm_* parameters from the address bar after reading them. Defaults to false.
  stripAttributionParams?: boolean;

  // See "Common options" below.
  projectId?: number;
  apiUrl?: string;
  requestTimeoutMs?: number;
  fetch?: FetchLike;
  logger?: GamebeastLogger;
  debug?: boolean;
}

Usage

const gamebeast = new GamebeastClient({
  apiKey: "abcd-efgh-1234-5678",
  configurations: ["game-settings"],
  appVersion: "2.1.0",
  properties: { plan: "pro" },
});

identify(distinctId)

voidreturn type

Switches to a signed-in user. Configurations are re-evaluated for them right away, and experiment assignments follow. Markers already recorded keep the id they were recorded under.

The id is not persisted. Call identify again on each page load once your login state has restored, or pass distinctId in the options.

distinctIdstring

The user's id, 1–256 characters.

Usage

gamebeast.identify(user.id);

resetIdentity()

voidreturn type

Returns to this browser's anonymous id, for example after sign-out. The anonymous id is kept while a user is identified, so the browser reports as the same anonymous user as before.

Usage

gamebeast.resetIdentity();

setProperties(properties)

voidreturn type

Replaces the current user's targeting properties and re-evaluates configurations, so targeted experiments see the new values.

propertiesRecord<string, PropertyValue>

The new properties. They replace the previous ones rather than merging into them.

Usage

gamebeast.setProperties({ plan: "pro", accountAgeDays: 12 });

captureAttribution(url)

voidreturn type

Reads deeplink and UTM attribution from url, for a landing URL the SDK didn't see when it started (for example in a single-page app). The first attribution in a session wins. See Deeplink attribution.

flush()

Promise<void>return type

Sends buffered markers now. Resolves once the requests have settled. You rarely need it in the browser: markers are also sent when the page is hidden or closed.

shutdown()

Promise<void>return type

Stops background work, flushes markers and removes the SDK's page listeners. Markers sent afterwards are dropped. Pages don't need to call it; it's for tests and single-page apps that tear the SDK down.

Properties

distinctId

stringreturn type

The current user's id: the one passed to identify or the options, or the anonymous id.

isAnonymous

booleanreturn type

True while the SDK is using its generated anonymous id.

sessionId

stringreturn type

The current session id, shared by every tab of your site.

attribution

DeeplinkAttribution | undefinedreturn type

The Gamebeast deeplink and UTM parameters the current session landed with (first touch), or undefined. See Deeplink attribution.

Common options

The constructor also accepts these options:

projectIdnumber

For keys with access to several projects: the project to act on. SDK Keys belong to one project and don't need it.

apiUrlstring

Overrides the Gamebeast API base URL. Leave unset for normal use.

requestTimeoutMsnumber

Per-request timeout. Defaults to 10000.

fetchFetchLike

A custom fetch implementation. Defaults to the global fetch.

loggerGamebeastLogger

Where SDK log lines go: an object with debug, warn and error methods. Defaults to the console.

debugboolean

Also log requests, cache hits and refreshes. Warnings and errors are always logged.

Targeting properties

Properties let experiments target users by your own data. Values must be:

  • a string, a finite number, a boolean or null;
  • a Date, sent as epoch milliseconds;
  • or an array of up to 100 values of one of those scalar types.

Property names are 1–128 characters, and at most 100 properties are sent. The SDK drops invalid entries with a warning instead of failing the call. undefined values are skipped silently, so { plan: user.plan } is safe to write.

The SDK also sends platform: "web", systemLanguage (from the browser) and appVersion (when set). Your own properties win on a name clash.

Server-side rendering

Constructing a GamebeastClient during server-side rendering (Next.js, Remix, Nuxt and so on) is safe. With no page there is no user, so the instance stays inert: reads return their fallbacks, configs.ready() resolves false, cohort checks resolve false, markers are dropped, and no deeplink attribution is captured. The browser instance does the real work once the page loads. To evaluate configurations on your server, use the Node.js SDK.

Errors and logging

The SDK never throws from reads, markers.send or cohorts.isMember: problems are logged and you get your fallback value. Only misconfiguration throws, from the constructor (a missing apiKey, an invalid environment).

Warnings and errors go to the console by default. Pass logger to route them elsewhere, and debug: true to also see requests, cache hits and refreshes.

Exports

Everything is a named export from the package root.

ExportWhat it is
GamebeastClient, GamebeastClientOptionsThe SDK and its options
ClientConfigs, ClientMarkers, ClientExperiments, ExperimentAssignment, ClientCohortsThe services and their result types
KeyValueStorageThe storage option's interface
DeeplinkAttribution, DeeplinkData, UtmParametersThe attribution getter's types
ConfigPath, JsonValue, JsonObject, Properties, PropertyValue, MarkerProperties, AssignmentSourceShared value types
Unsubscribe, GamebeastLogger, FetchLikeCallback and option types
SDK_VERSIONThis package's version

On this page