SDK reference

Feature flags

Declare a flag with its default, read it with one hook, and change who sees it from the dashboard without a deploy.

flags.ts
import { defineFlag } from "@databuddy/sdk";

export const newCheckout = defineFlag("new-checkout", { default: false });
export const theme = defineFlag<"light" | "dark">("theme", { default: "light" });
app/providers.tsx
"use client";

import { DatabuddyProvider, useFlag } from "@databuddy/sdk/react";
import { newCheckout } from "./flags";

export function Providers({ children }: { children: React.ReactNode }) {
  const { user, isPending } = useSession();
  return (
    <DatabuddyProvider
      user={user ? { id: user.id, traits: { email: user.email, plan: user.plan } } : null}
      userPending={isPending}
    >
      {children}
    </DatabuddyProvider>
  );
}

export function Checkout() {
  return useFlag(newCheckout) ? <NewCheckout /> : <OldCheckout />;
}

DatabuddyProvider loads flags the first time a component reads one, so apps that use no flags make no flag requests.

Read a flag

FunctionReturns
defineFlag(key, { default })A flag, typed by its default. Import it wherever you read it.
useFlag(flag)The value, never undefined.
useFlagDetails(flag){ value, loading, status, variant, reason, error, id }
useFlagsStatus(){ isReady, error, refresh } for all flags.
checkout.tsx
import { useFlagDetails } from "@databuddy/sdk/react";
import { newCheckout } from "./flags";

export function Checkout() {
  const { value, loading, status } = useFlagDetails(newCheckout);
  if (loading) return <Skeleton />;
  if (status === "error") return <OldCheckout />;
  return value ? <NewCheckout /> : <OldCheckout />;
}
statusWhenvalue
loadingFlags haven't loaded yetThe default, or the value saved from the last visit
pendinguserPending is setThe default
readyEvaluatedThe flag's value
errorThe first request failedThe default

The default is also served when the provider is disabled and when the flag doesn't exist (NOT_FOUND). A value whose type doesn't match the default is ignored too (TYPE_MISMATCH). A failed request is retried after 5 seconds, doubling up to 60 seconds, or after the API's Retry-After. A failed refresh keeps the last value.

Target users and accounts

Flags target the user you pass to the provider. The flag check uses it only to evaluate the request and stores none of it.

user fieldUsed for
idPer-user rollouts and rules on user ID
traitsRules on any property, such as plan or role. Also saved on the profile.
emailRules on email or domain, for targeting only. Defaults to traits.email.
organizationIdOrganization rollouts. Defaults to the provider's groups.organization.
teamIdTeam rollouts. Defaults to the provider's groups.team.

In the dashboard, choose what a rollout should Bucket by. Everyone in one bucket gets the same result.

Bucket byWho shares a result
UserNobody; each user on their own
OrganizationEveryone with the same organizationId
TeamEveryone with the same teamId
An account type, such as workspaceEveryone in one account from groups. Users in no account of that type share one result.
  1. Direct user rules
  2. Target groups
  3. Variant split
  4. Rollout %
  5. Default

Rules run in that order, and the first match wins. Rules and target groups support equals, contains, starts_with, ends_with, in and not_in; property rules add exists and not_exists. A flag that depends on another is blocked while that parent is paused, archived or deleted in the same environment.

Run an A/B test

Make a multivariant flag in the dashboard, then render from variant. Weights must total 100, or leave them out for an even split. Each user gets the same variant every time.

export-panel.tsx
import { defineFlag } from "@databuddy/sdk";
import { useFlagDetails } from "@databuddy/sdk/react";

const exportFlow = defineFlag("export-flow", { default: "control" });

export function ExportPanel() {
  const { variant, loading } = useFlagDetails(exportFlow);
  if (loading) return <Skeleton />;
  return variant === "guided" ? <GuidedExport /> : <DefaultExport />;
}

Reading a flag sends one $flag_evaluated event per flag per page load, which counts toward your plan. In Feature flags → Experiments, pick the flag and a conversion goal to compare each variant's visitors and conversions after their first evaluation.

Results ruleWhat it means
Only randomly assigned visitors countVisitors placed by a rule or a dependency, and those who saw several variants, are left out and reported separately
Changing variants, weights or the rollout restarts countingResults count visitors from that change on
Three or more variantsEach comparison needs stronger evidence (Holm's correction)
Boolean flagsRules choose the groups, so On/Off never shows a significant result
EnvironmentsNot separated

An evaluation isn't proof the feature was seen. For that, track() one exposure event when the flagged view appears, then the outcome, each with the flag key and variant.

Render flags on the server

Evaluate flags while rendering and pass them to the provider. The page renders with real values, and the browser starts from them without a request.

app/layout.tsx
import { evaluateFlags } from "@databuddy/sdk/node";
import { DatabuddyProvider } from "@databuddy/sdk/react";

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const session = await getSession();
  const user = session ? { id: session.user.id, traits: { email: session.user.email } } : null;
  const clientId = process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!;
  const bootstrap = await evaluateFlags({ clientId, user });

  return (
    <html lang="en">
      <body>
        <DatabuddyProvider clientId={clientId} user={user} flags={{ bootstrap }}>
          {children}
        </DatabuddyProvider>
      </body>
    </html>
  );
}
RuleWhy
Pass the same user, groups, client ID and environment to bothFlags evaluated for anything else are ignored
Expect nullA failure or a request over timeoutMs (2 seconds) returns null, and the browser loads flags itself
Cache results for signed-out visitors per environmentThey're the same for everyone, and server requests share the limit of 600 a minute per website from one IP
Expect percentage splits to change for signed-out visitorsThe server can't know the browser's anonymous ID, so the browser's evaluation wins when it arrives

Configure the provider

PropTypeDefaultWhat it does
userDatabuddyUser | nullThe signed-in user, or null when signed out
userPendingbooleanfalseWaits for the session instead of evaluating anonymously first
groupsRecord<string, string | null | undefined>The user's accounts, for account rollouts and rules on group_<type>
disabledbooleanfalseTurns off tracking and flags; flags serve their defaults
flags.environmentstringWhich flag definitions to use. Without it, only definitions with no environment
flags.persistbooleantrueKeeps values in localStorage so the next visit starts with them
flags.maxStaleTimenumber86400000How long, in ms, the last value is served while refreshes fail. Then reads return the default
flags.bootstrapFlagsBootstrap | nullFlags from evaluateFlags
flags.clientIdstringThe provider'sServe another website's flags
flags.apiUrlstringhttps://api.databuddy.ccFlags API endpoint

Reads made within 10 ms share one request, and identical requests are sent once. Background refreshes pause while the tab is hidden. Changing user clears the previous user's flags and fetches the new ones; inline objects are compared by value.

The Vue plugin takes user: { userId, email, organizationId, teamId, properties } and isPending, disabled, environment, cacheTtl, staleTime, maxStaleTime, autoFetch and skipStorage directly.

Using useFlag("key") or useFlags()? They still work. See Upgrade guide.

How is this guide?