Skip to content

Commit 2b71dcc

Browse files
roncohenclaude
andcommitted
docs: restructure SDK guides around common tasks
Give the Browser, React, Vue and Node guides a shared outline (get started, read flags, track usage, update context, bootstrap, opt-in, toolbar, type safety, configuration), plain-language explanations, and restore toolbar and CSP guidance for browser frameworks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 352462d commit 2b71dcc

1 file changed

Lines changed: 67 additions & 85 deletions

File tree

‎packages/node-sdk/README.md‎

Lines changed: 67 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
# Reflag Node.js SDK
22

3-
Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com).
3+
Feature flags, remote configuration and usage tracking for Node.js servers.
44

5-
## Installation and initialization
5+
## Get started
6+
7+
Install the SDK:
68

79
```sh
810
yarn add @reflag/node-sdk
911
```
1012

11-
Create one client per process and initialize it before reading flags. Obtain your environment's secret key from Reflag's environment settings; complete flag definitions must remain server-side.
13+
Create one client per process with your environment's **secret** key, found in your Reflag environment settings. Initialize it before reading flags:
1214

1315
```ts
1416
import { ReflagClient } from "@reflag/node-sdk";
@@ -19,75 +21,74 @@ export const reflag = new ReflagClient({
1921
await reflag.initialize();
2022
```
2123

22-
## Read flags
24+
Then read a flag for a user and company:
2325

2426
```ts
2527
const context = {
2628
user: { id: "user-1" },
2729
company: { id: "acme", plan: "enterprise" },
2830
};
2931

30-
const enabled = reflag.getFlag(context, "new-editor"); // boolean; implicit false
31-
const model = reflag.getFlag(context, "model", "quick"); // string
32-
const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number }
32+
if (reflag.getFlag(context, "new-editor")) {
33+
// Show the new editor
34+
}
3335
```
3436

35-
`getFlag()` returns a Boolean, string, number, array, object, or null. Without a default it is a Boolean read: unavailable or non-Boolean values return `false`. With a positional default, missing values use that default. Valid `false`, `0`, empty strings, arrays, and objects are preserved rather than replaced by truthiness checks.
37+
The SDK downloads your flag definitions and evaluates flags locally, so reads don't make network requests. Keep the secret key on your server.
3638

37-
Non-null defaults specify the expected JSON category: Boolean, number, string, array, or object. A category mismatch logs a warning without the payload and returns the default. This is not nested payload validation: object properties and array elements must still match your authored schema. Use an explicit `null` default for arbitrary JSON or nullable/off selections, and narrow the result before accessing object fields:
39+
## Read flags
40+
41+
Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean.
42+
43+
To read a configuration value, pass a default. The return type follows the default, and you get the default back if the flag is missing or holds a different type of value:
3844

3945
```ts
40-
const payload = reflag.getFlag(context, "nullable-settings", null); // FlagValue
41-
// Authored null is preserved, as are any other valid JSON values. Missing uses null.
46+
const model = reflag.getFlag(context, "model", "quick"); // string
47+
const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number }
48+
const payload = reflag.getFlag(context, "nullable-settings", null); // any JSON value; narrow it yourself
4249
```
4350

44-
Defaults infer useful types without generated declarations, including widening primitive literals. Readonly defaults are accepted; results and defaults are returned as independent copies. Defaults are ordinary JSON payloads, with no reserved property names.
51+
The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them.
52+
53+
`getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable.
4554

46-
Each call records a check, even if you don't use the returned value. Reflag uses checks for launch monitoring; they are batched and rate-limited.
55+
Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring.
4756

48-
`getFlags()` returns a record of flag values; unavailable values may be `undefined`.
57+
## Bind a client to a request
58+
59+
To avoid passing the context on every call, bind it once, for example per request:
4960

5061
```ts
51-
const values = reflag.getFlags(context); // value record; checks each returned root
5262
const bound = reflag.bindClient(context);
53-
const value = bound.getFlag("model", "quick");
54-
const allValues = bound.getFlags();
5563

