You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 2b71dcc
Browse filesBrowse the repository at this point in the historyBrowse files
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>
Copy file name to clipboardExpand all lines: packages/node-sdk/README.md
+67-85Lines changed: 67 additions & 85 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,14 +1,16 @@
1
1
# Reflag Node.js SDK
2
2
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.
4
4
5
-
## Installation and initialization
5
+
## Get started
6
+
7
+
Install the SDK:
6
8
7
9
```sh
8
10
yarn add @reflag/node-sdk
9
11
```
10
12
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:
12
14
13
15
```ts
14
16
import { ReflagClient } from"@reflag/node-sdk";
@@ -19,75 +21,74 @@ export const reflag = new ReflagClient({
`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.
36
38
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:
const payload =reflag.getFlag(context, "nullable-settings", null); // any JSON value; narrow it yourself
42
49
```
43
50
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.
45
54
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.
47
56
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:
49
60
50
61
```ts
51
-
const values =reflag.getFlags(context); // value record; checks each returned root
52
62
const bound =reflag.bindClient(context);
53
-
const value =bound.getFlag("model", "quick");
54
-
const allValues =bound.getFlags();
55
63
56
-
// Ordinary usage tracking is separate from flag checks.
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.
66
69
67
-
## Evaluation and synchronization
70
+
## Track usage
68
71
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.
`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.
72
77
73
-
Synchronization modes:
78
+
## Keep flags up to date
74
79
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`:
78
81
79
-
```ts
80
-
awaitreflag.refreshFlags();
81
-
awaitreflag.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.
84
85
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.
88
87
89
88
## Fallback providers
90
89
90
+
A fallback provider saves the latest flag definitions so your service can start even if Reflag is unreachable:
@@ -98,53 +99,42 @@ const client = new ReflagClient({
98
99
awaitclient.initialize();
99
100
```
100
101
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`.
102
103
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>`.
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.
144
134
145
-
## Typed flags
135
+
## Type safety
146
136
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:
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
163
152
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:
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.
176
160
177
161
## Remote evaluation
178
162
163
+
To evaluate flags on Reflag's servers instead of locally, use the remote methods:
164
+
179
165
```ts
180
-
const enabled =awaitreflag.getFlagRemote(
181
-
"new-editor",
182
-
undefined,
183
-
"user-1",
184
-
"acme",
185
-
);
186
166
const model =awaitreflag.getFlagRemote("model", "quick", "user-1", "acme");
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.
198
176
199
177
## Edge runtimes
200
178
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.
202
180
203
181
## Configuration
204
182
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`).
206
188
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
208
190
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 signalor call `process.exit()`, call`flush()` in your shutdown handler first.
0 commit comments