Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
af36337
docs: remove prerelease wording from framework SDK READMEs
roncohen Nov 28, 2026
6221dd1
docs: simplify Browser SDK tagline
roncohen Nov 28, 2026
e520ca9
docs: always say React Native in the React Native README
roncohen Nov 28, 2026
d20c2c9
docs: name the React Native SDK and provider explicitly
roncohen Nov 28, 2026
8ab8798
docs: move the bootstrap upgrade note into React Native migration
roncohen Nov 28, 2026
a182c3d
docs: move React and Vue bootstrap upgrade notes into migration
roncohen Nov 28, 2026
5d5f858
docs: drop bootstrap secrets warning from framework READMEs
roncohen Nov 28, 2026
30bbdb5
docs: simplify React Native key registration
roncohen Nov 28, 2026
2051aba
docs: explain React Native fallback flag migration plainly
roncohen Nov 28, 2026
edd76ca
docs: replace direct-value terminology in framework READMEs
roncohen Nov 28, 2026
4fb8058
docs: simplify React and Vue key registration
roncohen Nov 28, 2026
c40de4f
docs: name fallbackFlags explicitly in React Native README
roncohen Nov 28, 2026
43170de
docs: replace fallbackFlags with read defaults in framework READMEs
roncohen Nov 28, 2026
b6d0a95
docs: use the same bootstrap migration note in every framework README
roncohen Nov 28, 2026
328494c
docs: simplify bootstrap sections in framework READMEs
roncohen Nov 28, 2026
99b2f2d
docs: simplify flag read and check sections in framework READMEs
roncohen Nov 28, 2026
c34e870
docs: say checks feed exposure counts and debugging
roncohen Nov 28, 2026
7bb9855
docs: simplify context, refresh and cache sections
roncohen Nov 28, 2026
35ad9dc
docs: simplify overrides, opt-in and tracking sections
roncohen Nov 28, 2026
e6e41bc
docs: mention that checks show up in the Event Log
roncohen Nov 28, 2026
ebde9a1
docs: use the same migration list in every framework README
roncohen Nov 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 46 additions & 54 deletions packages/browser-sdk/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
# Reflag Browser SDK v2