56-
// Ordinary usage tracking is separate from flag checks.
57-
await bound.track("Document created", { attributes: { source: "editor" } });
58-
await reflag.flush();
64+
const model = bound.getFlag("model", "quick");
65+
const allValues = bound.getFlags();
5966
```
6067

61-
Binding queues user/company attributes and their association even if the client is subsequently used only for tracking or remote reads. Synchronization is asynchronous and respects offline/tracking guards; failures are logged.
62-
63-
Local reads made before initialization include a `CLIENT_NOT_INITIALIZED` diagnostic in their check's optional `evalErrors`. Targeting diagnostics retain their code, field/operator when applicable, message, and dependency origin. Remote evaluation does not require the local definition cache to be initialized, and bootstrap/diagnostic access does not itself register checks.
64-
65-
`enableTracking: false` disables checks, context synchronization, and bound-client usage tracking. Explicit calls to the root client's `track()`, `updateUser()`, and `updateCompany()` remain separate operations.
68+
Binding also sends the user's and company's attributes to Reflag, so you can target and filter by them.
6669

67-
## Evaluation and synchronization
70+
## Track usage
6871

69-
The SDK fetches a complete `{ flags, segments }` graph from secret-key-only `GET /flags`. Definitions are validated and prepared before the flags, segments, and snapshot version replace the current cache together. Malformed graphs and stale responses cannot replace last-known-good state.
72+
```ts
73+
await bound.track("Document created", { attributes: { source: "editor" } });
74+
```
7075

71-
`getFlag()` evaluates only its root and dependencies. `getFlags()` evaluates the collection. References are reevaluated on every traversal: there is **no context/dependency-result caching**. Only immutable definition preparation is retained. Returned objects are independent copies, so changing a value cannot mutate the saved definitions.
76+
Configure your flag's adoption rules to match the event names you send. Events are sent in batches. Call `await reflag.flush()` to send any queued events, for example before your process exits.
7277

73-
Synchronization modes:
78+
## Keep flags up to date
7479

75-
- `push` (default): authenticated SSE updates with reconnect handling.
76-
- `polling`: periodic background refreshes.
77-
- `in-request`: request-driven refreshes, suitable for constrained runtimes.
80+
The client keeps flag definitions up to date in the background. Choose how with `flagsSyncMode`:
7881

79-
```ts
80-
await reflag.refreshFlags();
81-
await reflag.refreshFlags(42); // request at least this snapshot version
82-
const definitions = reflag.getFlagDefinitions(); // { flags, segments }, not an array
83-
```
82+
- `push` (default): receive updates as soon as flags change.
83+
- `polling`: refresh periodically.
84+
- `in-request`: refresh when flags are read, for environments without long-running background work.
8485

85-
Refreshes are throttled. In-request mode can queue a refresh during the throttle window until a later access; a refresh call is not an unconditional synchronization barrier.
86-
87-
Ordinary warm `/flags` refreshes send `If-None-Match` when the accepted snapshot has an ETag. A bodyless `304` retains the complete prepared graph and version while resetting freshness, without recompiling or saving it again. Cold/fallback initialization and version-targeted requests remain unconditional. Custom HTTP clients can return the exact optional `HttpClientResponse.etag` to enable this behavior; clients without one continue to use full GETs. Validators are enabled only after the snapshot's fallback save succeeds. Failed or pending saves leave refreshes unconditional, and rejected snapshots cannot replace a validator or overwrite fallback storage.
86+
Call `await reflag.refreshFlags()` to request a refresh yourself. If a refresh fails, the client keeps using the flags it already has.
8887

8988
## Fallback providers
9089

90+
A fallback provider saves the latest flag definitions so your service can start even if Reflag is unreachable:
91+
9192
```ts
9293
import { ReflagClient, fallbackProviders } from "@reflag/node-sdk";
9394

