Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
194 changes: 109 additions & 85 deletions packages/browser-sdk/README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
# Reflag Browser SDK v2
# Reflag Browser SDK

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.
Feature flags, remote configuration, usage tracking and feedback for browser applications.

## Get started

### 1. Create a client

Install the SDK:

```sh
npm install @reflag/browser-sdk
```

Create a client with your **publishable** key and the signed-in user's context:

```ts
import { ReflagClient } from "@reflag/browser-sdk";

Expand All @@ -15,138 +23,154 @@ const reflag = new ReflagClient({
company: { id: "acme", plan: "enterprise" },
});
await reflag.initialize();
```

Publishable keys are safe to ship to the browser. Keep secret keys on your server.

### 2. Create a flag

const enabled = reflag.getFlag("huddles"); // boolean, implicit false
const settings = reflag.getFlag("assistant-settings", { model: "quick" });
// settings: { model: string }
Create a flag with the key `huddles` in the Reflag app.

if (enabled) {
// Application usage tracking is separate from reading the flag.
### 3. Read the flag

```ts
if (reflag.getFlag("huddles")) {
await reflag.track("Started huddle");
}
```

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

## Direct-value reads
Pass a flag key to check whether the flag is enabled:

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

- 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.
Pass a default as the second argument to read a configuration value. The default sets the expected JSON type:

`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.
```ts
const model = reflag.getFlag("model", "quick"); // string
const settings = reflag.getFlag("assistant-settings", { model: "quick" }); // { model: string }
```

If the flag is missing or has a different JSON type, such as a string instead of a number, the SDK returns your default. Without a default, it expects a Boolean and falls back to `false`. Pass `null` to allow any JSON value, then check its type before using it.

The SDK doesn't check object fields or fill in missing fields from your default.

`getFlags()` returns an object mapping flag keys to values.

## Checks and delivery
Each read records a check, which Reflag uses for launch monitoring.

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.
## Track usage and feedback

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.
```ts
await reflag.track("Started huddle", { button: "cta" });
reflag.requestFeedback({ flagKey: "huddles", title: "How did it go?" });
await reflag.feedback({ flagKey: "huddles", score: 5 });
```

`requestFeedback()` opens the feedback form. `feedback()` sends feedback you collected yourself.

`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.
Configure your flag's adoption rules to match the event names you send. See [FEEDBACK.md](./FEEDBACK.md) to configure feedback prompts and the feedback UI.

## Context, refresh and cache
## Update context

```ts
await reflag.updateUser({ role: "admin" });
await reflag.updateCompany({ plan: "enterprise" });
await reflag.updateOtherContext({ region: "eu" });

// Replace the whole context, for example after the user switches company:
await reflag.setContext({
user: { id: "bob" },
company: { id: "other-company" },
});
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.
The update methods merge into their section of the context, while `setContext()` replaces all of it. User and company sections need an `id`. Flag values are refetched for the new context.

Constructor options include:
## Bootstrap from the server

| 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 |
To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK** and pass the result to the browser:

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.

## Overrides and toolbar
```ts
// On the server
const bootstrappedState = serverClient.getFlagsForBootstrap(context);
```

```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
// In the browser
const reflag = new ReflagClient({ publishableKey, bootstrappedState });
await reflag.initialize();
```

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.
Pass the whole object returned by `getFlagsForBootstrap()`, 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.

## Server bootstrap
Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, leave `enableLiveFlagUpdates` off (the default).

Generate the full payload with **Node SDK v2** on your server:
## Let users opt in to flags

```ts
const bootstrappedState = serverClient.getFlagsForBootstrap(context);
// Send via your framework's safe JSON/hydration mechanism.
const optInFlags = reflag.getOptInFlags();
await reflag.setOptIn("huddles", { optedIn: true });
await reflag.setOptIn("huddles", { optedIn: false, scope: "company" });
```

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. Use `getIsLoadingOptInFlags()` and the `optInFlagsLoadingUpdated` event to show a loading state.

## Overrides and toolbar

Override flags locally while developing or testing:

```ts
const reflag = new ReflagClient({ publishableKey, bootstrappedState });
await reflag.initialize();
const enabled = reflag.getFlag("release");
reflag.setFlagOverride("huddles", true);
reflag.setFlagOverride("assistant-settings", { model: "local" });
reflag.setFlagOverride("huddles", undefined); // remove the override
```

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.

## End-user opt-in
The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` option to show it elsewhere, for example to internal users in production:

```ts
const options = reflag.getOptInFlags();
const loading = reflag.getIsLoadingOptInFlags();
try {
const response = await reflag.setOptIn("huddles", { optedIn: true });
if (!response?.ok) console.error("Could not update opt-in");
} catch (error) {
console.error("Could not update opt-in", error);
}
const reflag = new ReflagClient({
publishableKey,
toolbar: user.isInternal, // show the toolbar to internal users
});
```

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.
## Events

`on(event, handler)` subscribes to client events and returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated`, `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`.

## Configuration

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.
| Option | Description |
| -------------------------- | --------------------------------------------------------------- |
| `fallbackFlags` | Values to use if flags can't be fetched |
| `enableLiveFlagUpdates` | Update flags when they change in Reflag; default `false` |
| `staleTimeMs` | How long cached flags count as fresh; default `0` |
| `staleWhileRevalidate` | Use stale cached flags while fetching new ones; default `false` |
| `expireTimeMs` | How long cached flags are kept; default 30 days |
| `timeoutMs` | Flag request timeout; default 5,000 ms |
| `enableTracking` | Set to `false` to stop sending checks and usage events |
| `offline` | Make no network requests, for example in tests |
| `toolbar`, `feedback` | Toolbar and feedback UI options |
| `logger` | Custom logger |
| `apiBaseUrl`, `appBaseUrl` | Override the API and app URLs |
| `credentials` | Fetch credentials mode |
| `storage` | Custom async storage for the flag cache |
| `eventSourceFactory` | Custom EventSource implementation for runtimes without one |
| `trackingQueue` | Event batching: `flushDelayMs` and `maxSize` |

## Tracking, feedback and events
## Shut down

Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({ flagKey, ... })` on the client. See [FEEDBACK.md](./FEEDBACK.md) for the feedback UI and prompting configuration.
Call `await reflag.stop()` to send buffered events and close the client, for example when the user signs out.

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

## Migration from v1
If your site uses a strict Content Security Policy, allow:

- 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.
| Directive | Value | Reason |
| ------------- | -------------------------- | ---------------------------------- |
| `connect-src` | `https://front.reflag.com` | API requests and live updates |
| `style-src` | `'unsafe-inline'` | The feedback UI uses inline styles |
Loading
Loading