SDK reference

Server flags

Create one flags manager per process and pass each request's user to it.

lib/flags.ts
import { createServerFlagsManager, FlagsRequestError } from "@databuddy/sdk/node";

export const flags = createServerFlagsManager({
  clientId: process.env.DATABUDDY_CLIENT_ID!,
});

export async function isOn(key: string, userId: string): Promise<boolean> {
  try {
    const result = await flags.getFlag(key, { userId });
    return result.enabled;
  } catch (error) {
    if (error instanceof FlagsRequestError) return false;
    throw error;
  }
}

getFlag() throws a FlagsRequestError only when the request fails and nothing is cached for that flag, so wrap first reads and pick a safe default.

Read flags

MethodReturns
getFlag(key, user?)Promise<FlagResult>: { enabled, value, variant, reason, payload, id }. Cached, batched and deduplicated.
fetchAllFlags(user?)Loads every flag for that user, for the synchronous reads below.
isEnabled(key, user?)FlagState from cache: { on, status, loading, value, variant, reason }.
getValue(key, defaultValue?, user?)The cached value, or the default while loading, when missing or when disabled.
refresh(forceClear?)Fetches again.
waitForInit()Resolves once the manager is set up; with autoFetch: true, once every flag is loaded.
isReady()Whether the manager has loaded.
destroy()Stops the manager.
app/api/export/route.ts
import { flags } from "@/lib/flags";

export async function POST(request: Request) {
  const user = { userId: request.headers.get("x-user-id") ?? undefined };
  await flags.fetchAllFlags(user);

  const guided = flags.isEnabled("guided-export", user).on;
  const limit = flags.getValue("export-limit", 100, user);
  return Response.json({ guided, limit });
}

A shared manager serves every request. Pass the request's user to each read instead of calling updateUser(), which changes the default user for every concurrent caller.

id is the flag definition's ID, as in GET /public/v1/flags/definitions. It's absent when the flag doesn't exist (reason: "NOT_FOUND"). After a successful fetchAllFlags(), keys it didn't return resolve as NOT_FOUND without another request.

Configure the manager

OptionTypeDefaultWhat it does
clientIdstringRequiredYour website's client ID
userUserContextDefault user for reads that don't pass one
environmentstringWhich flag definitions to use
defaultsRecord<string, unknown>Values served while loading, when missing and on errors
cacheTtlnumber60000How long an unresolved entry is kept, in ms
staleTimenumbercacheTtl / 2After this, a cached answer is served and refreshed in the background
maxStaleTimenumber86400000How long the last answer is served while refreshes fail. 0 evaluates every read
maxCacheSizenumber5000Entries kept for per-call users, least recently used dropped first
requestTimeoutMsnumber10000Deadline for one evaluation request
autoFetchbooleanfalseLoads every flag when the manager starts
disabledbooleanfalseEvery read returns off, even when a value is cached
isPendingbooleanfalseDefers evaluation; reads report pending
trackEvaluationsDatabuddyYour Node client, to record evaluations
apiUrlstringhttps://api.databuddy.ccFlags API endpoint
User fieldUsed for
userIdPer-user rollouts and rules
emailRules on email or domain
organizationId, teamIdOrganization and team rollouts
propertiesRules on any property
groupsAccounts by type, such as { workspace: "ws_1" }, seen by rules as group_<type>

Databuddy uses the user only to evaluate that request and doesn't store it. Checking flags from your server creates no analytics events unless you turn on trackEvaluations.

Choose what happens when Databuddy is down

If refreshes keep failing, the manager serves the last answer for up to maxStaleTime after it was evaluated. After that, getFlag() throws, isEnabled() returns your defaults value with status: "error", and getValue() returns its default. Retries wait 5 seconds, doubling to 60 seconds, or the API's Retry-After.

lib/flags.ts
import { createServerFlagsManager } from "@databuddy/sdk/node";

export const flags = createServerFlagsManager({
  clientId: process.env.DATABUDDY_CLIENT_ID!,
  maxStaleTime: 60_000,
  defaults: { "new-checkout": false },
});

That setup fails closed: features turn off within a minute of an outage. To evaluate every flag for one user in one request without a manager, such as while rendering a page, use evaluateFlags.

Record evaluations

Flag activity and experiment results count $flag_evaluated events, which the browser sends when it reads a flag. To count your server's reads too, pass your Node client as trackEvaluations.

lib/flags.ts
import { createServerFlagsManager, Databuddy } from "@databuddy/sdk/node";

const databuddy = new Databuddy({ apiKey: process.env.DATABUDDY_API_KEY! });

export const flags = createServerFlagsManager({
  clientId: process.env.DATABUDDY_CLIENT_ID!,
  trackEvaluations: databuddy,
});

Each read sends one event per user and value while the manager runs, and remembers the latest 10,000. It's linked to the userId you pass, which can be the browser's anonymous ID from getIds() for a signed-out visitor. Unknown flags and failed evaluations aren't sent. Each event counts toward your plan, and with batching on you call flush() before a serverless function returns.

How is this guide?