Client-side feature flags and JSON values for [Reflag](https://reflag.com).

> This is a breaking v2 prerelease. It requires the v2 evaluated-flags/check protocol on the server. Do not switch existing v1 applications or bootstrap consumers without coordinating that upgrade. Nothing in this branch publishes or deploys the SDK/server.
Client-side feature flags for [Reflag](https://reflag.com).

## Get started

Expand All @@ -28,32 +26,27 @@ if (enabled) {

Use only a **publishable** key in a browser. Secret keys belong on your server.

## Direct-value reads
## Read flags

```ts
reflag.getFlag("release"); // boolean; missing/mismatched -> false
reflag.getFlag("huddles"); // true or false
reflag.getFlag("model", "quick"); // string
reflag.getFlag("limit", 10); // number
reflag.getFlag("settings", { model: "quick" });
reflag.getFlag("nullable-settings", null); // FlagValue (arbitrary JSON)
reflag.getFlag("settings", { model: "quick" }); // { model: string }
reflag.getFlag("anything", null); // any JSON value
```

- Defaults are positional JSON values; generation is not required for useful types. Primitive literals widen, and readonly defaults are accepted.
- A non-null default accepts only the same **top-level JSON category**: Boolean, number, string, array or object. A mismatch warns without logging the payload and returns the default. A bare read can never return a truthy object.
- Explicit `null` accepts any JSON value, including authored null. Missing values return null.
- Falsy selected values (`false`, `0`, `""`, null) are preserved when accepted by the requested category.
- Object fields and array elements are **not schema-validated**. Validate untrusted/nested payloads in your application.
- Values and defaults are returned as independent mutable copies. There are no reserved JSON property names.
Without a default, a read expects a Boolean and returns `false` if the flag is missing or isn't a Boolean. With a default, the read returns the default while flags load, or if the flag is missing or has a different JSON type. Pass `null` to accept any JSON value, then check its type before using it.

`getFlags()` returns a direct-value record (entries may be undefined) and registers checks for its returned roots. `getFlagResults()` returns owned evaluated diagnostics **without checks**; it is intended for tooling, not ordinary application reads. `getFlagsForBootstrap()` serializes protocol-v2 evaluated state without checks.
The SDK doesn't check object fields or fill in missing fields from your default.

## Checks and delivery
`getFlags()` returns all flag values as an object.

Calling a getter registers a requested-root check immediately, even if its return value is ignored. There are no `.isEnabled`, `.config`, `.value` or flag `.track()` wrappers. Delivery remains buffered through `/bulk` and identity-aware rate-limited.
## Checks

A selected check carries the authored selected key as `evalResult`, its `sourceVersionId` and the available snapshot `flagStateVersion`. Payload equality is not identity: equal-valued selections or segment-only snapshot changes remain distinguishable on subsequent reads. Defaults, category mismatches, local overrides and static fallback values do not fabricate authored selections. Diagnostics and bootstrap serialization generate no checks. The server evaluates dependencies; fetching their results does not itself register reads.
Each read records a check. Reflag uses checks for exposure counts, and they show up in the Event Log, which helps with debugging. `getFlags()` records a check for every flag it returns.

`enableTracking: false` disables checks and user/company/usage tracking. `offline: true` skips HTTP and tracking. `await reflag.stop()` flushes buffered events and closes the client's background transports.
Set `enableTracking: false` to stop sending checks and events, or `offline: true` to skip all requests. `await reflag.stop()` sends pending events and closes the client's connections.

## Context, refresh and cache

Expand All @@ -68,47 +61,44 @@ await reflag.setContext({
await reflag.refresh();
```

`setContext()` replaces the context; update methods shallow-merge their section. User/company sections require IDs, including valid numeric zero. Context supports nested JSON and arrays. A context change clears the old context's values while fetching; stale/in-flight responses cannot replace a newer context or snapshot.

Values come from `GET /flags/evaluated`, not legacy `/features/evaluated`. Server evaluation retains the complete internal graph and authorized public roots. The Browser SDK does not cache dependency evaluations of its own.
`setContext()` replaces the whole context. The update methods merge new attributes into the user, company or other context. Users and companies need an `id`. While flags for a new context load, reads return their defaults.

Constructor options include:

| Option | Behavior |
| ------------------------------- | --------------------------------------------------------------------------- |
| `apiBaseUrl`, `appBaseUrl` | API origin and toolbar/feedback links |
| `credentials` | Fetch credentials mode; `include` also enables default SSE credentials |
| `timeoutMs` | Flag request timeout; default 5,000 ms |
| `staleTimeMs` | Fresh-cache duration; default 0 |
| `staleWhileRevalidate` | Serve stale cached state while revalidating; default false |
| `expireTimeMs` | Cache expiry; default 30 days |
| `storage` | Optional async storage adapter |
| `fallbackFlags` | Value record or array of enabled Boolean keys, without authored provenance |
| `enableLiveFlagUpdates` | Refresh after SSE publications; default false in Browser, true in React/Vue |
| `eventSourceFactory` | Optional EventSource-compatible transport |
| `trackingQueue` | Buffered-delivery `flushDelayMs` and `maxSize` |
| `logger`, `toolbar`, `feedback` | Logging, Boolean override toolbar and feedback options |

Evaluated cache and override storage use isolated v2 keys. V1 cache entries are never interpreted as v2 values. Malformed refreshes leave known-good state intact. Valid saved v2 selections retain their real provenance on restore. There is no automatic periodic HTTP fallback after an SSE failure; manual refresh/context updates remain available.
| Option | Behavior |
| ------------------------------- | -------------------------------------------------------------------------------------------------- |
| `apiBaseUrl`, `appBaseUrl` | API origin and toolbar/feedback links |
| `credentials` | Fetch credentials mode |
| `timeoutMs` | Flag request timeout; default 5,000 ms |
| `staleTimeMs` | Fresh-cache duration; default 0 |
| `staleWhileRevalidate` | Serve stale cached state while revalidating; default false |
| `expireTimeMs` | Cache expiry; default 30 days |
| `storage` | Optional async storage adapter |
| `enableLiveFlagUpdates` | Update flags as soon as they change in Reflag; default `false` in Browser, `true` in React and Vue |
| `eventSourceFactory` | Custom EventSource implementation for live updates |
| `trackingQueue` | How long to batch events (`flushDelayMs`) and the batch size (`maxSize`) |
| `logger`, `toolbar`, `feedback` | Logging, toolbar and feedback options |

Flags are cached in the browser. If a refresh fails, the client keeps the last values it received.

## Overrides and toolbar

```ts
reflag.setFlagOverride("release", true);
reflag.setFlagOverride("settings", { model: "local" });
reflag.setFlagOverride("nullable-settings", null); // a real null override
reflag.setFlagOverride("release", undefined); // clear the override
reflag.setFlagOverride("nullable-settings", null); // override with null
reflag.setFlagOverride("release", undefined); // remove the override
```

Overrides apply after server evaluation and do not rewrite authored dependency results. The built-in toolbar appears on localhost by default and offers Boolean overrides only. It uses diagnostic access, so opening it does not register application checks.
Overrides apply on top of the values from Reflag and are saved in the browser. The toolbar appears on localhost by default and lets you override Boolean flags. Opening it doesn't record checks.

## Server bootstrap

Generate the full payload with **Node SDK v2** on your server:
Get the bootstrap data from the Node.js SDK on your server:

```ts
const bootstrappedState = serverClient.getFlagsForBootstrap(context);
// Send via your framework's safe JSON/hydration mechanism.
// Serialize this into the page with your framework's usual mechanism.
```

```ts
Expand All @@ -117,7 +107,7 @@ await reflag.initialize();
const enabled = reflag.getFlag("release");
```

The payload includes `protocolVersion: 2`, context, evaluated diagnostics/selections and an optional snapshot version. V1 payloads and the old `bootstrappedFlags` option are rejected. Preserve the entire envelope; do not pass just its `flags` property. A version is required for bootstrapped live updates. Never embed secrets or server-only context in public bootstrap data. Later refreshes use browser-visible context and can differ from server-only evaluation; disable live updates when that is inappropriate. Requesting missing opt-in metadata still makes a browser-side request even when live updates are disabled.
Pass the whole object, not just its `flags`. Flags are then available immediately, without a network request. With live updates on, later refreshes evaluate flags using the browser's context, so values that depend on server-only attributes can change. Set `enableLiveFlagUpdates: false` if they must not.

## End-user opt-in

Expand All @@ -132,21 +122,23 @@ try {
}
```

The list contains presentation/membership metadata (`key`, `name`, `description`, `isEnabled`, `userOptedIn`, `companyOptedIn`, `isOptedIn`); this is not the ordinary flag getter API. User/company grants remain independent. The selected scope requires its ID. Successful mutations wait for versioned evaluation and membership confirmation.

Metadata arrives with ordinary `/flags/evaluated` responses and is cached with the evaluated snapshot. Bootstrapped clients whose snapshot lacks metadata fetch it on demand from the same v2 endpoint, without replacing server-derived values or provenance with browser-context evaluations. Loading settles on success or failure, including an empty list. Opt-in mutations confirm values and membership together in one versioned refresh. `optInFlagsLoadingUpdated` and `flagsUpdated` support UI subscriptions. Failed metadata requests settle loading without exposing an error; call `reflag.refresh()` to retry. Check the mutation's returned `Response.ok` and catch promise rejections: HTTP failures return a readable non-OK response without refreshing, skipped calls return undefined, and confirmation can fail after membership changed remotely.
Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `reflag.refresh()` to retry.

## Tracking, feedback and events

Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({ flagKey, ... })` on the client. See [FEEDBACK.md](./FEEDBACK.md) for the feedback UI and prompting configuration.

`on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated` (evaluated diagnostics), `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`.
`on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated`, `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`.

## Migrating from v1

## Migration from v1
- `getFlag()` returns the flag's value: replace `getFlag(key).isEnabled` with `getFlag(key)`.
- Move remote config to a multivariate flag and read it with a default, such as `getFlag("model", "quick")`. Existing remote config isn't converted automatically.
- Use the client's `track()` and `requestFeedback()` instead of the flag's.
- `setFlagOverride(key, value)` takes the value directly; pass `undefined` to remove an override.
- `getFlags()` returns all flag values and records a check for each.
- Remove `fallbackFlags` and pass a default to each read instead, such as `getFlag("huddles", true)`.
- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time.
- If you generate type declarations, regenerate them with the v2 CLI.

- Replace `getFlag(key).isEnabled` with `getFlag(key)`.
- Replace legacy remote config access with a separately authored multivariate flag and a positional default. Legacy config is **not** automatically converted into v2 values.
- Move flag `.track()` / `.requestFeedback()` calls to ordinary client methods.
- Replace wrapper overrides with `setFlagOverride(key, value)`; undefined clears, null is a value.
- `getFlags()` now returns values and registers checks. Tooling should use `getFlagResults()`.
- Upgrade both ends of bootstrap to v2. Old Browser/framework clients remain incompatible with v2 bootstrap.
See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps.
Loading
Loading