Node.js SDK
Local evaluation with no network call per check. Flags are evaluated from an in-memory copy of your environment's configuration, so a check is synchronous and fast.
Use this SDK in any Node.js 18+ service. For a framework, see the NestJS SDK or the Next.js SDK, which are built on it. For browsers, use the JavaScript SDK. Options and behaviour every SDK shares are on Options and behaviour.
At a glance#
- Install
npm install @flagswift/node- Requires
- Node 18+
- Key
- Server key (fs_srv_)
- Evaluates
- Locally, in memory
- Real-time updates
- Yes
- Works offline from
- Snapshot file
- 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/nodeInitialization#
You need a server key (fs_srv_…) from the API Keys page. Connect once at startup and share the client. connect never rejects, so your service boots even when FlagSwift is unreachable.
import { FlagSwift } from "@flagswift/node";
export const flags = await FlagSwift.connect({
apiKey: process.env.FLAGSWIFT_SERVER_KEY!, // fs_srv_... keep it private
baseUrl: "https://flags.example.com", // your FlagSwift server
environment: "production",
snapshotPath: "/var/cache/app/flagswift.json", // optional: survive restarts during an outage
fallbacks: { "new-checkout": false },
});
process.on("SIGTERM", () => flags.destroy());Keep the key on the server
Connection options#
apiKey and baseUrl are required. Everything else has a default.
| Option | Type | Description |
|---|---|---|
| apiKey* | string | A server key (fs_srv_…) or admin key. |
| baseUrl* | string | Your server address, starting with http:// or https://. |
| environment | string | Only for keys that cover every environment of a project. |
| refreshInterval | ms | How often to check for a new configuration. Default 30000. 0 turns polling off. An unchanged poll costs a 304. |
| 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 for flags the server does not know, and when no configuration was ever loaded. |
| snapshotPath | string | File that keeps the last configuration. Loaded first on start so a restart works while the server is down. |
| bootstrap | ConfigPayload | A configuration to start from instead of, or before, the snapshot. |
| timeout / maxRetries / initTimeout | ms / number / ms | Per request 5000, 3 retries, and startup waits at most 5000. |
| autoExposures | boolean | Report an exposure the first time each person gets each outcome. Default false. |
| reportErrors | boolean | Report evaluation error counts (never details). Default true. |
| onError / onUpdate | function | Called when a refresh fails, and after a new configuration is applied. |
Check flags#
Checks are synchronous, in memory, and never throw. Pass the person as the second argument.
const user = { identifier: account.userId, account: account.orgId, attributes: { plan: "pro" } };
if (flags.isEnabled("new-checkout", user)) {
runNewCheckout();
}
flags.isEnabled("beta", user, true); // the fallback applies only when the flag is not foundTo check several at once, evaluateAll(user) returns a result for every flag, and getFlagKeys() lists the known keys.
Check variants and values#
flags.getVariant("checkout-layout", user); // "compact" | undefined
flags.getValue("max-upload-mb", user, 10); // the variant's value, or 10
const result = flags.evaluate("new-checkout", user);
// { enabled, reason, variant?, value?, found }
// A missing flag gives found: false (reason FLAG_NOT_FOUND, or ENV_NOT_CONFIGURED when nothing has loaded)Who is the person#
There is no global user on a server. Build the person for each request and pass it to every check. identifier is who they are, account is their organisation, and attributes feed attribute rules.
app.get("/checkout", (req, res) => {
const user = { identifier: req.user.id, account: req.user.orgId, attributes: { plan: req.user.plan } };
res.send(flags.isEnabled("new-checkout", user) ? renderNew() : renderOld());
});Real-time updates#
By default the client polls. Set streaming: true and a flag change reaches the service within moments. The client then downloads the new configuration at once and keeps evaluating locally. The stream carries only a note that something changed, never flag data.
const flags = await FlagSwift.connect({ apiKey, baseUrl, streaming: true });If the stream drops, polling returns to its normal rate at once instead of waiting out the slower interval. Streams are per server process, so a change made on another instance may not reach this connection, which is why polling continues as a safety net. If streaming is off on the server, or the connection cannot be kept, the client settles on polling. getStatus().streaming reports off, connecting, connected or unavailable. To run code on each update, use flags.onUpdate(listener).
Offline and errors#
Once a configuration has loaded, evaluation keeps working with no internet and through a server outage. It is local, in memory, and never throws.
| Situation | Description |
|---|---|
| A refresh fails | The last good configuration and its ETag stay. getStatus() reports lastError and consecutiveFailures, and onError is called. Polling backs off up to five minutes. A recovery is a 304 or a fresh configuration. |
| First start, nothing loaded | You get your fallbacks, then false. connect waits at most initTimeout (5 seconds) and never rejects. |
| Restart during an outage | With snapshotPath, every new configuration is written atomically to that file and read back on the next start, before the network is tried. |
| A bad snapshot | A malformed one, or one for another hash version, is ignored. A server that speaks a newer hashing version than the SDK is refused rather than guessed at. |
| Reading the state | getStatus() for initialized, version, lastFetchTime, lastError and the failure counts. |
Serverless
flushAnalytics() before a function returns, so queued exposures are not lost.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 your server.
flags.trackExposure("checkout-redesign", user); // evaluates locally for this person and records what they got
await flags.track("purchase", user, 49.9); // what they did, with an optional value
await flags.flushAnalytics(); // send what is queued nowAt 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 getStatus().analytics.dropped.
See Outcomes for how results are read in the console.
Reference#
Install with npm install @flagswift/node. Evaluation is synchronous and in memory.
| Option | Type | Description |
|---|---|---|
| snapshotPath | string | File that keeps the last configuration. Loaded first on start so a restart works while the server is down. |
| bootstrap | ConfigPayload | A configuration to start from instead of, or before, the snapshot. |
| maxRetries | number | Default 3. |
| Method | Description |
|---|---|
| FlagSwift.connect(options): Promise<FlagSwift> | Also exported as createFlagSwift. Loads the snapshot, fetches fresh configuration and starts polling. |
| isEnabled(flagKey, user?, fallback?): boolean | The fallback applies only when the flag is not found. |
| getVariant(flagKey, user?): string | undefined | The served variant. |
| getValue<T>(flagKey, user?, fallback?): T | Variant value or boolean. |
| evaluate(flagKey, user?): ServerEvaluation | The full result. A missing flag gives FLAG_NOT_FOUND (or ENV_NOT_CONFIGURED when nothing has loaded) with found: false. |
| evaluateAll(user?) | A result for every flag. |
| getFlagKeys(): string[] | Every known flag key. |
| getSnapshot(): ConfigPayload | null | The loaded configuration, for bootstrap or persistence. |
| trackExposure(flag, user) | Evaluates locally for this user and records the outcome they got. Never throws. |
| track(event, user, value?) | Records an outcome for this user, after their pending exposures. Never rejects. |
| flushAnalytics() | Sends queued exposures now. Call it before a serverless function returns. |
| getStatus() | initialized, environment, version, lastFetchTime, lastError, consecutiveFailures, errorCount and streaming (off, connecting, connected or unavailable). and analytics (pending, sent, dropped, enabled). |
| initialize() / refresh() | Load and re-fetch (If-None-Match; a 304 is success). Failures keep the last good configuration. |
| onUpdate(listener): () => void | Called after a new configuration is applied. |
| pause() / destroy() | Stop polling; destroy ends the client. |
| readSnapshot(path) / writeSnapshot(path, payload) | The snapshot file helpers. |
| Export | Description |
|---|---|
| FlagSwiftServer, createFlagSwiftClient, checkFlag | Drop-in names from the old package. Options include failsafeFallbacks, killSwitchFallbacks, globalIdentifier and snapshotPath; cacheTimeout is accepted and ignored. |
| isKillSwitchEnabled(flagKey) | Whether the flag's configured kill switch is active. Local overrides are ignored on purpose, so a kill can never be masked. |
| activateKillSwitch() / deactivateKillSwitch() | Affect this process only and make no server call. While active, every flag serves its kill switch fallback (default off). |
| evaluateFlags(names, user?) / getAllFlags(user?) | Evaluated booleans, not raw configuration. |
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.
flags.isEnabled("new-checkout", { identifier: user.id, segments: ["beta", "staff"] });
flags.evaluate("new-checkout", { identifier: user.id, segments: user.groups });Trusted input