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
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.
optionsGamebeastServerOptionsThe 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:
projectIdnumberFor Server Keys with access to several projects: the project to act on.
apiUrlstringOverrides the Gamebeast API base URL. Leave unset for normal use.
requestTimeoutMsnumberPer-request timeout. Defaults to 10000.
fetchFetchLikeA custom fetch implementation. Defaults to the global fetch.
loggerGamebeastLoggerWhere SDK log lines go: an object with debug, warn and error methods. Defaults to the
console.
debugbooleanAlso 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 finitenumber, abooleanornull; - 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.
| Export | What it is |
|---|---|
GamebeastServer, GamebeastServerOptions | The SDK and its options |
GamebeastError | The rejection reason for experiments.assign and cohorts.getMembership |
ServerConfigs, EvaluatedConfiguration, EvaluateOptions, EvaluationSource, ConfigurationInfo | Configs and their result types |
ServerMarkers, ServerMarkerOptions, MarkerQueueSettings | Markers and their options |
ServerExperiments, AssignUnit, AssignOptions, AssignmentEntry, SdkExperimentDescriptor, SdkExperimentGroup, ExperimentAssignmentMetadata, UnitType | Experiments and their types |
ServerCohorts | Cohorts |
ConfigPath, JsonValue, JsonObject, Properties, PropertyValue, MarkerProperties, AssignmentSource | Shared value types |
Unsubscribe, GamebeastLogger, FetchLike | Callback and option types |
SDK_VERSION | This package's version |