From f58fb1fd08c16e9f4395dea9b6d1dd1c8014397a Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:37:15 +0000 Subject: [PATCH 1/7] docs(react-sdk): base the v2 README on the v1 guide and update only what changed --- packages/react-sdk/README.md | 979 ++++++++++++++++++++++++++++++++--- 1 file changed, 894 insertions(+), 85 deletions(-) diff --git a/packages/react-sdk/README.md b/packages/react-sdk/README.md index 5af65a44..6c0622e8 100644 --- a/packages/react-sdk/README.md +++ b/packages/react-sdk/README.md @@ -1,166 +1,975 @@ -# Reflag React SDK v2 +# Reflag React SDK -Feature flags for React, built on the [Browser SDK](../browser-sdk/README.md). +React client side library for [Reflag.com](https://reflag.com) -## Setup +Reflag supports flag toggling, tracking flag usage, [requesting feedback](#userequestfeedback) on features, and [multivariate flags](#multivariate-flags) that return strings, numbers or JSON objects. + +The Reflag React SDK comes with a [built-in toolbar](https://docs.reflag.com/supported-languages/browser-sdk#toolbar) which appears on `localhost` by default. + +## Install + +Install via npm: + +```shell +npm i @reflag/react-sdk +``` + +## Get started + +### 1. Add the `ReflagProvider` context provider + +Add the `ReflagProvider` context provider to your application: + +**Example:** ```tsx import { ReflagProvider } from "@reflag/react-sdk"; } > - + {/* children here are shown when loading finishes or immediately if no `loadingComponent` is given */} ; ``` -Provider options forward Browser SDK settings, including `logger`, `debug`, `enableTracking`, `offline`, cache options, `toolbar`, `feedback`, `credentials` and API origins. A custom logger takes precedence over debug logging. Live updates default to true; set `enableLiveFlagUpdates={false}` to disable them. +### 2. Create a new flag and set up type safety + +Install the Reflag CLI: + +```shell +npm i --save-dev @reflag/cli +``` + +Run `npx reflag new` to create your first flag! +On the first run, it will sign into Reflag and set up type generation for your project: + +```shell +❯ npx reflag new +Opened web browser to facilitate login: https://app.reflag.com/api/oauth/cli/authorize + +Welcome to ◪ Reflag! + +? Where should we generate the types? gen/flags.d.ts +? What is the output format? react +✔ Configuration created at reflag.config.json. + +Creating flag for app Slick app. +? New flag name: Huddle +? New flag key: huddle +✔ Created flag Huddle with key huddle (https://app.reflag.com/features/huddles) +✔ Generated react types in gen/flags.d.ts. +``` + +> [!Note] +> By default, types will be generated in `gen/flags.d.ts`. +> The default `tsconfig.json` file `include`s this file by default, but if your `tsconfig.json` is different, make sure the file is covered in the `include` property. + +### 3. Use `useFlag()` to get flag status -## `useFlag(key, defaultValue?)` +Using the `useFlag` hook from your components lets you toggle flags on/off, and `useTrack` lets you track flag usage: + +**Example:** ```tsx import { useFlag, useTrack } from "@reflag/react-sdk"; -function Huddles() { - const enabled = useFlag("huddles"); // true or false - const settings = useFlag("huddle-settings", { maxParticipants: 10 }); +function StartHuddleButton() { + const isEnabled = useFlag("huddle"); // boolean indicating if the flag is enabled + const track = useTrack(); // track usage of the flag + + if (!isEnabled) { + return null; + } + + return ; +} +``` + +`useFlag` can help you do much more. See a full example for `useFlag` [see below](#useflag). + +## Setting context + +Reflag determines which flags are active for a given `user`, `company`, or `other` context. +You can pass these to the `ReflagProvider` using the `context` prop. + +### Using the `context` prop + +```tsx + + + {/* children here are shown when loading finishes */} + + +``` + +### Legacy individual props (deprecated) + +For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: + +```tsx + + + {/* children here are shown when loading finishes */} + + +``` + +> [!Important] +> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. + +### Context requirements + +If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. +In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. +Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. + +Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. +A number of special attributes exist: + +- `name` -- display name for `user`/`company`, +- `email` -- the email of the user, +- `avatar` -- the URL for `user`/`company` avatar image. + +To retrieve a flag's value, use the `useFlag(key: string)` hook (described in a section below). + +Note that each `useFlag()` read automatically generates a `check` event. + +## React Native + +For React Native, use `@reflag/react-native-sdk`, which is a thin wrapper around +`@reflag/react-sdk` and wires up AsyncStorage by default. + +An Expo example app lives at `packages/react-native-sdk/dev/expo`. + +## Multivariate flags + +Multivariate flags are a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Instead of a Boolean, a multivariate flag returns one of several values, which can be strings, numbers or JSON objects. The values are managed from within Reflag, similar to the way access to flags is managed, and different users/companies can get different values. + +### Get started with multivariate flags + +1. Update your flag definitions: + +```typescript +import "@reflag/react-sdk"; + +// Define your flags by extending the `Flags` interface in @reflag/react-sdk +declare module "@reflag/react-sdk" { + interface Flags { + huddle: boolean; + // a multivariate flag whose values are objects + "huddle-settings": { + maxTokens: number; + model: string; + }; + } +} +``` + +2. Read the flag with a default: + +```ts +const settings = useFlag("huddle-settings", { + maxTokens: 1000, + model: "gpt-3.5", +}); + +// settings: { maxTokens: 10000, model: "gpt-3.5-beta1" } +``` + +The default sets the return type. `useFlag()` returns the default while flags load, or if the flag is missing or has a different JSON type, so make sure your default is a value your application can use. Pass `null` as the default to accept 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. + +Without a default, `useFlag()` expects a Boolean and returns `false` if the flag is missing or isn't a Boolean. + +Note that, similar to Boolean flags, each read of a multivariate flag automatically generates a `check` event. + +Remote config from v1 isn't converted automatically. Move each remote config to a multivariate flag; see [Migrating from v1](#migrating-from-v1). + +## Toolbar + +The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. + +Toolbar + +The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the ReflagProvider. + +You can pass a simple boolean to force the toolbar to appear/disappear: + +```ts +` component is a specialized version of `ReflagProvider` designed for server-side rendering, preloaded flag scenarios, and high-reliability setups. It uses pre-fetched evaluated state for the initial render, resulting in faster initial page loads, better SSR compatibility, and a more resilient startup path for React applications. + +```tsx +import { useState, useEffect } from "react"; +import { BootstrappedFlags } from "@reflag/react-sdk"; + +interface BootstrapData { + user: User; + flags: BootstrappedFlags; +} + +function useBootstrap() { + const [data, setData] = useState(null); + + useEffect(() => { + fetch("/bootstrap") + .then((res) => res.json()) + .then(setData); + }, []); + + return data; +} + +// Usage in your app +function App() { + const { user, flags } = useBootstrap(); + + return ( + + + + + + ); +} +``` + +### Server-side endpoint setup + +Create an endpoint that provides bootstrap data to your client application: + +```typescript +// server.js or your Express app +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; + +const reflagClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY, +}); +await reflagClient.initialize(); + +app.get("/bootstrap", (req, res) => { + const user = getUser(req); // Get user from your auth system + const company = getCompany(req); // Get company from your auth system + + const flags = reflagClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + other: { source: "web" }, + }); + + res.status(200).json({ + user, + flags, + }); +}); +``` + +The `flags` object returned by `getFlagsForBootstrap()` contains the full bootstrapped state package: + +- `protocolVersion`: the bootstrap format version +- `context`: the evaluation context used on the server +- `flags`: the evaluated raw flags +- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping + +`getFlagsForBootstrap()` only includes flags that are marked as not secret (`secret: false`). Secret flags can still be read on the server. Because the browser can read the bootstrapped context, include only browser-safe attributes in it. + +Use `@reflag/node-sdk` v2 to produce the bootstrap data. The React SDK v2 doesn't accept bootstrap data from Node SDK v1. + +### Next.js Page Router SSR example + +For Next.js applications using server-side rendering, you can pre-fetch flags in `getServerSideProps`: + +```typescript +// pages/index.tsx +import { GetServerSideProps } from "next"; +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; +import { ReflagBootstrappedProvider, BootstrappedFlags, useFlag, useTrack } from "@reflag/react-sdk"; + +interface PageProps { + bootstrapData: BootstrappedFlags; +} + +export const getServerSideProps: GetServerSideProps = async (context) => { + const serverClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY + }); + await serverClient.initialize(); + + const user = await getUserFromSession(context.req); + const company = await getCompanyFromUser(user); + + const bootstrapData = serverClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + other: { page: "homepage" } + }); + + return { props: { bootstrapData } }; +}; + +export default function HomePage({ bootstrapData }: PageProps) { + return ( + + + + ); +} + +function HuddleFeature() { + const isEnabled = useFlag("huddle"); + const settings = useFlag("huddle-settings", { + maxParticipants: 10, + videoQuality: "standard", + }); const track = useTrack(); - if (!enabled) return null; + + if (!isEnabled) return null; + return ( - +
+

