Skip to content
FlagSwiftDocs

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#

bash
npm install @flagswift/node

Initialization#

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.

flags.ts
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

A server key reads your full targeting configuration. Never ship it to a browser or a mobile app.

Connection options#

apiKey and baseUrl are required. Everything else has a default.

Common options of FlagSwift.connect
OptionTypeDescription
apiKey*stringA server key (fs_srv_…) or admin key.
baseUrl*stringYour server address, starting with http:// or https://.
environmentstringOnly for keys that cover every environment of a project.
refreshIntervalmsHow often to check for a new configuration. Default 30000. 0 turns polling off. An unchanged poll costs a 304.
streamingbooleanKeep one real-time connection open so changes arrive at once. Default false.
streamingPollIntervalmsPolling 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.
snapshotPathstringFile that keeps the last configuration. Loaded first on start so a restart works while the server is down.
bootstrapConfigPayloadA configuration to start from instead of, or before, the snapshot.
timeout / maxRetries / initTimeoutms / number / msPer request 5000, 3 retries, and startup waits at most 5000.
autoExposuresbooleanReport an exposure the first time each person gets each outcome. Default false.
reportErrorsbooleanReport evaluation error counts (never details). Default true.
onError / onUpdatefunctionCalled 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.

ts
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 found

To check several at once, evaluateAll(user) returns a result for every flag, and getFlagKeys() lists the known keys.

Check variants and values#

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

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

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

What happens when something goes wrong
SituationDescription
A refresh failsThe 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 loadedYou get your fallbacks, then false. connect waits at most initTimeout (5 seconds) and never rejects.
Restart during an outageWith snapshotPath, every new configuration is written atomically to that file and read back on the next start, before the network is tried.
A bad snapshotA 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 stategetStatus() for initialized, version, lastFetchTime, lastError and the failure counts.

Serverless

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

ts
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 now

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

Options added by the Node.js SDK
OptionTypeDescription
snapshotPathstringFile that keeps the last configuration. Loaded first on start so a restart works while the server is down.
bootstrapConfigPayloadA configuration to start from instead of, or before, the snapshot.
maxRetriesnumberDefault 3.
Methods of the server client
MethodDescription
FlagSwift.connect(options): Promise<FlagSwift>Also exported as createFlagSwift. Loads the snapshot, fetches fresh configuration and starts polling.
isEnabled(flagKey, user?, fallback?): booleanThe fallback applies only when the flag is not found.
getVariant(flagKey, user?): string | undefinedThe served variant.
getValue<T>(flagKey, user?, fallback?): TVariant value or boolean.
evaluate(flagKey, user?): ServerEvaluationThe 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 | nullThe 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): () => voidCalled after a new configuration is applied.
pause() / destroy()Stop polling; destroy ends the client.
readSnapshot(path) / writeSnapshot(path, payload)The snapshot file helpers.
Version 1 compatibility in Node.js
ExportDescription
FlagSwiftServer, createFlagSwiftClient, checkFlagDrop-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.

ts
flags.isEnabled("new-checkout", { identifier: user.id, segments: ["beta", "staff"] });
flags.evaluate("new-checkout", { identifier: user.id, segments: user.groups });

Trusted input

With a server key the segments you pass are authoritative: your backend decides who is in them.