@@ -98,53 +99,42 @@ const client = new ReflagClient({
9899
await client.initialize();
99100
```
100101

101-
Live state is primary. When the initial live fetch fails, the SDK can load a saved complete collection. Later outages retain the in-memory graph rather than reloading older fallback state. Accepted live snapshots are saved in order; `flush()` also waits for pending saves.
102+
The client uses saved definitions only when it can't fetch them at startup. Built-in providers are `file`, `redis`, `s3`, `gcs` and `static`. You can also implement your own `FlagsFallbackProvider`.
102103

103-
Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `FlagsFallbackProvider` implementations. A snapshot contains:
104-
105-
```ts
106-
{
107-
version: 2,
108-
savedAt: "2026-01-01T00:00:00.000Z",
109-
flagStateVersion: 42,
110-
flags: [/* compiled flags */],
111-
segments: [/* compiled segment predicates */],
112-
}
113-
```
114-
115-
Built-in files/S3/GCS objects use `flags-fallback-v2-<hash-prefix>.json`; Redis uses `<keyPrefix>:v2:<hash-prefix>`.
116-
117-
A static fallback can contain any JSON values:
104+
A static provider takes fixed values:
118105

119106
```ts
120107
fallbackProviders.static({
121108
flags: { "new-editor": false, model: "quick", limits: null },
122109
});
123110
```
124111

125-
Providers are not loaded in offline mode.
126-
127112
## Overrides and tests
128113

114+
Use offline mode and overrides to run tests without contacting Reflag:
115+
129116
```ts
130117
const client = new ReflagClient({
131118
offline: true,
132119
flagOverrides: { "new-editor": true, limits: { maxItems: 5 } },
133120
});
134121
await client.initialize();
122+
135123
client.setFlagOverrides({ model: "quick" });
124+
136125
const remove = client.pushFlagOverrides((context) => ({
137126
model: context.company?.id === "qa" ? "quality" : "quick",
138127
}));
139128
remove();
129+
140130
client.clearFlagOverrides();
141131
```
142132

143-
Overrides are direct JSON values. Pushed layers win over base overrides and can be removed independently. They apply **after evaluation**, so overriding a dependency's returned value does not rewrite dependent flag evaluations. Offline mode does not fetch, load a provider, or send tracking events.
133+
Overrides pushed with `pushFlagOverrides()` take precedence over base overrides and can be removed independently. In offline mode, the client makes no network requests and sends no events.
144134

145-
## Typed flags
135+
## Type safety
146136

147-
Generated declarations are optional. Singular reads infer their return type from the default, or return Boolean when no default is supplied. Optionally augment `Flags` to constrain keys, check non-null defaults against each key's value schema, and type batch records:
137+
Optionally declare your flags to get autocompletion for keys, type checks for defaults and typed `getFlags()` results:
148138

149139
```ts
150140
declare module "@reflag/node-sdk" {
@@ -154,35 +144,25 @@ declare module "@reflag/node-sdk" {
154144
limits: { maxItems: number } | null;
155145
}
156146
}
157-
158-
const model = reflag.getFlag(context, "model", "quick"); // string
159-
const models = reflag.getFlags(context); // models.model: "quick" | "quality" | undefined
160147
```
161148

162-
Augmentation rejects defaults with the wrong category, missing required properties, or incompatible nested types. Named-interface and readonly defaults are supported. Explicit `null` remains an arbitrary-JSON request, and bare/`undefined` reads still return Boolean. Return types continue to be inferred and widened from the default; generated types do not add nested runtime validation. The Reflag CLI generates schemas from current production-environment variants. See the Express example for a typed integration.
149+
The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only.
150+
151+
## Bootstrap the browser
163152

164-
## Bootstrap state
153+
To render flags in the browser without waiting for a network request, evaluate them on the server and pass the result to the Browser, React or Vue SDK's bootstrap option:
165154

166155
```ts
167156
const bootstrap = reflag.getFlagsForBootstrap(context);
168-
// { protocolVersion: 2, context, flags: { model: { resolved, value,
169-
// variantKey, sourceVersionId, matchedRuleId, ruleResults, errors, ... } },
170-
// flagStateVersion }
171157
```
172158

173-
Bootstrap uses batch evaluation and does **not** register checks.
174-
175-
Pass the entire envelope to the Browser, React or Vue SDK's bootstrap option, not just its `flags` property. Use your framework's safe serialization mechanism and never expose secret keys or server-only context in public bootstrap data.
159+
Pass the whole object, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it.
176160

177161
## Remote evaluation
178162

163+
To evaluate flags on Reflag's servers instead of locally, use the remote methods:
164+
179165
```ts
180-
const enabled = await reflag.getFlagRemote(
181-
"new-editor",
182-
undefined,
183-
"user-1",
184-
"acme",
185-
);
186166
const model = await reflag.getFlagRemote("model", "quick", "user-1", "acme");
187167
const boundModel = await reflag
188168
.bindClient(context)
@@ -192,21 +172,23 @@ const values = await reflag.getFlagsRemote("user-1", "acme", {
192172
});
193173
```
194174

195-
These methods use `/flags/evaluated` and return direct values. Singular remote reads use the same defaults, category checks, and JSON validation as local reads. The root `getFlagRemote(key, defaultValue, userId?, companyId?, context?)` places the default second; use `undefined` for an implicit Boolean read when passing explicit IDs. `getFlagsRemote(userId?, companyId?, context?)` returns a record of flag values.
196-
197-
Each requested singular root registers a check, including a default after a failed/missing remote evaluation, unless tracking is disabled. Explicit IDs, including numeric zero, take precedence over IDs in additional context. Stored attribute updates are asynchronous; remote evaluation need not immediately observe a just-sent update.
175+
On the root client, the default comes second: `getFlagRemote(key, defaultValue, userId?, companyId?, context?)`. Pass `undefined` as the default for a Boolean read.
198176

199177
## Edge runtimes
200178

201-
Use `EdgeClient` with Node compatibility enabled. It selects in-request synchronization. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events and refresh work can complete.
179+
Use `EdgeClient` in edge runtimes such as Cloudflare Workers, with Node.js compatibility enabled. It refreshes flags as they're read. Call `ctx.waitUntil(client.flush())` before returning from a Worker so queued events are sent.
202180

203181
## Configuration
204182

205-
Configuration precedence is constructor options, environment variables, then `reflag.config.json`. Supported environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and Boolean override lists `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED`.
183+
Options can be set in the constructor, through environment variables, or in `reflag.config.json`, in that order of precedence.
184+
185+
Environment variables include `REFLAG_SECRET_KEY`, `REFLAG_API_BASE_URL`, `REFLAG_LOG_LEVEL`, `REFLAG_OFFLINE`, `REFLAG_CONFIG_FILE`, and `REFLAG_FLAGS_ENABLED` / `REFLAG_FLAGS_DISABLED` to override Boolean flags.
186+
187+
Constructor options include `logger`, `httpClient`, `flagsSyncMode`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, `flagOverrides`, `enableTracking`, `offline` and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`).
206188

207-
Constructor options also include a custom `logger` / `httpClient`, `flagsSyncMode`, `flagsPushUrl`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, direct-value `flagOverrides`, and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). `emitEvaluationEvents` is deprecated and has no effect.
189+
## Shutting down
208190

209-
Invalid options/context or non-JSON defaults can throw. Network or definition-refresh failures are logged and retain usable state. Singular reads use their caller default (implicit `false`); batch reads retain raw values/`undefined`. Call `await client.flush()` before shutting down, then `client.destroy()` to stop background work. `batchOptions.flushOnExit` only flushes on natural Node process exit (`beforeExit`); it does not install signal handlers or force application shutdown. For signal-driven shutdown or an explicit `process.exit()`, await `flush()` in the application's own shutdown hook before exiting.
191+
Before your process exits, call `await reflag.flush()` to send queued events, then `reflag.destroy()` to stop background work. `batchOptions.flushOnExit` flushes only when Node exits on its own; if you exit on a signal or call `process.exit()`, call `flush()` in your shutdown handler first.
210192

211193
## License
212194

0 commit comments

Comments
 (0)