GamebeastDocs
Dashboard
Node.js SDK

Node.js SDK

Use this section to review setup, options and lifecycle methods for the Gamebeast Node.js SDK, for Node.js and other server runtimes.

The Node.js SDK, @gamebeast/node, runs on your backend for many users: you say which user each call is about. It runs on Node.js 20+, Bun, Deno, edge runtimes and serverless functions. Use a Server Key with it, and never ship that key to browsers.

Refer to the Installation section for installation information. For code that runs in the browser, use the JavaScript SDK instead.

Calling into Gamebeast

gamebeast.ts
import { GamebeastServer } from "@gamebeast/node";

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 });

Methods

new GamebeastServer(options)

GamebeastServerreturn type

Creates the 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.
  };

  // 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);
});

Properties

serverId

stringreturn type

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

Common options

The constructor also accepts 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.

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 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/node";

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.

The SDK also checks every API response against the API contract. If a response doesn't match what this SDK version expects, it logs a warning once per endpoint naming the field that didn't match, and keeps the last good data. Upgrading @gamebeast/node usually fixes it.

Exports

Everything is a named export from the package root.

ExportWhat it is
GamebeastServer, GamebeastServerOptionsThe SDK and its options
GamebeastErrorThe rejection reason for experiments.assign and cohorts.getMembership
ServerConfigs, EvaluatedConfiguration, EvaluateOptions, EvaluationSource, ConfigurationInfoConfigs and their result types
ServerMarkers, ServerMarkerOptions, MarkerQueueSettingsMarkers and their options
ServerExperiments, AssignUnit, AssignOptions, AssignmentEntry, SdkExperimentDescriptor, SdkExperimentGroup, ExperimentAssignmentMetadata, UnitTypeExperiments and their types
ServerCohortsCohorts
ConfigPath, JsonValue, JsonObject, Properties, PropertyValue, MarkerProperties, AssignmentSourceShared value types
Unsubscribe, GamebeastLogger, FetchLikeCallback and option types
SDK_VERSIONThis package's version

On this page