Start a Huddle

+

Max participants: {settings.maxParticipants}

+

Video quality: {settings.videoQuality}

+ +
); } ``` -Pass a default to read other values. The default sets the return type: +This approach eliminates loading states and removes the initial render's dependency on the flags API. -```ts -useFlag("model", "quick"); // string -useFlag("limit", 10); // number -useFlag("settings", { model: "quick" }); // { model: string } -useFlag("anything", null); // any JSON value +### Next.js App Router example + +For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components: + +```typescript +// app/layout.tsx (Server Component) +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; +import { ClientProviders } from "./providers"; + +async function getBootstrapData() { + const serverClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY! + }); + await serverClient.initialize(); + + // In a real app, you'd get user/company from your auth system + const bootstrapData = serverClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + other: { source: "web" } + }); + + return bootstrapData; +} + +export default async function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + const bootstrapData = await getBootstrapData(); + + return ( + + + + {children} + + + + ); +} ``` -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. +```typescript +// app/providers.tsx (Client Component) +"use client"; -The SDK doesn't check object fields or fill in missing fields from your default. +import { ReflagBootstrappedProvider, BootstrappedFlags } from "@reflag/react-sdk"; -`useFlag()` never suspends. To wait for flags with Suspense, use `useFlagSuspense()`. For a loading UI, use `useIsLoading()` or the provider's `loadingComponent`. +interface ClientProvidersProps { + children: React.ReactNode; + bootstrapData: BootstrappedFlags; +} -## `useFlagSuspense(key, defaultValue?)` +export function ClientProviders({ children, bootstrapData }: ClientProvidersProps) { + return ( + + {children} + + ); +} +``` -```tsx -import { Suspense } from "react"; -import { useFlagSuspense } from "@reflag/react-sdk"; +```typescript +// app/page.tsx (Server Component) +import { HuddleFeature } from "./huddle-feature"; -function Model() { - const model = useFlagSuspense("model", "quick"); - return {model}; +export default function HomePage() { + return ( +
+

My App

+ +
+ ); } +``` + +```typescript +// app/huddle-feature.tsx (Client Component) +"use client"; + +import { useFlag, useTrack } from "@reflag/react-sdk"; -Loading flags…}> - -; +export function HuddleFeature() { + const isEnabled = useFlag("huddle"); + const settings = useFlag("huddle-settings", { + maxParticipants: 10, + videoQuality: "standard", + }); + const track = useTrack(); + + if (!isEnabled) return null; + + return ( +
+

Start a Huddle

+

Max participants: {settings.maxParticipants}

+

Video quality: {settings.videoQuality}

+ +
+ ); +} ``` -It takes the same arguments as `useFlag()` and suspends until flags have loaded. If a flag is missing once they have, it returns the default. +This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed. -The provider's `suspense` prop applies only to `useOptInFlags()`. +## `` component -## Checks and usage tracking +The `` is a lower-level component that accepts a `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. -Each read records a check. Reflag uses checks for exposure counts, and they show up in the Event Log, which helps with debugging. +In most cases you should initialize the client before rendering this provider. If you pass an idle client, a `useFlagSuspense()` call can initialize the client on demand; otherwise, you must initialize the client yourself. -Track usage and collect feedback with separate hooks: +### Usage -```ts -const track = useTrack(); -await track("Started huddle", { button: "cta" }); -const requestFeedback = useRequestFeedback(); -requestFeedback({ flagKey: "huddles", title: "How did it go?" }); -const sendFeedback = useSendFeedback(); -await sendFeedback({ flagKey: "huddles", score: 5 }); +```tsx +import { ReflagClient } from "@reflag/browser-sdk"; +import { ReflagClientProvider } from "@reflag/react-sdk"; + +// Initialize the client yourself +const client = new ReflagClient({ + publishableKey: "your-publishable-key", + user: { id: "user123", name: "John Doe" }, + company: { id: "company456", name: "Acme Inc" }, + // ... other configuration options +}); + +// Initialize the client +await client.initialize(); + +function App() { + return ( + }> + + + ); +} ``` -See [Browser feedback documentation](../browser-sdk/FEEDBACK.md) for UI/prompt configuration. +### Props -## Optional key registration +The `ReflagClientProvider` accepts the following props: -```ts -import "@reflag/react-sdk"; -declare module "@reflag/react-sdk" { - interface Flags { - huddles: boolean; - "huddle-settings": { maxParticipants: number }; +- `client`: A `ReflagClient` instance. Prefer passing an already-initialized client; idle clients are initialized on demand only by `useFlagSuspense()` calls. +- `loadingComponent`: Optional React component to show while the client is initializing (same as `ReflagProvider`) +- `suspense`: Optional. Set to `true` to make `useOptInFlags()` suspend while opt-in metadata is loading. To suspend flag reads, use `useFlagSuspense()`. + +> [!Note] +> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. + +## `` component + +The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: + +- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, +- `context` (recommended): An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. +- `company`, `user` and `other` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. + > [!Note] + > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, +- `timeoutMs`: Timeout in milliseconds when fetching flags from the server. +- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background. +- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds). +- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. +- `offline`: Provide this option when testing or in local development environments to avoid contacting Reflag servers. +- `loadingComponent` lets you specify an React component to be rendered instead of the children while the Reflag provider is initializing. If you want more control over loading screens, `useIsLoading()` returns `isLoading` which you can use to customize the loading experience. +- `suspense`: Set to `true` to make `useOptInFlags()` suspend while required opt-in metadata is loading. Flag reads with `useFlag()` never suspend; use `useFlagSuspense()` to suspend them. Wrap components that suspend in React `` boundaries and omit `loadingComponent` if you want Suspense fallbacks to control loading UI. +- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), +- `enableLiveFlagUpdates`: Enables live flag updates over SSE. Defaults to `true` in the React SDK. +- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, +- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. +- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, + +- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, +- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, +- `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar, +- `feedback`: Optional configuration for feedback collection + +## `` component + +The `` is a specialized version of the `ReflagProvider` that uses pre-fetched flag data for the initial render. This is ideal for server-side rendering scenarios. + +The component accepts the following props: + +- `flags`: Pre-fetched bootstrapped state of type `BootstrappedFlags` obtained from the Node SDK's `getFlagsForBootstrap()` method. This contains the context (`flags.context`), the evaluated flags (`flags.flags`), and an optional `flags.flagStateVersion`. +- All other props available in [`ReflagProvider`](#reflagprovider-component) are supported except `context`, `user`, `company`, and `other` (which are extracted from `flags.context`). + +**Example:** + +```tsx +import { + ReflagBootstrappedProvider, + BootstrappedFlags, +} from "@reflag/react-sdk"; + +interface AppProps { + bootstrapData: BootstrappedFlags; +} + +function App({ bootstrapData }: AppProps) { + return ( + } + debug={process.env.NODE_ENV === "development"} + > + + + ); +} +``` + +> [!Note] +> When using `ReflagBootstrappedProvider`, pass the entire object returned by `getFlagsForBootstrap()` directly as the `flags` prop. The context is extracted from `flags.context`, and `flags.flagStateVersion` is used when present. +> +> With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It returns `isLoading: true` (or suspends) until that refresh settles. +> +> Use `@reflag/node-sdk` v2 to produce the bootstrap data. It only includes flags marked as not secret (`secret: false`). +> +> After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. +> +> Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. + +## Hooks + +### `useFlag()` + +Returns the value of a given flag for the current context. The hook provides type-safe access to flags and their values. + +```tsx +import { + useFlag, + useIsLoading, + useRequestFeedback, + useTrack, +} from "@reflag/react-sdk"; +import { Loading } from "./Loading"; + +function StartHuddleButton() { + const isLoading = useIsLoading(); // true while flags are being loaded + const isEnabled = useFlag("huddle"); // boolean indicating if the flag is enabled + const settings = useFlag("huddle-settings", { + question: "How do you like the Huddles feature?", + }); // value of a multivariate flag, or the default + const track = useTrack(); // function to track flag usage + const requestFeedback = useRequestFeedback(); // function to request feedback + + if (isLoading) { + return ; + } + + if (!isEnabled) { + return null; } + + return ( + <> + + + + ); } ``` -Registered flags get autocompletion for their keys and type checks for the defaults you pass, in both `useFlag()` and `useFlagSuspense()`. The checks happen at compile time only. To generate the declarations, run `npx reflag flags types` with the `react` format. +Without a default, `useFlag(key)` returns a Boolean, using `false` while flags load or if the flag is missing. Pass a default to read a [multivariate flag](#multivariate-flags), such as `useFlag("model", "quick")`; the default sets the return type. -## Bootstrap and SSR +#### Suspense loading -Get the bootstrap data from the Node.js SDK on your server: +`useFlag()` never suspends. Use `useFlagSuspense()` to suspend until flags are ready. It takes the same arguments as `useFlag()`, and the nearest `` boundary will render its fallback until flags are ready. If a flag is missing once they have loaded, it returns the default. -```ts -const flags = serverClient.getFlagsForBootstrap(context); +```tsx +import { Suspense } from "react"; +import { ReflagProvider, useFlagSuspense } from "@reflag/react-sdk"; + +function Huddles() { + const isEnabled = useFlagSuspense("huddle"); + return isEnabled ? : null; +} + + + }> + + +; +``` + +The provider's `suspense` prop doesn't affect `useFlag()` or `useFlagSuspense()`; it only applies to `useOptInFlags()`. + +### `useOptInFlags()` + +Use this hook to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. It returns the opt-in flags, their loading state and a `setOptIn` function. + +```tsx +import { type OptInFlag, useIsLoading, useOptInFlags } from "@reflag/react-sdk"; + +function OptInList() { + const isProviderLoading = useIsLoading(); + const { flags, isLoading, setOptIn } = useOptInFlags(); + + async function toggleOptIn(flag: OptInFlag) { + try { + const response = await setOptIn(flag.key, { + optedIn: !flag.userOptedIn, + }); + if (!response?.ok) { + console.error("Could not update opt-in"); + } + } catch (error) { + console.error("Could not update opt-in", error); + } + } + + if (isProviderLoading || isLoading) { + return

