GamebeastDocs
Dashboard
JavaScript SDK

JavaScript SDK

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

Refer to the Installation section for installation information.

The JavaScript SDK is one package, @gamebeast/sdk, with two entry points:

  • @gamebeast/sdk/client runs in the browser for one user: the person using the page. Configurations are evaluated for them, and markers are attributed to them automatically.
  • @gamebeast/sdk/server runs on your backend for many users. You say which user each call is about.

Pages in this section mark which entry point each API belongs to:

ClientServer

Calling into Gamebeast

client.ts
// Browser
import { GamebeastClient } from "@gamebeast/sdk/client";

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 });
server.ts
// Node.js, Bun, Deno, edge, serverless
import { GamebeastServer } from "@gamebeast/sdk/server";

export const gamebeast = new GamebeastServer({ apiKey: process.env.GAMEBEAST_SERVER_KEY! });

const config = await gamebeast.configs.evaluate({
  distinctId: user.id,
  configuration: "game-settings",
});
const speed = config.get("PlayerSpeed", 16);
gamebeast.markers.send("purchase_completed", { sku: "gems_100" }, { distinctId: user.id });

Client methods

Client

new GamebeastClient(options)

GamebeastClientreturn type

Creates the browser 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;

  // Shared with the server SDK; 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 });

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.

Client 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.

Server methods

Server

new GamebeastServer(options)

GamebeastServerreturn type

Creates the server SDK and starts loading configurations and experiments. Create one instance per process and share it. Its timers never keep the process alive.

optionsGamebeastServerOptions

The settings for the SDK. Only apiKey is required.

Types

interface GamebeastServerOptions {
  // Your Server Key. Required.
  apiKey: string;

  // Environment name from the dashboard. Defaults to "production".
  environment?: string;

  // Identifies this process. Used for rate limiting and to attribute
  // server-level markers. Defaults to a random id per process.
  serverId?: string;

  // Poll for configuration and experiment changes in the background. Set false
  // for short-lived processes and call configs.refresh() yourself. Defaults to true.
  autoRefresh?: boolean;

  // Poll interval in seconds. Defaults to the backend's (30); minimum 5.
  pollIntervalSeconds?: number;

  // How long configs.evaluate reuses a user's result before revalidating.
  // 0 always asks the backend. Defaults to 30.
  evaluationCacheSeconds?: number;

  // Marker batching.
  markers?: {
    maxBatchSize?: number; // Markers per request. Defaults to 100.
    flushIntervalMs?: number; // Longest a marker waits. Defaults to 5000.
    maxBufferedMarkers?: number; // Cap during an outage. Defaults to 10000.
  };

  // Shared with the client SDK; see "Common options" below.
  projectId?: number;
  apiUrl?: string;
  requestTimeoutMs?: number;
  fetch?: FetchLike;
  logger?: GamebeastLogger;
  debug?: boolean;
}

Usage

const gamebeast = new GamebeastServer({
  apiKey: process.env.GAMEBEAST_SERVER_KEY!,
  serverId: process.env.HOSTNAME,
});

flush()

Promise<void>return type

Sends buffered markers now. Resolves once the requests have settled. In a serverless function, await it before the handler returns.

shutdown()

Promise<void>return type

Stops polling and flushes buffered markers. Call it before the process exits, for example on SIGTERM. Markers sent afterwards are dropped.

Usage

process.on("SIGTERM", async () => {
  await gamebeast.shutdown();
  process.exit(0);
});

Server properties

serverId

stringreturn type

The id this process reports as: the serverId option, or a generated one.

Common options

Both constructors accept these options:

projectIdnumber

For Server Keys with access to several projects: the project to act on.

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.

In the browser, 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, and markers are dropped. The browser instance does the real work once the page loads. To evaluate configurations on your server, use @gamebeast/sdk/server.

Errors and logging

The SDK never throws from reads, markers.send, or configs.evaluate: problems are logged and you get your fallback value. Only misconfiguration throws, from the constructor. The two server calls that return data you'd act on, experiments.assign and cohorts.getMembership, reject with a GamebeastError instead of returning a partial answer:

import { GamebeastError } from "@gamebeast/sdk/server";

try {
  await gamebeast.experiments.assign(userIds);
} catch (error) {
  if (error instanceof GamebeastError && error.retryable) {
    // Rate limited or a transient failure: try again later.
  }
}

GamebeastError carries status (the HTTP status, when the backend answered), errorCode (for example RATE_LIMITED) and retryable.

On this page