From 9dd4e70ef9318a26ed0770d715b1600944664190 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Sun, 15 Nov 2026 20:19:00 +0000 Subject: [PATCH 1/6] docs: write Node SDK guide for new integrations --- packages/node-sdk/README.md | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index 6d3cde0a..076076ca 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -2,8 +2,6 @@ Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com). -> This branch implements the breaking v2 API. It requires the collection-capable evaluator, the v2 `/flags` endpoint, and compatible variant-key check ingestion. It has not been published or deployed. - ## Installation and initialization ```sh @@ -21,7 +19,7 @@ export const reflag = new ReflagClient({ await reflag.initialize(); ``` -## Direct values, immediate checks +## Read flags ```ts const context = { @@ -34,7 +32,7 @@ const model = reflag.getFlag(context, "model", "quick"); // string const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } ``` -**`getFlag()` returns the value itself**, not a flag object. There is no `.value`, `.isEnabled`, `.config`, or flag `.track()` wrapper. Without a default it is a Boolean read: unavailable or non-Boolean values return `false`, never a truthy object. 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. +`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. 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: @@ -59,7 +57,7 @@ Each call immediately registers a check for the requested root, including when y } ``` -Boolean selections send `"true"` / `"false"` while returning Boolean values. Caller defaults, including category-mismatch defaults, do not claim an authored selection: their checks omit `evalResult` and `sourceVersionId`. Check deduplication includes normalized context, selection identity, root version, and snapshot version. Equal-valued variants are not interchangeable selections. Batch `getFlags()` remains a raw value record, without per-root caller defaults; unavailable batch values may be `undefined`. +Boolean selections send `"true"` / `"false"` while returning Boolean values. Caller defaults, including category-mismatch defaults, do not claim an authored selection: their checks omit `evalResult` and `sourceVersionId`. Check deduplication includes normalized context, selection identity, root version, and snapshot version. Equal-valued variants are not interchangeable selections. `getFlags()` returns a record of flag values, without per-root caller defaults; unavailable batch values may be `undefined`. ```ts const values = reflag.getFlags(context); // value record; checks each returned root @@ -114,7 +112,7 @@ await client.initialize(); 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. -Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `FlagsFallbackProvider` implementations. A v2 snapshot contains: +Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `FlagsFallbackProvider` implementations. A snapshot contains: ```ts { @@ -126,7 +124,7 @@ Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `Fl } ``` -V1 flag-only snapshots are incompatible and are not automatically expanded or converted. Built-in files/S3/GCS objects use `flags-fallback-v2-.json`; Redis uses `:v2:`. This keeps v1 and v2 processes from overwriting each other's fallback state. +Built-in files/S3/GCS objects use `flags-fallback-v2-.json`; Redis uses `:v2:`. A static fallback can contain any JSON values: @@ -173,7 +171,7 @@ const model = reflag.getFlag(context, "model", "quick"); // string const models = reflag.getFlags(context); // models.model: "quick" | "quality" | undefined ``` -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 v2 CLI generates direct-value schemas from current production-environment variants. Regenerate old CLI wrapper declarations when migrating. Both destructuring `.isEnabled` and accessing it through an assigned singular value fail type checking, including without generated declarations. See the Express example for a typed direct-value integration. +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. ## Bootstrap state @@ -186,7 +184,7 @@ const bootstrap = reflag.getFlagsForBootstrap(context); Bootstrap uses batch evaluation and preserves selection metadata and raw context. It does **not** register browser checks. Local overrides/value-only fallbacks carry their values without fabricated authored-selection metadata. -**This is a v2 bootstrap contract, not the existing v1 Browser/React/Vue bootstrap shape.** Those consumers require a coordinated migration before accepting this state. Likewise, the current OpenFeature provider deliberately remains on published Node SDK v1 until its separate migration. +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. ## Remote evaluation @@ -206,7 +204,7 @@ const values = await reflag.getFlagsRemote("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. This moves the old positional IDs one place to the right. `getFlagsRemote()` keeps its existing argument order and returns a raw value record. +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. Each requested singular root registers a check, including a default after a failed/missing remote evaluation, unless tracking is disabled. Only accepted authored selections retain the server's selection/version metadata. 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. From 3d48c02c2a0c24fb33f9096f49b09ef47ba52129 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Mon, 16 Nov 2026 18:37:19 +0000 Subject: [PATCH 2/6] docs: remove check internals from SDK guides Co-Authored-By: Claude Opus 5.5 --- packages/node-sdk/README.md | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index 076076ca..bb244bf7 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -43,21 +43,9 @@ const payload = reflag.getFlag(context, "nullable-settings", null); // FlagValue 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. -Each call immediately registers a check for the requested root, including when you do not subsequently use its return value. Dependencies traversed internally do not register extra checks. Delivery is buffered and rate-limited. A check records the selected **variant key**, never the JSON payload: +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. -```ts -{ - type: "feature-flag-event", - action: "check", - key: "model", - evalResult: "quality", - sourceVersionId: "version-id", - flagStateVersion: 42, - evalContext: { company: { id: "acme", plan: "enterprise" } }, -} -``` - -Boolean selections send `"true"` / `"false"` while returning Boolean values. Caller defaults, including category-mismatch defaults, do not claim an authored selection: their checks omit `evalResult` and `sourceVersionId`. Check deduplication includes normalized context, selection identity, root version, and snapshot version. Equal-valued variants are not interchangeable selections. `getFlags()` returns a record of flag values, without per-root caller defaults; unavailable batch values may be `undefined`. +`getFlags()` returns a record of flag values; unavailable values may be `undefined`. ```ts const values = reflag.getFlags(context); // value record; checks each returned root @@ -134,7 +122,7 @@ fallbackProviders.static({ }); ``` -Static values, `fallbackFlags`, and overrides do not identify authored variants. Their checks omit `evalResult` and `sourceVersionId`; they must not claim exposure to an authored selection. Restored real collection snapshots retain their real selection/version metadata. Providers are not loaded in offline mode. +Providers are not loaded in offline mode. ## Overrides and tests @@ -182,7 +170,7 @@ const bootstrap = reflag.getFlagsForBootstrap(context); // flagStateVersion } ``` -Bootstrap uses batch evaluation and preserves selection metadata and raw context. It does **not** register browser checks. Local overrides/value-only fallbacks carry their values without fabricated authored-selection metadata. +Bootstrap uses batch evaluation and does **not** register checks. 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. @@ -206,7 +194,7 @@ const values = await reflag.getFlagsRemote("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. -Each requested singular root registers a check, including a default after a failed/missing remote evaluation, unless tracking is disabled. Only accepted authored selections retain the server's selection/version metadata. 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. +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. ## Edge runtimes @@ -218,7 +206,7 @@ Configuration precedence is constructor options, environment variables, then `re 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. -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`) without fabricating an authored false selection; 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. +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. ## License From b399e5d2e2acf60bf89e52ccfa1a47e65f608055 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Mon, 16 Nov 2026 18:41:31 +0000 Subject: [PATCH 3/6] 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 --- packages/node-sdk/README.md | 152 ++++++++++++++++-------------------- 1 file changed, 67 insertions(+), 85 deletions(-) diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index bb244bf7..854cfd30 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -1,14 +1,16 @@ # Reflag Node.js SDK -Server-side Boolean and multivariate flag values for [Reflag](https://reflag.com). +Feature flags, remote configuration and usage tracking for Node.js servers. -## Installation and initialization +## Get started + +Install the SDK: ```sh yarn add @reflag/node-sdk ``` -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. +Create one client per process with your environment's **secret** key, found in your Reflag environment settings. Initialize it before reading flags: ```ts import { ReflagClient } from "@reflag/node-sdk"; @@ -19,7 +21,7 @@ export const reflag = new ReflagClient({ await reflag.initialize(); ``` -## Read flags +Then read a flag for a user and company: ```ts const context = { @@ -27,67 +29,66 @@ const context = { company: { id: "acme", plan: "enterprise" }, }; -const enabled = reflag.getFlag(context, "new-editor"); // boolean; implicit false -const model = reflag.getFlag(context, "model", "quick"); // string -const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } +if (reflag.getFlag(context, "new-editor")) { + // Show the new editor +} ``` -`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. +The SDK downloads your flag definitions and evaluates flags locally, so reads don't make network requests. Keep the secret key on your server. -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: +## Read flags + +Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean. + +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: ```ts -const payload = reflag.getFlag(context, "nullable-settings", null); // FlagValue -// Authored null is preserved, as are any other valid JSON values. Missing uses null. +const model = reflag.getFlag(context, "model", "quick"); // string +const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } +const payload = reflag.getFlag(context, "nullable-settings", null); // any JSON value; narrow it yourself ``` -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. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. + +`getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. -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. +Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. -`getFlags()` returns a record of flag values; unavailable values may be `undefined`. +## Bind a client to a request + +To avoid passing the context on every call, bind it once, for example per request: ```ts -const values = reflag.getFlags(context); // value record; checks each returned root const bound = reflag.bindClient(context); -const value = bound.getFlag("model", "quick"); -const allValues = bound.getFlags(); -// Ordinary usage tracking is separate from flag checks. -await bound.track("Document created", { attributes: { source: "editor" } }); -await reflag.flush(); +const model = bound.getFlag("model", "quick"); +const allValues = bound.getFlags(); ``` -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. - -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. - -`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. +Binding also sends the user's and company's attributes to Reflag, so you can target and filter by them. -## Evaluation and synchronization +## Track usage -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. +```ts +await bound.track("Document created", { attributes: { source: "editor" } }); +``` -`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. +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. -Synchronization modes: +## Keep flags up to date -- `push` (default): authenticated SSE updates with reconnect handling. -- `polling`: periodic background refreshes. -- `in-request`: request-driven refreshes, suitable for constrained runtimes. +The client keeps flag definitions up to date in the background. Choose how with `flagsSyncMode`: -```ts -await reflag.refreshFlags(); -await reflag.refreshFlags(42); // request at least this snapshot version -const definitions = reflag.getFlagDefinitions(); // { flags, segments }, not an array -``` +- `push` (default): receive updates as soon as flags change. +- `polling`: refresh periodically. +- `in-request`: refresh when flags are read, for environments without long-running background work. -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. - -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. +Call `await reflag.refreshFlags()` to request a refresh yourself. If a refresh fails, the client keeps using the flags it already has. ## Fallback providers +A fallback provider saves the latest flag definitions so your service can start even if Reflag is unreachable: + ```ts import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; @@ -98,23 +99,9 @@ const client = new ReflagClient({ await client.initialize(); ``` -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. +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`. -Available providers: `static`, `file`, `redis`, `s3`, and `gcs`, plus custom `FlagsFallbackProvider` implementations. A snapshot contains: - -```ts -{ - version: 2, - savedAt: "2026-01-01T00:00:00.000Z", - flagStateVersion: 42, - flags: [/* compiled flags */], - segments: [/* compiled segment predicates */], -} -``` - -Built-in files/S3/GCS objects use `flags-fallback-v2-.json`; Redis uses `:v2:`. - -A static fallback can contain any JSON values: +A static provider takes fixed values: ```ts fallbackProviders.static({ @@ -122,29 +109,32 @@ fallbackProviders.static({ }); ``` -Providers are not loaded in offline mode. - ## Overrides and tests +Use offline mode and overrides to run tests without contacting Reflag: + ```ts const client = new ReflagClient({ offline: true, flagOverrides: { "new-editor": true, limits: { maxItems: 5 } }, }); await client.initialize(); + client.setFlagOverrides({ model: "quick" }); + const remove = client.pushFlagOverrides((context) => ({ model: context.company?.id === "qa" ? "quality" : "quick", })); remove(); + client.clearFlagOverrides(); ``` -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. +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. -## Typed flags +## Type safety -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: +Optionally declare your flags to get autocompletion for keys, type checks for defaults and typed `getFlags()` results: ```ts declare module "@reflag/node-sdk" { @@ -154,35 +144,25 @@ declare module "@reflag/node-sdk" { limits: { maxItems: number } | null; } } - -const model = reflag.getFlag(context, "model", "quick"); // string -const models = reflag.getFlags(context); // models.model: "quick" | "quality" | undefined ``` -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. +The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. + +## Bootstrap the browser -## Bootstrap state +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: ```ts const bootstrap = reflag.getFlagsForBootstrap(context); -// { protocolVersion: 2, context, flags: { model: { resolved, value, -// variantKey, sourceVersionId, matchedRuleId, ruleResults, errors, ... } }, -// flagStateVersion } ``` -Bootstrap uses batch evaluation and does **not** register checks. - -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. +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. ## Remote evaluation +To evaluate flags on Reflag's servers instead of locally, use the remote methods: + ```ts -const enabled = await reflag.getFlagRemote( - "new-editor", - undefined, - "user-1", - "acme", -); const model = await reflag.getFlagRemote("model", "quick", "user-1", "acme"); const boundModel = await reflag .bindClient(context) @@ -192,21 +172,23 @@ const values = await reflag.getFlagsRemote("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. - -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. +On the root client, the default comes second: `getFlagRemote(key, defaultValue, userId?, companyId?, context?)`. Pass `undefined` as the default for a Boolean read. ## Edge runtimes -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. +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. ## Configuration -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`. +Options can be set in the constructor, through environment variables, or in `reflag.config.json`, in that order of precedence. + +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. + +Constructor options include `logger`, `httpClient`, `flagsSyncMode`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, `flagOverrides`, `enableTracking`, `offline` and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). -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. +## Shutting down -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. +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. ## License From 3c6dff1b15db40af9f2b3c561343d315312a18b9 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Mon, 16 Nov 2026 18:59:50 +0000 Subject: [PATCH 4/6] docs: simplify how SDK guides explain flag reads and defaults Co-Authored-By: Claude Opus 5.5 --- packages/node-sdk/README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index 854cfd30..77580af1 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -38,16 +38,21 @@ The SDK downloads your flag definitions and evaluates flags locally, so reads do ## Read flags -Without a default, `getFlag()` returns a Boolean. You get `false` if the flag is missing or isn't a Boolean. +Pass a context and a flag key to check whether the flag is enabled: -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: +```ts +const enabled = reflag.getFlag(context, "new-editor"); // true or false +``` + +To read a configuration value, pass a default as the third argument. You get back a value of the same type as the default: ```ts const model = reflag.getFlag(context, "model", "quick"); // string const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } -const payload = reflag.getFlag(context, "nullable-settings", null); // any JSON value; narrow it yourself ``` +If the flag doesn't exist, or its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. + The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. `getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. From a4e6d19da098ebec4cc7df3e62304d1432d7e10c Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:01:17 +0000 Subject: [PATCH 5/6] docs: tidy Node guide configuration, edge and remote sections Co-Authored-By: Claude Opus 5.5 --- packages/node-sdk/README.md | 70 +++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 11 deletions(-) diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index 77580af1..790963dc 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -4,6 +4,8 @@ Feature flags, remote configuration and usage tracking for Node.js servers. ## Get started +### 1. Create a client + Install the SDK: ```sh @@ -21,7 +23,22 @@ export const reflag = new ReflagClient({ await reflag.initialize(); ``` -Then read a flag for a user and company: +Keep the secret key on your server. + +### 2. Create a flag + +Install the Reflag CLI and create a flag: + +```sh +yarn add --dev @reflag/cli +npx reflag new +``` + +The first time you run it, it signs you in to Reflag, saves its settings in `reflag.config.json` and generates types for your flags in `gen/flags.d.ts`. Choose `node` when asked for the output format, and make sure your `tsconfig.json` includes the generated file. You can also create flags in the Reflag app. + +### 3. Read the flag + +Read a flag for a user and company: ```ts const context = { @@ -34,7 +51,7 @@ if (reflag.getFlag(context, "new-editor")) { } ``` -The SDK downloads your flag definitions and evaluates flags locally, so reads don't make network requests. Keep the secret key on your server. +The SDK downloads your flag definitions and evaluates flags locally, so reads don't make network requests. ## Read flags @@ -57,7 +74,7 @@ The SDK checks only the top-level type of a value. If your application depends o `getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. -Reading a flag records a check, even if you don't use the value. Reflag uses checks for launch monitoring. +Each read records a check, which Reflag uses for launch monitoring. ## Bind a client to a request @@ -78,7 +95,7 @@ Binding also sends the user's and company's attributes to Reflag, so you can tar await bound.track("Document created", { attributes: { source: "editor" } }); ``` -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. +Configure your flag's adoption rules to match the event names you send. Events are sent in batches; see [Shutting down](#shutting-down) to send them before your process exits. ## Keep flags up to date @@ -139,7 +156,7 @@ Overrides pushed with `pushFlagOverrides()` take precedence over base overrides ## Type safety -Optionally declare your flags to get autocompletion for keys, type checks for defaults and typed `getFlags()` results: +Declaring your flags gives you autocompletion for keys, type checks for defaults and typed `getFlags()` results. If you created a flag with `npx reflag new`, the declarations are already generated; run `npx reflag flags types` again when your flags change. A declaration looks like this: ```ts declare module "@reflag/node-sdk" { @@ -151,7 +168,7 @@ declare module "@reflag/node-sdk" { } ``` -The [Reflag CLI](https://docs.reflag.com/api/cli) can generate these declarations for you. Declarations are checked at compile time only. +Declarations are checked at compile time only. See the [Reflag CLI](https://docs.reflag.com/api/cli) for more options. ## Bootstrap the browser @@ -177,19 +194,50 @@ const values = await reflag.getFlagsRemote("user-1", "acme", { }); ``` -On the root client, the default comes second: `getFlagRemote(key, defaultValue, userId?, companyId?, context?)`. Pass `undefined` as the default for a Boolean read. +Unlike `getFlag()`, `getFlagRemote()` on the root client takes the default before the user and company IDs. To read a Boolean, pass `undefined` as the default. ## Edge runtimes -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. +Use `EdgeClient` in edge runtimes such as Cloudflare Workers, with Node.js compatibility enabled. It refreshes flags as they're read, instead of in the background: + +```ts +import { EdgeClient } from "@reflag/node-sdk"; + +let reflag: EdgeClient | undefined; + +export default { + async fetch(request, env, ctx) { + reflag ??= new EdgeClient({ secretKey: env.REFLAG_SECRET_KEY }); + await reflag.initialize(); + const enabled = reflag.getFlag({ user: { id: "user-1" } }, "new-editor"); + ctx.waitUntil(reflag.flush()); + return new Response(enabled ? "New editor" : "Old editor"); + }, +}; +``` + +Call `ctx.waitUntil(reflag.flush())` before returning so queued events are sent. ## Configuration Options can be set in the constructor, through environment variables, or in `reflag.config.json`, in that order of precedence. -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. - -Constructor options include `logger`, `httpClient`, `flagsSyncMode`, `fetchTimeoutMs`, `flagsFetchRetries`, `flagsFallbackProvider`, `flagOverrides`, `enableTracking`, `offline` and `batchOptions` (`maxSize`, `intervalMs`, `flushOnExit`). +| Option | Environment variable | Description | +| ----------------------- | ----------------------------------------------- | -------------------------------------------------------------------- | +| `secretKey` | `REFLAG_SECRET_KEY` | Your environment's secret key | +| `apiBaseUrl` | `REFLAG_API_BASE_URL` | Override the API URL | +| `logLevel`, `logger` | `REFLAG_LOG_LEVEL` | Log level (default `INFO`) or a custom logger | +| `offline` | `REFLAG_OFFLINE` | Make no network requests, for example in tests | +| `configFile` | `REFLAG_CONFIG_FILE` | Path to a config file other than `reflag.config.json` | +| `flagOverrides` | `REFLAG_FLAGS_ENABLED`, `REFLAG_FLAGS_DISABLED` | Override flags; the variables take comma-separated Boolean flag keys | +| `flagsSyncMode` | | How flag definitions are kept up to date; default `push` | +| `flagsFallbackProvider` | | Where to save flag definitions for startup | +| `fetchTimeoutMs` | | Request timeout; default 10,000 ms | +| `flagsFetchRetries` | | Retries for fetching flag definitions; default 3 | +| `batchOptions` | | Event batching: `maxSize`, `intervalMs` and `flushOnExit` | +| `httpClient` | | Custom HTTP client | + +To stop sending checks and events for a context, include `enableTracking: false` in it. ## Shutting down From 64bf707ec4527bdfec6395a75e759d117c4d226e Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Wed, 18 Nov 2026 18:38:39 +0000 Subject: [PATCH 6/6] docs(node-sdk): clarify bootstrap compatibility and tracking controls --- packages/node-sdk/README.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index 790963dc..c38e69af 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -172,13 +172,15 @@ Declarations are checked at compile time only. See the [Reflag CLI](https://docs ## Bootstrap the browser -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: +**Requires a Browser, React or Vue SDK that supports the v2 bootstrap protocol.** V1 consumers expect a different flag shape and cannot use this result. + +With a compatible v2 consumer, evaluate flags on the server to render them in the browser without waiting for a network request: ```ts const bootstrap = reflag.getFlagsForBootstrap(context); ``` -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. +Pass the whole object to the compatible consumer's bootstrap option, serialized with your framework's usual mechanism. Do not pass it to a v1 SDK. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. ## Remote evaluation @@ -237,7 +239,14 @@ Options can be set in the constructor, through environment variables, or in `ref | `batchOptions` | | Event batching: `maxSize`, `intervalMs` and `flushOnExit` | | `httpClient` | | Custom HTTP client | -To stop sending checks and events for a context, include `enableTracking: false` in it. +To disable checks, automatic user/company updates and bound-client usage tracking for a context, pass `enableTracking: false` to reads or `bindClient()`, not to the constructor: + +```ts +reflag.getFlag({ ...context, enableTracking: false }, "new-editor"); +const untracked = reflag.bindClient({ ...context, enableTracking: false }); +``` + +Explicit calls to the root client's `track()`, `updateUser()` and `updateCompany()` remain separate operations and still send events. ## Shutting down