Loading…

; + } + + return flags.map((flag) => ( + + )); +} ``` -Pass the whole object to `ReflagBootstrappedProvider`: +Each entry includes the flag's `key`, `name`, `description`, a Boolean `value` that says whether the flag is on, and whether the user (`userOptedIn`) or company (`companyOptedIn`) has opted in. + +By default, `setOptIn` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. + +User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. + +`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. React may not have committed the resulting render yet. + +The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. + +`useOptInFlags()` returns `{ flags, isLoading, setOptIn }`. The separate `useSetOptIn()` hook still works but is deprecated. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. + +If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. + +With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` hook or the provider's `loadingComponent` for that initial loading state. + +`useOptInFlags()` also supports Suspense. It respects the provider-level `suspense` option, or you can enable it for only this hook with `useOptInFlags({ suspense: true })`. While required opt-in metadata is loading, the nearest `` boundary renders its fallback: ```tsx -import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; +import { Suspense } from "react"; - - + + }> + + ; ``` -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. +Opt-in metadata Suspense is primarily relevant with `ReflagBootstrappedProvider`. Use `useOptInFlags({ suspense: false })` to opt out for one call when Suspense is enabled on the provider. + +### `useTrack()` -To use a client you create yourself, pass it to `ReflagClientProvider`. Your app is then responsible for initializing and stopping it. +`useTrack()` lets you send custom events to Reflag. Use this whenever a user _uses_ a feature. These events can be used to analyze feature usage in Reflag. -## Context, loading and events +```tsx +import { useTrack } from "@reflag/react-sdk"; + +function StartHuddle() { + const track = useTrack(); +
+ +
; +} +``` + +### `useRequestFeedback()` -- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. `useClient().setContext(context)` replaces the whole context. -- While flags for a new context load, reads return their defaults. -- `useIsLoading()` returns provider loading state. Use `loadingComponent` or `initialLoading` to control what renders while flags load. -- `useClient()` returns the underlying Browser client. -- `useOnEvent(type, handler, client?)` subscribes and unsubscribes on unmount. A supplied external client works without a provider. +`useRequestFeedback()` returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. -## Opt-in hooks +When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. +The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. ```tsx -const { flags, isLoading, setOptIn } = useOptInFlags(); -try { - const response = await setOptIn("huddles", { optedIn: true }); - if (!response?.ok) console.error("Could not update opt-in"); -} catch (error) { - console.error("Could not update opt-in", error); +import { useRequestFeedback } from "@reflag/react-sdk"; + +function FeedbackButton() { + const requestFeedback = useRequestFeedback(); + return ( + + ); } ``` -Each entry includes the flag's `key`, `name`, `description`, a Boolean `value`, 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 `useClient().refresh()` to retry. +See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. + +### `useSendFeedback()` + +Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. + +```tsx +import { useSendFeedback } from "@reflag/react-sdk"; + +function CustomFeedbackForm() { + const sendFeedback = useSendFeedback(); + + const handleSubmit = async (data: FormData) => { + await sendFeedback({ + flagKey: "reflag-flag-key", + score: parseInt(data.get("score") as string), + comment: data.get("comment") as string, + }); + }; + + return
...
; +} +``` + +### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` + +These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. + +```tsx +import { + useUpdateUser, + useUpdateCompany, + useUpdateOtherContext, +} from "@reflag/react-sdk"; + +function FlagOptIn() { + const updateUser = useUpdateUser(); + const updateCompany = useUpdateCompany(); + const updateOtherContext = useUpdateOtherContext(); + + const handleUserUpdate = async () => { + await updateUser({ + role: "admin", + betaFlags: "enabled", + }); + }; + + const handleCompanyUpdate = async () => { + await updateCompany({ + plan: "enterprise", + employees: 500, + }); + }; + + const handleContextUpdate = async () => { + await updateOtherContext({ + currentWorkspace: "workspace-123", + theme: "dark", + }); + }; + + return ( +
+ + + +
+ ); +} +``` -Pass `{ suspense: true }` to `useOptInFlags()` to suspend until the list loads. It defaults to the provider's `suspense` prop. +### `useClient()` + +Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that +is not directly accessible thorough the other hooks. + +```tsx +import { useClient } from "@reflag/react-sdk"; + +function LoggingWrapper({ children }: { children: ReactNode }) { + const client = useClient(); + + console.log(client.getContext()); + + return children; +} +``` + +### `useIsLoading()` + +Returns the loading state of the flags in the `ReflagClient`. +Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. + +```tsx +import { useIsLoading } from "@reflag/react-sdk"; +import { Spinner } from "./Spinner"; + +function LoadingWrapper({ children }: { children: ReactNode }) { + const isLoading = useIsLoading(); + + if (isLoading) { + return ; + } + + return children; +} +``` + +### `useOnEvent()` + +Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. + +```tsx +import { useOnEvent } from "@reflag/react-sdk"; + +function LoggingWrapper({ children }: { children: ReactNode }) { + useOnEvent("flagsUpdated", (newFlags) => { + console.log(newFlags); + }); + + return children; +} +``` + +To listen to a client outside a provider, pass it as the third argument: `useOnEvent("flagsUpdated", handler, client)`. ## Migrating from v1 -- `useFlag()` returns the flag's value: replace `const { isEnabled } = useFlag(key)` with `const enabled = useFlag(key)`. +- `useFlag()` returns the flag's value: replace `const { isEnabled } = useFlag(key)` with `const isEnabled = useFlag(key)`. - Move remote config to a multivariate flag and read it with a default, such as `useFlag("model", "quick")`. Existing remote config isn't converted automatically. - Use `useTrack()` and `useRequestFeedback()` instead of the flag's `track()` and `requestFeedback()`. -- Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and the flag's loading property with `useIsLoading()`. +- Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and the flag's `isLoading` property with `useIsLoading()`. The provider's `suspense` prop now only applies to `useOptInFlags()`. - `useFeature()` is removed. Use `useFlag()` instead. - Use the `setOptIn` function returned by `useOptInFlags()`. `useSetOptIn()` still works but is deprecated. - Opt-in entries have a Boolean `value` instead of `isEnabled`. -- Remove `fallbackFlags` and pass a default to each read instead, such as `useFlag("huddles", true)`. -- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time. +- Remove `fallbackFlags` and pass a default to each read instead, such as `useFlag("huddle", true)`. +- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time, and mark the flags the browser needs as not secret. - If you generate type declarations, regenerate them with the v2 CLI. See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps. + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- When using strongly-typed flags, the new `Flags` interface replaced `Features` interface +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- The `fallbackFeatures` property has been removed; pass a default to each `useFlag()` read instead +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The SDKs will not emit `evaluate` and `evaluate-config` events anymore +- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead of `bucket-*` +- The `featuresUpdated` hook has been renamed to `flagsUpdated` +- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on + +To ease in transition to Reflag SDK, the `featuresUpdated` hook has been preserved as an alias for `flagsUpdated`. The `getFeature`, `getFeatures` and `useFeature` aliases have been removed; use `getFlag`, `getFlags` and `useFlag` instead. + +If you are running with strict Content Security Policies active on your website, you will need change them as follows: + +- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` + +## Content Security Policy (CSP) + +See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP + +## License + +MIT License + +Copyright (c) 2025 Bucket ApS From 4602f96d9a409a061c9f6b5a673733c105f30973 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:49:29 +0000 Subject: [PATCH 2/7] docs: base the Browser, Vue, Node and React Native v2 READMEs on their v1 guides --- packages/browser-sdk/README.md | 615 ++++++++++++-- packages/node-sdk/README.md | 1171 +++++++++++++++++++++++---- packages/react-native-sdk/README.md | 213 ++--- packages/vue-sdk/README.md | 731 +++++++++++++++-- 4 files changed, 2295 insertions(+), 435 deletions(-) diff --git a/packages/browser-sdk/README.md b/packages/browser-sdk/README.md index 49b32ab2..4b607de3 100644 --- a/packages/browser-sdk/README.md +++ b/packages/browser-sdk/README.md @@ -1,145 +1,580 @@ -# Reflag Browser SDK v2 +# Reflag Browser SDK -Client-side feature flags for [Reflag](https://reflag.com). +Basic client for [Reflag.com](https://reflag.com). If you're using React, you'll be better off with the Reflag React SDK. -## Get started +Reflag supports flag toggling, tracking flag usage, [collecting feedback](#qualitative-feedback-on-beta-flags) on flags, and [multivariate flags](#multivariate-flags) that return strings, numbers or JSON objects. -```ts +## Install + +First find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. + +The package can be imported or used directly in a HTML script tag: + +A. Import module: + +```typescript import { ReflagClient } from "@reflag/browser-sdk"; -const reflag = new ReflagClient({ - publishableKey: "your-publishable-key", - user: { id: "alice", role: "manager" }, - company: { id: "acme", plan: "enterprise" }, +const user = { + id: 42, + role: "manager", +}; + +const company = { + id: 99, + plan: "enterprise", +}; + +const reflagClient = new ReflagClient({ publishableKey, user, company }); + +await reflagClient.initialize(); + +// `getFlag` returns `true` or `false`. Reading a flag automatically +// sends a "check" event for the "huddle" flag which is shown in the +// Reflag UI. +const isEnabled = reflagClient.getFlag("huddle"); + +if (isEnabled) { + // On usage, call `track` to let Reflag know that a user interacted with the flag. + // By default Reflag expects event names to align with the flag keys. + reflagClient.track("huddle"); + + // A multivariate flag returns a value that is configured in Reflag and + // dynamically picked out depending on the user/company. The default is + // used while flags load, or if the flag is missing or has a different type. + const { question } = reflagClient.getFlag("huddle-feedback", { + question: "Tell us what you think of Huddles", + }); + + // Use `requestFeedback` to create "Send feedback" buttons easily for specific + // flags. This is not related to `track` and you can call them individually. + reflagClient.requestFeedback({ flagKey: "huddle", title: question }); +} +``` + +B. Script tag (client-side directly in html) + +See [example/browser.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/browser.html) for a working example: + +```html + + +Loading... + +``` + +### Init options + +Supply these to the constructor call: + +```typescript +type Configuration = { + logger: console; // by default only logs warn/error, by passing `console` you'll log everything + apiBaseUrl?: "https://front.reflag.com"; + credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport + feedback?: undefined; // See FEEDBACK.md + enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user + enableLiveFlagUpdates?: false; // Set to `true` to keep flags up to date over SSE (browser SDK default: false) + eventSourceFactory?: (url: string) => { + // Advanced: provide a custom EventSource-compatible transport + addEventListener: (type: string, cb: (event: any) => void) => void; + close: () => void; + }; + timeoutMs?: number; // Timeout for fetching flags (default: 5000ms) + staleWhileRevalidate?: boolean; // Revalidate in the background when cached flags turn stale to avoid latency in the UI (default: false) + staleTimeMs?: number; // at initialization time flags are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase this in the case of a non-SPA + expireTimeMs?: number; // In case we're unable to fetch flags from Reflag, cached/stale flags will be used instead until they expire after `expireTimeMs`. Default is 30 days + offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development +}; +``` + +## Migrating 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. Use `getFlagResults()` to inspect flags without recording checks. Replace `getFeatures()` and `getFeature(key)` with `getFlags()` and `getFlag(key)`; the feature-named methods are removed. +- Opt-in entries from `getOptInFlags()` have a Boolean `value` instead of `isEnabled`. +- Remove `fallbackFlags` and pass a default to each read instead, such as `getFlag("huddle", true)`. +- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time, and mark the flags the browser needs as not secret. Replace `bootstrappedFlags` with `bootstrappedState`. +- If you generate type declarations, regenerate them with the v2 CLI. + +See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps. + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- The `fallbackFeatures` property has been removed; pass a default to each `getFlag()` read instead +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` +- The `featuresUpdated` hook has been renamed to `flagsUpdated` +- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on + +To ease in transition to Reflag SDK, the `featuresUpdated` hook has been preserved as an alias for `flagsUpdated`. The `getFeature` and `getFeatures` aliases have been removed; use `getFlag` and `getFlags` instead. + +If you are running with strict Content Security Policies active on your website, you will need change them as follows: + +- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` + +Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` + +## Flag toggles + +Reflag determines which flags are active for a given user/company. The user/company is given in the ReflagClient constructor. + +If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. +In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. + +Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. +Some attributes are special and used in Reflag UI: + +- `name` -- display name for `user`/`company`, +- `email` -- is accepted for `user`s and will be highlighted in the Reflag UI if available, +- `avatar` -- can be provided for both `user` and `company` and should be an URL to an image. + +```ts +const reflagClient = new ReflagClient({ + publishableKey, + user: { + id: "user_123", + name: "John Doe", + email: "john@acme.com" + avatar: "https://example.com/images/udsy6363" + }, + company: { + id: "company_123", + name: "Acme, Inc", + avatar: "https://example.com/images/31232ds" + }, }); -await reflag.initialize(); +``` -const enabled = reflag.getFlag("huddles"); // boolean, implicit false -const settings = reflag.getFlag("assistant-settings", { model: "quick" }); -// settings: { model: string } +To retrieve a flag's value, use `getFlag(key: string)`: + +```ts +const huddle = reflagClient.getFlag("huddle"); +// true +``` + +Without a default, `getFlag()` expects a Boolean and returns `false` if the flag is missing or isn't a Boolean. To read a [multivariate flag](#multivariate-flags), pass a default as the second argument. + +You can use `getFlags()` to retrieve the values of all flags currently. + +```ts +const flags = reflagClient.getFlags(); +// { +// huddle: true, +// "huddle-settings": { maxParticipants: 10 } +// } +``` -if (enabled) { - // Application usage tracking is separate from reading the flag. - await reflag.track("Started huddle"); +`getFlags()` is meant to be more low-level than `getFlag()` and it typically used +by down-stream clients. + +Note that each `getFlag()` read automatically generates a `check` event, and `getFlags()` generates a `check` event for every flag it returns. To inspect the evaluated flags without generating `check` events, for example for debugging, use `getFlagResults()`. + +## End-user opt-in + +If a flag has end-user opt-in enabled in Reflag, you can list the opt-in options for the current context and set or cancel opt-in for the current user or company. + +```ts +const optInFlags = reflagClient.getOptInFlags(); +// [{ key, name, description, value, userOptedIn, companyOptedIn, isOptedIn }] +// `value` is a Boolean that says whether the flag is on for the current context + +try { + const response = await reflagClient.setOptIn("huddle", { + optedIn: true, // Use false to cancel this scope's opt-in. + scope: "user", // Use "company" to change the current company's opt-in. + }); + if (!response?.ok) { + console.error("Could not update opt-in"); + } +} catch (error) { + console.error("Could not update opt-in", error); } ``` -Use only a **publishable** key in a browser. Secret keys belong on your server. +By default, `setOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. -## Read flags +User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. + +`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and `flagsUpdated` listeners have been notified when flags change. + +The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. + +The `description` comes from the dedicated SDK-facing opt-in description configured in Reflag. + +When using bootstrapped flags, the first `getOptInFlags()` or `getIsLoadingOptInFlags()` call requests a flags refresh. The list call returns the currently available list synchronously, and the loading getter returns `true` until that refresh succeeds or fails. Normal initialization also exposes loading through the client's state. + +Listen for `optInFlagsLoadingUpdated` to update UI when this loading state changes. `flagsUpdated` is emitted when a successful refresh updates the list. + +If fetching opt-in metadata fails, loading ends without exposing an error. Call `reflagClient.refresh()` to retry. + +## Multivariate flags + +Multivariate flags are a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Instead of a Boolean, a multivariate flag returns one of several values, which can be strings, numbers or JSON objects. The values are managed from within Reflag, similar to the way access to flags is managed, and different users/companies can get different values. + +Read a multivariate flag by passing a default. The default sets the return type: ```ts -reflag.getFlag("huddles"); // true or false -reflag.getFlag("model", "quick"); // string -reflag.getFlag("limit", 10); // number -reflag.getFlag("settings", { model: "quick" }); // { model: string } -reflag.getFlag("anything", null); // any JSON value +reflagClient.getFlag("model", "quick"); // string +reflagClient.getFlag("limit", 10); // number +reflagClient.getFlag("assistant", { maxTokens: 1000, model: "gpt-3.5" }); +// { maxTokens: 10000, model: "gpt-3.5-beta1" } +reflagClient.getFlag("anything", null); // any JSON value +``` + +`getFlag()` returns the default while flags load, or if the flag is missing or has a different JSON type, so make sure your default is a value your application can use. Pass `null` to accept 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. + +Just as Boolean flags, each `getFlag()` read of a multivariate flag automatically generates a `check` event. + +Remote config from v1 isn't converted automatically. Move each remote config to a multivariate flag; see [Migrating from v1](#migrating-from-v1). + +## Server-side rendering and bootstrapping + +For server-side rendered applications, you can render immediately with pre-fetched flag data by bootstrapping the client. + +### Init options bootstrapped + +```typescript +type Configuration = { + logger: console; // by default only logs warn/error, by passing `console` you'll log everything + apiBaseUrl?: "https://front.reflag.com"; + credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport + feedback?: undefined; // See FEEDBACK.md + enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user + offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development + bootstrappedState?: { + protocolVersion: 2; + context: ReflagContext; + flags: RawFlags; + flagStateVersion?: number; + }; // Pre-fetched evaluated state from server-side (see Server-side rendering section) +}; +``` + +### Using `bootstrappedState` + +Use the Node SDK's `getFlagsForBootstrap()` method to pre-fetch evaluated state server-side, then pass the returned object directly to the browser client: + +```typescript +// Server-side: Get bootstrapped state using Node SDK +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; + +const serverClient = new ReflagNodeClient({ secretKey: "your-secret-key" }); +await serverClient.initialize(); + +const bootstrappedState = serverClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, +}); + +// Pass the bootstrapped state to the client using your framework's preferred method +app.get("/", (req, res) => { + res.set("Content-Type", "text/html"); + res.send( + Buffer.from( + ` +
`, + ), + ); +}); + +// Client-side: Initialize with pre-fetched evaluated state +import { ReflagClient } from "@reflag/browser-sdk"; + +const reflagClient = new ReflagClient({ + publishableKey: "your-publishable-key", + bootstrappedState, // Contains context, flags, and optional flagStateVersion +}); + +await reflagClient.initialize(); +const isEnabled = reflagClient.getFlag("huddle"); +``` + +The `bootstrappedState` object contains: + +- `protocolVersion`: the bootstrap format version +- `context`: the evaluation context used on the server +- `flags`: the evaluated raw flags +- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping + +`getFlagsForBootstrap()` only includes flags that are marked as not secret (`secret: false`). Secret flags can still be read on the server. Because the browser can read the bootstrapped context, include only browser-safe attributes in it. + +Use `@reflag/node-sdk` v2 to produce the bootstrap data. The Browser SDK v2 doesn't accept bootstrap data from Node SDK v1. + +If a bootstrapped application requests opt-in flags, the browser SDK performs one flags refresh. Applications that do not request opt-in data do not make this request. + +The `bootstrappedFlags` option has been removed. If you previously used it, migrate like this: + +```typescript +// Before +const { flags } = serverClient.getFlagsForBootstrap(context); +const client = new ReflagClient({ + publishableKey, + user: context.user, + company: context.company, + other: context.other, + bootstrappedFlags: flags, +}); + +// After +const bootstrappedState = serverClient.getFlagsForBootstrap(context); +const client = new ReflagClient({ + publishableKey, + bootstrappedState, +}); ``` -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. +> [!NOTE] +> After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. +> +> Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -The SDK doesn't check object fields or fill in missing fields from your default. +This eliminates loading states and removes the initial render's dependency on the flags API. -`getFlags()` returns all flag values as an object. +## Context management -## Checks +### Updating user/company/other context -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. +Attributes given for the user/company/other context in the ReflagClient constructor can be updated for use in flag targeting evaluation with the `updateUser()`, `updateCompany()` and `updateOtherContext()` methods. +They return a promise which resolves once the flags have been re-evaluated follow the update of the attributes. -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. +> [!NOTE] > `user`/`company` attributes are also stored remotely on the Reflag servers and will automatically be used to evaluate flag targeting if the page is refreshed. -## Context, refresh and cache +### setContext() + +The `setContext()` method allows you to replace the entire context (user, company, and other attributes) at once. This method is useful when you need to completely change the context, such as when a user logs in or switches between different accounts. ```ts -await reflag.updateUser({ role: "admin" }); -await reflag.updateCompany({ plan: "enterprise" }); -await reflag.updateOtherContext({ region: "eu" }); -await reflag.setContext({ - user: { id: "bob" }, - company: { id: "other-company" }, +await reflagClient.setContext({ + user: { + id: "new-user-123", + name: "Jane Doe", + email: "jane@example.com", + role: "admin", + }, + company: { + id: "company-456", + name: "New Company Inc", + plan: "enterprise", + }, + other: { + feature: "beta", + locale: "en-US", + }, +}); +``` + +The method will: + +- Replace the entire context with the new values +- Re-evaluate all flags based on the new context +- Update the user and company information on Reflag servers +- Return a promise that resolves once the flags have been re-evaluated + +### getContext() + +The `getContext()` method returns the current context being used for flag evaluation. This is useful for debugging or when you need to inspect the current user, company, and other attributes. + +```ts +const currentContext = reflagClient.getContext(); +console.log(currentContext); +// { +// user: { id: "user-123", name: "John Doe", email: "john@example.com" }, +// company: { id: "company-456", name: "Acme Inc", plan: "enterprise" }, +// other: { locale: "en-US", feature: "beta" } +// } +``` + +The returned context object contains: + +- `user`: Current user attributes (if any) +- `company`: Current company attributes (if any) +- `other`: Additional context attributes not related to user or company + +## Toolbar + +The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. + +Toolbar screenshot + +The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. +You have full control over when it appears through the `toolbar` configuration option passed to the `ReflagClient`. + +You can pass a simple boolean to force the toolbar to appear/disappear: + +```typescript +const client = new ReflagClient({ + // show the toolbar even in production if the user is an internal/admin user + toolbar: user?.isInternal, + ... }); -await reflag.refresh(); ``` -`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. +You can also configure the position of the toolbar on the screen: + +```typescript +const client = new ReflagClient({ + toolbar: { + show: true; + position: { + placement: "bottom-left", + offset: {x: "1rem", y: "1rem"} + } + } + ... +}) +``` + +See [the reference](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for details. + +## Qualitative feedback on beta flags + +Reflag can collect qualitative feedback from your users in the form of a [Customer Satisfaction Score](https://en.wikipedia.org/wiki/Customer_satisfaction) and a comment. + +### Automated feedback collection + +The Reflag Browser SDK comes with automated feedback collection mode enabled by default, which lets the Reflag service ask your users for feedback for relevant flags just after they've used them. -Constructor options include: +> [!NOTE] +> To get started with automatic feedback collection, make sure you've set `user` in the `ReflagClient` constructor. -| 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 | +Automated feedback surveys work even if you're not using the SDK to send events to Reflag. +It works because the Reflag Browser SDK maintains a live connection to Reflag's servers and can automatically show a feedback prompt whenever the Reflag servers determines that an event should trigger a prompt - regardless of how this event is sent to Reflag. -Flags are cached in the browser. If a refresh fails, the client keeps the last values it received. +You can find all the options to make changes to the default behavior in the [Reflag feedback documentation](./FEEDBACK.md). -## Overrides and toolbar +### Reflag feedback UI + +Reflag can assist you with collecting your user's feedback by offering a pre-built UI, allowing you to get started with minimal code and effort. + +[Read the Reflag feedback UI documentation](./FEEDBACK.md) + +### Reflag feedback SDK + +Feedback can be submitted to Reflag using the SDK: ```ts -reflag.setFlagOverride("release", true); -reflag.setFlagOverride("settings", { model: "local" }); -reflag.setFlagOverride("nullable-settings", null); // override with null -reflag.setFlagOverride("release", undefined); // remove the override +reflagClient.feedback({ + flagKey: "my-flag-key", // String (required), copy from Flag feedback tab + score: 5, // Number: 1-5 (optional) + comment: "Absolutely stellar work!", // String (optional) +}); ``` -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. +### Reflag feedback API -## Server bootstrap +If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API. -Get the bootstrap data from the Node.js SDK on your server: +See details in [Feedback HTTP API](https://docs.reflag.com/api/http-api#post-feedback) + +## Tracking flag usage + +The `track` function lets you send events to Reflag to denote flag usage. +By default Reflag expects event names to align with the flag keys, but +you can customize it as you wish. ```ts -const bootstrappedState = serverClient.getFlagsForBootstrap(context); -// Serialize this into the page with your framework's usual mechanism. +reflagClient.track("huddle", { voiceHuddle: true }); ``` +## Event listeners + +Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are: + +- `check`: Your code read a flag with `getFlag()` or `getFlags()` +- `flagsUpdated`: Flags were updated. Either because they were loaded as part of initialization or because the user/company updated +- `optInFlagsLoadingUpdated`: The opt-in flag loading state changed +- `user`: User information updated (similar to the `identify` call used in tracking terminology) +- `company`: Company information updated (sometimes to the `group` call used in tracking terminology) +- `track`: Track event occurred. + +Use the `on()` method to add an event listener to respond to certain events. See the API reference for details on each hook. + ```ts -const reflag = new ReflagClient({ publishableKey, bootstrappedState }); -await reflag.initialize(); -const enabled = reflag.getFlag("release"); +import { ReflagClient, CheckEvent, RawFlags } from "@reflag/browser-sdk"; + +const client = new ReflagClient({ + // options +}); + +// or add the hooks after construction: +const unsub = client.on("check", (check: CheckEvent) => + console.log(`Check event ${check}`), +); +// use the returned function to unsubscribe, or call `off()` with the same arguments again +unsub(); ``` -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. +## Zero PII -## End-user opt-in +The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. + +For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag: ```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); -} +import reflag from "@reflag/browser-sdk"; +import { sha256 } from "crypto-hash"; + +reflag.user(await sha256("john_doe")); ``` -Each entry includes the flag's `key`, `name`, `description`, a Boolean `value`, 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. +## Use of cookies -## Tracking, feedback and events +The Reflag Browser SDK uses a couple of cookies to support automated feedback surveys. These cookies are not used for tracking purposes and thus should not need to appear in cookie consent forms. -Use `track(eventName, attributes?)`, `feedback(payload)` and `requestFeedback({ flagKey, ... })` on the client. See [FEEDBACK.md](./FEEDBACK.md) for the feedback UI and prompting configuration. +The two cookies are: -`on(event, handler)` returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated`, `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. +- `reflag-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys +- `reflag-token-${userId}`: caching a token used to connect to Reflag's live messaging infrastructure that is used to deliver automated feedback surveys in real time. -## Migrating from v1 +## TypeScript -- `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. Replace `getFeatures()` and `getFeature(key)` with `getFlags()` and `getFlag(key)`; the feature-named methods are removed. -- Opt-in entries from `getOptInFlags()` have a Boolean `value` instead of `isEnabled`. -- 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. +Types are bundled together with the library and exposed automatically when importing through a package manager. -See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps. +## Content Security Policy (CSP) + +If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK: + +| Directive | Values | Reason | +| ----------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| connect-src | [https://front.reflag.com](https://front.reflag.com) | API requests plus Server-Sent Events for live flag updates and automated feedback surveys. | +| style-src | 'unsafe-inline' | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. | + +If you are including the Reflag tracking SDK with a ` - + + + ``` -Provider options forward Browser settings, including cache/storage, offline/tracking, feedback, toolbar, credentials and API origins. `logger` takes precedence over `debug`. Live updates default to true; disable with `:enable-live-flag-updates="false"`. For an ordinary client-only Nuxt provider, wrap it in ``. +If using Nuxt, wrap `` in ``. `` only renders client-side currently. -## `useFlag(key, defaultValue?)` +### 2. Use `useFlag` to get flag status ```vue ``` -`useFlag()` returns a ref. Vue unwraps it in templates; use `.value` in script. +`useFlag()` returns a ref. Vue unwraps it in templates; use `.value` in script. See [useFlag()](#useflag) for a full example + +## Setting context + +Reflag determines which flags are active for a given `user`, `company`, or `other` context. +You can pass these to the `ReflagProvider` using the `context` prop. + +### Using the `context` prop + +```vue + + + +``` + +### Legacy individual props (deprecated) + +For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: + +```vue + + + +``` + +> [!Important] +> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. + +### Context requirements + +If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. +In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. +Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. + +Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. +A number of special attributes exist: + +- `name` -- display name for `user`/`company`, +- `email` -- the email of the user, +- `avatar` -- the URL for `user`/`company` avatar image. + +To retrieve a flag's value, use the `useFlag(key: string)` hook (described in a section below). + +Note that each `useFlag()` read automatically generates a `check` event. + +## Multivariate flags + +Multivariate flags are a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Instead of a Boolean, a multivariate flag returns one of several values, which can be strings, numbers or JSON objects. The values are managed from within Reflag, similar to the way access to flags is managed, and different users/companies can get different values. + +### Get started with multivariate flags + +Read a multivariate flag by passing a default. The default sets the type of the returned ref: ```ts -useFlag("release"); // ShallowRef +const settings = useFlag("huddle-settings", { + maxTokens: 1000, + model: "gpt-3.5", +}); + +// settings.value: { maxTokens: 10000, model: "gpt-3.5-beta1" } + useFlag("model", "quick"); // ShallowRef useFlag("limit", 10); // ShallowRef -useFlag("settings", { model: "quick" }); // ShallowRef<{ model: string }> useFlag("anything", null); // ShallowRef, any JSON value ``` -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. +`useFlag()` returns the default while flags load, or if the flag is missing or has a different JSON type, so make sure your default is a value your application can use. Pass `null` to accept 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. + +Without a default, `useFlag()` expects a Boolean and returns `false` if the flag is missing or isn't a Boolean. + +Note that, similar to Boolean flags, each read of a multivariate flag automatically generates a `check` event. + +Remote config from v1 isn't converted automatically. Move each remote config to a multivariate flag; see [Migrating from v1](#migrating-from-v1). -The SDK doesn't check object fields or fill in missing fields from your default. +## Type safety + +You can register your flags to get autocompletion for their keys and type checks for the defaults you pass: + +```ts +import "@reflag/vue-sdk"; -The ref updates when flag values change. Each read records a check. Reflag uses checks for exposure counts, and they show up in the Event Log, which helps with debugging. +declare module "@reflag/vue-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; + } +} +``` -## Loading, context and client access +The checks happen at compile time only. To generate the declarations, run `npx reflag flags types` with the `vue` format. -- `useIsLoading()` returns a Boolean ref for provider loading; use the `#loading` slot or `initialLoading` to control what renders while flags load. -- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. -- `useClient()` exposes the Browser client, including `setContext(context)`, `refresh()` and `setFlagOverride(key, value)`. Pass `undefined` to remove an override. -- `getFlags()` returns all flag values and records a check for each. -- `useOnEvent(type, handler, client?)` subscribes on mount and unsubscribes on unmount. An external client may be supplied explicitly. +## `` component -While flags for a new context load, reads return their defaults. +The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: -## Bootstrap +- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, +- `context`: An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. +- `company`, `user` and `otherContext` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. -Get the bootstrap data from the Node.js SDK on your server, and serialize it into the page with your framework's usual mechanism: + > [!Note] + > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, -```ts -const flags = serverClient.getFlagsForBootstrap(context); +- `timeoutMs`: Timeout in milliseconds when fetching flags from the server, +- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background, +- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds), +- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. + +- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), +- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, +- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. +- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, + +- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, +- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, +- `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar, +- `feedback`: Optional configuration for feedback collection + +### Loading states + +ReflagProvider lets you define a template to be shown while ReflagProvider is initializing: + +```vue + ``` +If you want more control over loading screens, `useIsLoading()` returns a `Ref` which you can use to customize the loading experience. + +## `` component + +The `` component is a specialized version of `ReflagProvider` designed for server-side rendering and preloaded flag scenarios. It uses pre-fetched flags for the initial render, resulting in faster initial page loads and better SSR compatibility. + +### Usage + ```vue - - - + + + ``` -Pass the whole object to `ReflagBootstrappedProvider`. 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 `:enable-live-flag-updates="false"` if they must not. +### Getting bootstrapped flags -To use a client you create yourself, pass it to `ReflagClientProvider`. Your app is then responsible for initializing and stopping it. +You'll typically generate the `bootstrappedFlags` object on your server using the Node.js SDK. Pass the full object returned by `getFlagsForBootstrap()` directly to ``. It contains: -## Opt-in, tracking and feedback +- `protocolVersion`: the bootstrap format version +- `context`: the evaluation context used on the server +- `flags`: the evaluated raw flags +- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping -```ts -const { flags, isLoading, setOptIn } = useOptInFlags(); // flags and isLoading are refs -try { - const response = await setOptIn("huddles", { optedIn: true }); - if (!response?.ok) console.error("Could not update opt-in"); -} catch (error) { - console.error("Could not update opt-in", error); -} +`getFlagsForBootstrap()` only includes flags that are marked as not secret (`secret: false`). Secret flags can still be read on the server. Because the browser can read the bootstrapped context, include only browser-safe attributes in it. + +Use `@reflag/node-sdk` v2 to produce the bootstrap data. The Vue SDK v2 doesn't accept bootstrap data from Node SDK v1. + +With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It reports `isLoading: true` until that refresh settles. + +Here's an example using the Node.js SDK: + +```js +// server.js (Node.js/SSR) +import { ReflagClient } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: "your-secret-key", // Use secret key on server +}); +await client.initialize(); + +// Fetch flags for specific context +const context = { + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, +}; + +const bootstrappedFlags = client.getFlagsForBootstrap(context); + +// Pass to your Vue app +``` +### ReflagBootstrappedProvider Props + +`ReflagBootstrappedProvider` accepts all the same props as `ReflagProvider` except: + +- `flags`: The pre-fetched bootstrapped state object containing `protocolVersion`, `context`, evaluated `flags`, and an optional `flagStateVersion` +- All other props available in `ReflagProvider` are supported except `context`, `user`, `company`, and `otherContext` (which are extracted from `flags.context`) + +If the `flags` prop is not provided or is undefined, the provider will not initialize the client and will render in a non-loading state. + +> [!NOTE] +> After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. +> +> Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. + +## `` component + +The `` is a lower-level component that accepts a pre-initialized `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. + +### ReflagClientProvider Usage + +```vue + + + +``` + +### ReflagClientProvider Props + +The `ReflagClientProvider` accepts the following props: + +- `client`: A pre-initialized `ReflagClient` instance + +### Slots + +- `loading`: Optional slot to show while the client is initializing (same as `ReflagProvider`) + +> [!Note] +> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. + +## Hooks + +### `useFlag()` + +Returns the value of a given flag for the current context as a ref. The composable provides access to flags and their values. + +`useFlag(key)` returns a `ShallowRef`. With a default, `useFlag(key, defaultValue)` returns a ref whose type comes from the default; see [Multivariate flags](#multivariate-flags). The ref updates when flag values change. Use `useTrack()` to send a track event when the flag is used, `useRequestFeedback()` to open up a feedback dialog, and `useIsLoading()` to manage loading state. + +Example: + +```vue + + + ``` -Each entry includes the flag's `key`, `name`, `description`, a Boolean `value`, 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 `useClient().refresh()` to retry. +See the reference docs for details. -Set `enableTracking: false` to stop sending checks and events, or `offline` to skip all requests. See [Browser feedback documentation](../browser-sdk/FEEDBACK.md) for prompting/UI options. +### `useOptInFlags()` -## Optional key registration +Use this composable to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. It returns the opt-in flags, their loading state and a `setOptIn` function. -```ts -import "@reflag/vue-sdk"; -declare module "@reflag/vue-sdk" { - interface Flags { - huddles: boolean; - "huddle-settings": { maxParticipants: number }; +```vue + + + +``` + +Each entry includes the flag's `key`, `name`, `description`, a Boolean `value` that says whether the flag is on, and whether the user (`userOptedIn`) or company (`companyOptedIn`) has opted in. + +By default, `setOptIn` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. + +User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. + +`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. Vue may not have committed the resulting render yet. + +The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. + +`useOptInFlags()` returns `{ flags, isLoading, setOptIn }`, where `flags` and `isLoading` are computed refs. The separate `useSetOptIn()` composable still works but is deprecated. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. + +If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. + +With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` composable or the provider's loading slot for that initial loading state. + +### `useTrack()` + +`useTrack()` returns a function which lets you send custom events to Reflag. It takes a string argument with the event name and optionally an object with properties to attach the event. + +By default Reflag expects event names to align with the flag keys, so to track usage of a flag, call `track` with the flag key as the event name. + +```vue + + + +``` + +### `useRequestFeedback()` + +Returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features. + +See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. + +When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. +The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. + +```vue + + + +``` + +See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. + +### `useSendFeedback()` + +Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. + +```vue + + + +``` + +### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` + +These composables return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. + +```vue + + + +``` + +Note: To change the `user.id` or `company.id`, you need to update the props passed to `ReflagProvider` instead of using these composables. + +### `useClient()` + +Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that +is not directly accessible through the other composables. + +```vue + + + +``` + +### `useIsLoading()` + +Returns a `Ref` to indicate if Reflag has finished loading. +Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. + +```vue + + + +``` + +### `useOnEvent()` + +Vue composable for listening to Reflag client events. This composable automatically handles mounting and unmounting of event listeners. + +Available events include: + +- `flagsUpdated`: Triggered when flags are updated +- `track`: Triggered when tracking events are sent +- `feedback`: Triggered when feedback is sent + +```vue + + + ``` -Registered flags get autocompletion for their keys and type checks for the defaults you pass. The checks happen at compile time only. To generate the declarations, run `npx reflag flags types` with the `vue` format. +You can also provide a specific client instance if needed: + +```vue + + + +``` ## Migrating from v1 -- `useFlag()` returns the flag's value: replace `const { isEnabled } = useFlag(key)` with `const enabled = useFlag(key)`. Use `.value` in script. +- `useFlag()` returns the flag's value as a ref: replace `const { isEnabled } = useFlag(key)` with `const isEnabled = useFlag(key)`. Use `.value` in script. - Move remote config to a multivariate flag and read it with a default, such as `useFlag("model", "quick")`. Existing remote config isn't converted automatically. -- Use `useTrack()` and `useRequestFeedback()` instead of the flag's `track()` and `requestFeedback()`. +- Use `useTrack()` and `useRequestFeedback()` instead of the flag's `track()` and `requestFeedback()`, and `useIsLoading()` instead of the flag's `isLoading`. - Use the `setOptIn` function returned by `useOptInFlags()`. `useSetOptIn()` still works but is deprecated. - Opt-in entries have a Boolean `value` instead of `isEnabled`. - Remove `fallbackFlags` and pass a default to each read instead, such as `useFlag("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 bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time, and mark the flags the browser needs as not secret. - If you generate type declarations, regenerate them with the v2 CLI. See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps. + +## Content Security Policy (CSP) + +See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP + +## License + +MIT License + +Copyright (c) 2025 Bucket ApS From 3dff4a1c92453de7e1e3acadd9d9bfda71e522eb Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:50:43 +0000 Subject: [PATCH 3/7] docs: fix the bootstrap, Next.js and feedback form examples --- packages/react-sdk/README.md | 45 +++++++++++++++++++++++------------- packages/vue-sdk/README.md | 5 ++-- 2 files changed, 32 insertions(+), 18 deletions(-) diff --git a/packages/react-sdk/README.md b/packages/react-sdk/README.md index 6c0622e8..1acf3c3b 100644 --- a/packages/react-sdk/README.md +++ b/packages/react-sdk/README.md @@ -257,13 +257,15 @@ function useBootstrap() { // Usage in your app function App() { - const { user, flags } = useBootstrap(); + const data = useBootstrap(); + + if (!data) return ; return ( - + @@ -289,9 +291,10 @@ app.get("/bootstrap", (req, res) => { const user = getUser(req); // Get user from your auth system const company = getCompany(req); // Get company from your auth system + // Include only attributes the browser may see const flags = reflagClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + user: { id: user.id, name: user.name, email: user.email }, + company: { id: company.id, name: company.name, plan: company.plan }, other: { source: "web" }, }); @@ -327,18 +330,22 @@ interface PageProps { bootstrapData: BootstrappedFlags; } +// Create one client per server process and reuse it across requests +const serverClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY +}); +const serverClientReady = serverClient.initialize(); + export const getServerSideProps: GetServerSideProps = async (context) => { - const serverClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY - }); - await serverClient.initialize(); + await serverClientReady; const user = await getUserFromSession(context.req); const company = await getCompanyFromUser(user); + // Include only attributes the browser may see const bootstrapData = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + user: { id: user.id, name: user.name, email: user.email }, + company: { id: company.id, name: company.name, plan: company.plan }, other: { page: "homepage" } }); @@ -388,11 +395,14 @@ For Next.js applications using the App Router (Next.js 13+), you can pre-fetch f import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; import { ClientProviders } from "./providers"; +// Create one client per server process and reuse it across requests +const serverClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY! +}); +const serverClientReady = serverClient.initialize(); + async function getBootstrapData() { - const serverClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY! - }); - await serverClient.initialize(); + await serverClientReady; // In a real app, you'd get user/company from your auth system const bootstrapData = serverClient.getFlagsForBootstrap({ @@ -809,12 +819,15 @@ See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/ma Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. ```tsx +import type { FormEvent } from "react"; import { useSendFeedback } from "@reflag/react-sdk"; function CustomFeedbackForm() { const sendFeedback = useSendFeedback(); - const handleSubmit = async (data: FormData) => { + const handleSubmit = async (event: FormEvent) => { + event.preventDefault(); + const data = new FormData(event.currentTarget); await sendFeedback({ flagKey: "reflag-flag-key", score: parseInt(data.get("score") as string), diff --git a/packages/vue-sdk/README.md b/packages/vue-sdk/README.md index 6eb703eb..0959254a 100644 --- a/packages/vue-sdk/README.md +++ b/packages/vue-sdk/README.md @@ -548,7 +548,8 @@ import { useSendFeedback } from "@reflag/vue-sdk"; const sendFeedback = useSendFeedback(); -const handleSubmit = async (data: FormData) => { +const handleSubmit = async (event: Event) => { + const data = new FormData(event.currentTarget as HTMLFormElement); await sendFeedback({ flagKey: "reflag-flag-key", score: parseInt(data.get("score") as string), @@ -558,7 +559,7 @@ const handleSubmit = async (data: FormData) => { From d299305ac726d71d05e42bfc8c0158231ce69491 Mon Sep 17 00:00:00 2001 From: Ron Cohen <744+roncohen@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:57:28 +0000 Subject: [PATCH 4/7] docs: fix broken example code in the SDK READMEs --- packages/browser-sdk/README.md | 14 ++++++++++---- packages/node-sdk/README.md | 7 +++++-- packages/react-sdk/README.md | 12 +++++++----- packages/vue-sdk/README.md | 33 +++++++++++++++++++++------------ 4 files changed, 43 insertions(+), 23 deletions(-) diff --git a/packages/browser-sdk/README.md b/packages/browser-sdk/README.md index 4b607de3..b6d6dded 100644 --- a/packages/browser-sdk/README.md +++ b/packages/browser-sdk/README.md @@ -295,12 +295,14 @@ const bootstrappedState = serverClient.getFlagsForBootstrap({ company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, }); -// Pass the bootstrapped state to the client using your framework's preferred method +// Pass the bootstrapped state to the client using your framework's preferred method. +// Escape `<` so flag values or attributes can't close the script tag. app.get("/", (req, res) => { + const serialized = JSON.stringify(bootstrappedState).replace(/var bootstrappedState = ${JSON.stringify(bootstrappedState)}; + `
`, ), ); @@ -540,10 +542,14 @@ The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are _n For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag: ```ts -import reflag from "@reflag/browser-sdk"; +import { ReflagClient } from "@reflag/browser-sdk"; import { sha256 } from "crypto-hash"; -reflag.user(await sha256("john_doe")); +const reflagClient = new ReflagClient({ + publishableKey, + user: { id: await sha256("john_doe") }, +}); +await reflagClient.initialize(); ``` ## Use of cookies diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index 8f38b7b7..b1224d00 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -469,9 +469,12 @@ export default { // initialize the client and wait for it to complete // if the client was initialized on a previous invocation, this is a no-op. await reflag.initialize(); + // get the user and company from the request in a real app + const userId = "user-1"; + const companyId = "company-1"; const flags = reflag.getFlags({ - user: { id: "userId" }, - company: { id: "companyId" }, + user: { id: userId }, + company: { id: companyId }, }); // ensure all events are flushed and any requests to refresh the flag cache diff --git a/packages/react-sdk/README.md b/packages/react-sdk/README.md index 1acf3c3b..eb36afd4 100644 --- a/packages/react-sdk/README.md +++ b/packages/react-sdk/README.md @@ -768,11 +768,13 @@ import { useTrack } from "@reflag/react-sdk"; function StartHuddle() { const track = useTrack(); -
- -
; + return ( +
+ +
+ ); } ``` diff --git a/packages/vue-sdk/README.md b/packages/vue-sdk/README.md index 0959254a..2db1fb0f 100644 --- a/packages/vue-sdk/README.md +++ b/packages/vue-sdk/README.md @@ -49,15 +49,17 @@ Add the `ReflagProvider` context provider to your application: import { ReflagProvider } from "@reflag/vue-sdk"; - - - + ``` If using Nuxt, wrap `` in ``. `` only renders client-side currently. @@ -236,10 +238,13 @@ The `` component is a specialized version of `Reflag ```vue