Skip to content

Latest commit

 

History

History
586 lines (432 loc) · 26 KB

README.md

File metadata and controls

586 lines (432 loc) · 26 KB

Reflag Browser SDK

Basic client for Reflag.com. If you're using React, you'll be better off with the Reflag React SDK.

Reflag supports flag toggling, tracking flag usage, collecting feedback on flags, and multivariate flags that return strings, numbers or JSON objects.

Install

First find your publishableKey under environment settings in Reflag.

The package can be imported or used directly in a HTML script tag:

A. Import module:

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

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 for a working example:

<script src="https://cdn.jsdelivr.net/npm/@reflag/browser-sdk"></script>
<script>
  const reflag = new ReflagBrowserSDK.ReflagClient({
    publishableKey: "publishableKey",
    user: { id: "42" },
    company: { id: "1" },
  });

  reflag.initialize().then(() => {
    console.log("Reflag initialized");
    document.getElementById("loading").style.display = "none";
    document.getElementById("start-huddle").style.display = "block";
  });
</script>
<span id="loading">Loading...</span>
<button
  id="start-huddle"
  style="display: none"
  onClick="reflag.track('Started huddle')"
>
  Click me
</button>

Init options

Supply these to the constructor call:

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 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 users 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.
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",
  },
});

To retrieve a flag's value, use getFlag(key: string):

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, pass a default as the second argument.

You can use getFlags() to retrieve the values of all flags currently.

const flags = reflagClient.getFlags();
// {
//   huddle: true,
//   "huddle-settings": { maxParticipants: 10 }
// }

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.

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);
}

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 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:

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.

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

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:

// 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();

// Pass the bootstrapped state to the client using your framework's preferred method.
// Evaluate flags for each request, so pages get the current flags for the current user.
// Escape `<` so flag values or attributes can't close the script tag.
app.get("/", (req, res) => {
  const bootstrappedState = serverClient.getFlagsForBootstrap({
    user: { id: "user123", name: "John Doe", email: "john@acme.com" },
    company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
  });
  const serialized = JSON.stringify(bootstrappedState).replace(/</g, "\\u003c");
  res.set("Content-Type", "text/html");
  res.send(
    Buffer.from(
      `<script>var bootstrappedState = ${serialized};</script>
      <main id="app"></main>`,
    ),
  );
});

// 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:

// 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,
});

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.

This eliminates loading states and removes the initial render's dependency on the flags API.

Context management

Updating user/company/other context

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.

[!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.

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.

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.

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:

const client = new ReflagClient({
  // show the toolbar even in production if the user is an internal/admin user
  toolbar: user?.isInternal,
  ...
});

You can also configure the position of the toolbar on the screen:

const client = new ReflagClient({
  toolbar: {
    show: true;
    position: {
      placement: "bottom-left",
      offset: {x: "1rem", y: "1rem"}
    }
  }
  ...
})

See the reference for details.

Qualitative feedback on beta flags

Reflag can collect qualitative feedback from your users in the form of a Customer Satisfaction Score 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.

Note

To get started with automatic feedback collection, make sure you've set user in the ReflagClient constructor.

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.

You can find all the options to make changes to the default behavior in the Reflag feedback documentation.

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

Reflag feedback SDK

Feedback can be submitted to Reflag using the SDK:

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)
});

Reflag feedback API

If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API.

See details in Feedback HTTP API

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.

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.

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();

Zero PII

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:

import { ReflagClient } from "@reflag/browser-sdk";
import { sha256 } from "crypto-hash";

const reflagClient = new ReflagClient({
  publishableKey,
  user: { id: await sha256("john_doe") },
});
await reflagClient.initialize();

Use of cookies

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.

The two cookies are:

  • 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.

TypeScript

Types are bundled together with the library and exposed automatically when importing through a package manager.

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 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 <script>-tag from jsdelivr.net you will also need:

Directive Values Reason
script-src-elem https://cdn.jsdelivr.net Loads the Reflag SDK from a CDN

License

MIT License Copyright (c) 2025 Bucket ApS