JavaScript SDK
Framework-free browser SDK, about 10 KB. The server decides, so no targeting rules reach the page. This page also covers the client methods every JavaScript client SDK shares, and the core package.
Use this SDK on any website, with or without a framework. For a framework, see the React, Vue or Next.js SDKs, which are built on the same client. Options and behaviour every SDK shares are on Options and behaviour.
At a glance#
- Install
npm install @flagswift/js- Requires
- Any modern browser
- Key
- Client key (fs_client_)
- Evaluates
- On the server, for one person
- Real-time updates
- Yes
- Works offline from
- localStorage cache
- Outcome analytics
- Yes
- Verified
- Tested against shared vectors
Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.
Installation#
npm install @flagswift/jsScript tag, no build step#
Load dist/flagswift.min.js from a CDN. It exposes the global FlagSwift.
<script src="https://unpkg.com/@flagswift/js@2.0.0/dist/flagswift.min.js"></script>
<script>
const flags = FlagSwift.init({ apiKey: "fs_client_...", baseUrl: "https://flags.example.com", user: { identifier: "u1" } });
flags.ready().then(() => {
if (flags.isEnabled("banner")) document.getElementById("banner").hidden = false;
});
</script>Pin a version
To build the file yourself from a source checkout, run npm install in the sdks folder (it installs esbuild, the only tool the bundle needs), then npm run build -w @flagswift/js. The bundle is written to javascript/dist/flagswift.min.js. Without esbuild the build still produces the npm package and prints that it skipped the bundle.
Initialization#
You need a client key (fs_client_…) from the API Keys page and the address of your FlagSwift server. FlagSwift.init returns at once and starts loading; call ready() if you want to wait.
import { FlagSwift } from "@flagswift/js";
const flags = FlagSwift.init({
apiKey: "fs_client_...", // a client key, safe for browsers
baseUrl: "https://flags.example.com", // your FlagSwift server
user: { identifier: "user-42", account: "acme", attributes: { plan: "pro" } },
fallbacks: { "new-checkout": false },
});
await flags.ready(); // optional: waits for flags or the cached copy, at most 3 seconds, never rejectsNever a server key
fs_srv_…) in a browser.Connection options#
apiKey and baseUrl are required. Everything else has a default.
| Option | Type | Description |
|---|---|---|
| apiKey* | string | A client key. |
| baseUrl* | string | Your server address, starting with http:// or https://. |
| environment | string | Only for keys that cover every environment of a project. |
| user | FlagSwiftUser | Who is asking. Change it later with identify. |
| refreshInterval | ms | How often to check for changes. Default 30000. 0 turns polling off. |
| streaming | boolean | Keep one real-time connection open so changes arrive at once. Default false. |
| streamingPollInterval | ms | Polling safety net while a stream is connected. Default 300000. |
| fallbacks | { [flag]: value } | Served until flags load, and for flags the server does not know. |
| initialFlags | Record<string, ClientFlag> | Server-evaluated flags for a first paint that is already correct. |
| overrides | Record<string, FlagOverride> | Runtime-only values for local tests. Never sent to Enterprise. |
| storage | adapter | false | Offline cache. localStorage by default; false turns it off. |
| autoPause | boolean | Default true. Pause polling in a hidden tab. |
| anonymousDeviceId | boolean | Default false. Store a random device id for anonymous visitors. |
| timeout / maxRetries / initTimeout | ms / number / ms | Per request 5000, 2 retries, and startup waits at most 5000. |
| autoExposures | boolean | Report an exposure the first time each outcome is read. Default false. |
| reportErrors | boolean | Report evaluation error counts (never details). Default true. |
| onError | function | Called when a refresh fails. Flags stay as they were. |
Developer overrides#
The browser client exposes local overrides for automated tests or a product-specific debug panel. They affect only this client instance.
flags.setOverride("new-checkout", true);
flags.isEnabled("new-checkout"); // true locally
flags.clearOverride("new-checkout");
flags.clearOverrides();Never an operational control
flags.isKillSwitchEnabled(key) still reports it. isKillSwitchEnabled ignores local overrides on purpose, so a kill can never be masked.Developer toolbar#
mountDeveloperToolbar(client, options) adds a small panel to the page for inspecting flags, forcing one on or off in this browser only, and trying another user. Nothing is sent to FlagSwift. It returns { open, close, destroy } and does nothing in production builds or during server rendering.
import { mountDeveloperToolbar } from "@flagswift/js";
const toolbar = mountDeveloperToolbar(flags, { enabled: import.meta.env.DEV });See the developer toolbar guide for the options.
Check flags#
Reads are synchronous and use the flags already loaded. isEnabled never throws. It answers from the current flags, then the cached copy, then your fallbacks, then false.
if (flags.isEnabled("new-checkout")) showNewCheckout();
// Run code now and whenever this flag changes
const stop = flags.onFlagChange("new-checkout", (on, variant) => render(on, variant));
stop(); // unsubscribeTo react to any change, use flags.subscribe(listener), which returns the unsubscribe function.
Check variants and values#
A flag can serve a named variant, such as a button colour or a plan limit. getVariant gives its key and getValue gives what it carries.
flags.getVariant("button-colour"); // "green" | undefined
flags.getValue("button-colour", "blue"); // the variant's value, or "blue"
flags.getFlag("button-colour"); // { enabled, variant, value, version } | undefinedChange the person#
Call identify after a login, logout or tenant switch. Every flag is re-evaluated for the new person.
await flags.identify({ identifier: "user-43", account: "acme" });Offline, identify uses that person's cached flags if there are any, and otherwise keeps the previous flags rather than dropping to fallbacks. With anonymousDeviceId: true, anonymous visitors get a persistent random device id, so a flag that buckets by device stays stable before login. It is off by default because it stores an identifier.
If you already hold the new person's flags, for example evaluated on the server, pass them: identify(user, { flags }) shows them at once as bootstrap and then refreshes. The same user keeps its bootstrap or network flags rather than a stale cache, and getUser() returns the person being evaluated. From an identify without flags until the new person's flags arrive, automatic exposures are not reported and an explicit trackExposure is skipped, so an exposure is never credited to the wrong user.
Real-time updates#
By default the client polls. Set streaming: true and a flag change reaches the page within moments. The stream carries only a note that something changed, never flag data, and the key travels in a header.
const flags = FlagSwift.init({ apiKey, baseUrl, streaming: true });While the stream is connected, polling slows to streamingPollInterval. If the stream drops, polling returns to its normal rate at once. If streaming is off on the server, or the connection cannot be kept, the client settles on polling. Flags keep working either way. getHealth().streaming reports off, connecting, connected or unavailable.
Offline and errors#
Once flags have loaded, the page keeps working with no internet and through a server outage. Checks read from memory, never touch the network and never throw.
| Situation | Description |
|---|---|
| A refresh fails | The last good flags stay. The status becomes error, onError is called, and polling backs off up to five minutes. The next success clears it. |
| First load, nothing cached | You get your fallbacks, then false, until the response arrives. Startup waits at most initTimeout (5 seconds). |
| Next page load, offline | The flags saved in localStorage apply at once. |
| Hidden tab | Polling pauses, and a refresh runs when the tab returns or the network comes back. |
| Reading the state | getState() for status, source and lastUpdated, getHealth() for failure counts. |
Outcome analytics#
Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or turn autoExposures on, and only the person's identifier, the flag, the variant and the event name leave the page.
flags.trackExposure("checkout-redesign"); // this person was shown the flag's current outcome
await flags.track("purchase", 49.9); // what they did, with an optional value
await flags.flushAnalytics(); // send what is queued now (optional)At most 500 events wait in the queue. Once it is full, new ones are dropped silently (the ones already queued are kept) and counted in getHealth().analytics.dropped.
See Outcomes for how results are read in the console.
Reference#
The sections below keep their own anchors: #client, #js and #core.
Client methods#
Shared by @flagswift/js, @flagswift/react and @flagswift/react-native through FlagSwiftClient in @flagswift/core. Reads are synchronous and use the flags already loaded.
| Method | Description |
|---|---|
| initialize(): Promise<void> | Loads the cache (only when nothing came from bootstrap or the network), fetches, and starts polling. Waits up to initTimeout and never rejects. After destroy() it starts the client again; a superseded earlier call starts no second fetch or timer. |
| identify(user | undefined, { flags? }): Promise<void> | Switches the person and refreshes. Pass flags you already hold for them to show those at once as bootstrap. Until the new person's flags arrive, exposures are not reported. Offline, it uses that person's cached flags if there are any; otherwise it keeps the previous flags rather than dropping to fallbacks. |
| refresh(): Promise<void> | Fetches now. A newer refresh supersedes an older one. On failure the old flags stay and status becomes error. |
| isEnabled(flagKey, fallback?): boolean | Flag, then fallback, then the configured fallbacks (booleans), then false. |
| getVariant(flagKey): string | undefined | The served variant key. |
| getValue<T>(flagKey, fallback?): T | The variant's value, the boolean for plain flags, or the fallback. |
| getFlag(flagKey): ClientFlag | undefined | The raw result: enabled, variant, value, version. |
| getAll(): Record<string, ClientFlag> | Every loaded flag. |
| getState(): ClientState | Status, flags, error, lastUpdated and source. A new object on every change. |
| subscribe(listener): () => void | Called on every change. Returns the unsubscribe function. |
| trackExposure(flag) | Records that the current user was shown the flag's current outcome. Ignored for unknown flags. Never throws. |
| track(event, value?) | Records an outcome for the current user, after their pending exposures. Returns a promise that never rejects. |
| flushAnalytics() | Sends queued exposures now. |
| getUser() | The person being evaluated right now, as last given to the constructor or identify. |
| getHealth() | consecutiveFailures, errorCount, lastUpdated, source and streaming (off, connecting, connected or unavailable). and analytics (pending, sent, dropped, enabled). |
| pause() / resume() | Stop polling; resume resets the failure count, refreshes and restarts polling. |
| destroy() | Stops polling and ignores any fetch still in flight. Calling initialize() again restarts the client, which is what React StrictMode's mount, unmount, mount cycle relies on. |
| Field | Type | Description |
|---|---|---|
| status | "idle" | "loading" | "ready" | "error" | Where the client is. |
| flags | Record<string, ClientFlag> | Loaded results. |
| error | Error | null | The last failure. |
| lastUpdated | number | null | Milliseconds since the epoch. |
| source | "none" | "bootstrap" | "cache" | "network" | Where the current flags came from. |
@flagswift/js#
Framework-free browser SDK. Install with npm install @flagswift/js, or load dist/flagswift.min.js from a CDN, which exposes the global FlagSwift (about 10 KB).
| Option | Type | Description |
|---|---|---|
| storage | StorageAdapter | false | Offline cache. Defaults to localStorage when usable; false turns it off. |
| autoPause | boolean | Default true. Pauses polling in a hidden tab and resumes on return; the online event triggers a refresh. |
| anonymousDeviceId | boolean | Default false. Stores a random id under flagswift:device-id and uses it as the device when none is given. |
| sdk | { name, version } | Sent as the X-FlagSwift-SDK header. Defaults to js 2.0.0. |
| Export | Description |
|---|---|
| FlagSwift.init(config): FlagSwift | Creates the client and starts initialize without waiting. Call ready() before relying on flags. |
| client.ready(timeoutMs = 3000): Promise<ClientState> | Resolves when status is ready or error, or when cached flags are there. On timeout it resolves with the current state. Never rejects. |
| client.onFlagChange(flagKey, listener): () => void | Calls listener(enabled, variant) at once and whenever that flag's result changes. The second argument is the variant key, not the flag. Returns unsubscribe. |
| client.destroy() | Removes the page listeners, then destroys the client. A later initialize() re-attaches them. |
| createClient(config) / init(config) | Same as FlagSwift.init. |
| localStorageAdapter | A StorageAdapter over localStorage (null when blocked). |
| FlagSwiftError, SDK | The error class and the { name, version } constant. |
@flagswift/core#
The engine and clients the other packages are built on. Most apps should use a wrapper SDK. It needs an sdk option, which is sent as the X-FlagSwift-SDK header.
| Export | Description |
|---|---|
| FlagSwiftClient | The remote-evaluation client described above. Extra options: initialFlags, fetch (custom fetch), random (jitter source). A cache load never replaces flags that came from bootstrap or the network. |
| FlagSwiftServerClient | The local-evaluation client described under Node.js. Extra option: onUpdate. A malformed payload, such as a flag without config, is checked before applying and refused, so a half-applied configuration cannot happen; a malformed or wrong-hash bootstrap is ignored. |
| evaluate(config, flagKey, ctx): EvaluationResult | The pure engine. |
| bucket(identifier, flagKey): number | The bucket, 0 to 9999: sha256 of identifier:flagKey, modulo 10000. Variants add :variant to the salt. |
| isInRollout(bucket, percentage) | Whether a bucket is inside a percentage. |
| sha256, utf8, toContext, browserStorage | Helpers. browserStorage returns null when localStorage is missing or blocked. |
| requestJson, backoffDelay, pollDelay, withBudget | The HTTP and timing helpers. |
| HASH_VERSION = 1, RULES_VERSION = 1 | The bucketing and rules versions this engine implements. |
| FlagSwiftError(message, code, status?, retryable?) | The error class. Codes are listed on the SDK reference page. |
Dependencies and segments are followed up to five levels deep. Types exported include ClientFlag, FlagValue, FlagSwiftUser, StorageAdapter, ConfigPayload, ServerEvaluation, EvaluationContext, EvaluationResult and EvaluationReason.
Segments from your own code#
Put segment keys on the user and they count as extra segment membership: a flag that targets segment beta is turned on for a user who passes segments: ["beta"], even if the segment has no members or rules of its own in FlagSwift. Segments only decide on or off, so a kill switch or a disabled flag still wins, and variants are still chosen by the flag's allocation weights when it is on and its off variant when it is off. Changing the segments re-evaluates the flags.
await flags.identify({ identifier: "u1", segments: ["beta", "staff"] });
flags.isEnabled("new-checkout");Trusted input