NestJS SDK
A module, a service and a route guard. Flags are evaluated locally, so a check is synchronous and makes no network call.
Use this SDK in NestJS 9 or newer. It sits on top of the Node.js SDK, so every option and method there also works here through FlagSwiftService.raw. Options and behaviour every SDK shares are on Options and behaviour.
At a glance#
- Install
npm install @flagswift/nestjs @flagswift/node- Requires
- NestJS 9+, Node 18+
- Key
- Server key (fs_srv_)
- Evaluates
- Locally, in memory
- Real-time updates
- Yes
- Works offline from
- Snapshot file
- Outcome analytics
- Yes
- Verified
- Unit tests
Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.
Installation#
npm install @flagswift/nestjs @flagswift/nodeInitialization#
You need a server key (fs_srv_…) from the API Keys page. Import the global module once in AppModule. The configuration loads when the application starts, and the app still boots when FlagSwift is unreachable.
import { Module } from "@nestjs/common";
import { FlagSwiftModule } from "@flagswift/nestjs";
@Module({
imports: [
FlagSwiftModule.forRoot({
apiKey: process.env.FLAGSWIFT_SERVER_KEY!, // fs_srv_... keep it private
baseUrl: process.env.FLAGSWIFT_URL!,
snapshotPath: "/var/cache/app/flagswift.json",
fallbacks: { "new-billing": false },
}),
],
})
export class AppModule {}To read options from configuration, use forRootAsync with a factory and injected dependencies.
FlagSwiftModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
apiKey: config.getOrThrow("FLAGSWIFT_SERVER_KEY"),
baseUrl: config.getOrThrow("FLAGSWIFT_URL"),
}),
})Stop polling on shutdown
app.enableShutdownHooks() in main.ts. The service then flushes analytics and stops its background polling when the app closes.Connection options#
The module takes every Node.js option, plus two of its own. apiKey and baseUrl are required.
| Option | Type | Description |
|---|---|---|
| apiKey* | string | A server key (fs_srv_…). |
| 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. |
| streaming | boolean | Keep one real-time connection open so changes arrive at once. Default false. |
| fallbacks | { [flag]: value } | Served for flags the server does not know, and until a configuration has loaded. |
| snapshotPath | string | File that keeps the last configuration, so a restart works while the server is down. |
| userFromRequest | (request) => FlagSwiftUser | How a request becomes a person. See Who is the person. |
| onDisabled | "not-found" | "forbidden" | What @RequireFlag answers when the flag is off: 404 (default) or 403. |
| timeout / maxRetries / initTimeout | ms / number / ms | Per request 5000, 3 retries, and startup waits at most 5000. |
| autoExposures / onError | boolean / function | Automatic exposures (default false), and a callback when a refresh fails. |
Check flags#
Inject FlagSwiftService anywhere. Checks are synchronous, in memory, and never throw. isEnabledForRequest works out the person from the request for you.
import { Controller, Get, Req } from "@nestjs/common";
import { FlagSwiftService } from "@flagswift/nestjs";
@Controller("invoices")
export class InvoicesController {
constructor(private readonly flags: FlagSwiftService) {}
@Get()
list(@Req() req) {
return this.flags.isEnabledForRequest("fast-invoice-list", req) ? this.fast() : this.slow();
}
}Gate a route with @RequireFlag#
Put @RequireFlag on a controller or a route. It allows the request only when every listed flag is on for the requester. Hidden features answer 404 by default, so they look like they do not exist. Set onDisabled: "forbidden" for 403, which suits internal APIs.
import { Post } from "@nestjs/common";
import { RequireFlag } from "@flagswift/nestjs";
@RequireFlag("new-billing") // 404 unless the flag is ON for the requesting user
@Post("v2")
create() {}
@RequireFlag("new-billing", "eu-tax") // both must be ON
@Post("v2/eu")
createEu() {}Check variants and values#
The same methods take a person you build yourself, or one from userOf(request).
const user = this.flags.userOf(req);
this.flags.getVariant("checkout-layout", user); // "compact" | undefined
this.flags.getValue("max-upload-mb", user, 10); // the variant's value, or 10
this.flags.evaluate("new-billing", user); // { enabled, reason, variant?, value?, found }
this.flags.evaluateAll(user); // a result for every flagWho is the person#
By default the person comes from request.user. Its id (else sub, userId or email) is the identifier, accountId, tenantId, organizationId or orgId is the account, and the whole object is available to attribute rules. To change that, pass userFromRequest.
FlagSwiftModule.forRoot({
apiKey, baseUrl,
userFromRequest: (req) => ({
identifier: req.user?.id,
account: req.headers["x-tenant"] as string,
attributes: { plan: req.user?.plan },
}),
});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.
FlagSwiftModule.forRoot({ apiKey, baseUrl, streaming: true });If the stream drops, polling returns to its normal rate at once instead of waiting out the slower interval. If streaming is off on the server, or the connection cannot be kept, the client settles on polling. flags.raw.getStatus().streaming reports off, connecting, connected or unavailable.
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 stays. flags.raw.getStatus() reports lastError and consecutiveFailures, and onError is called. Polling backs off up to five minutes. |
| App starts, FlagSwift unreachable | The app still boots and serves fallbacks (or the snapshotPath copy), then false. Startup waits at most initTimeout (5 seconds). |
| Restart during an outage | With snapshotPath, every new configuration is written atomically 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. |
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.
this.flags.trackExposure("checkout-redesign", user); // evaluates locally and records what they got
await this.flags.track("purchase", user, 49.9); // what they did, with an optional value
await this.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 flags.raw.getStatus().analytics.dropped.
See Outcomes for how results are read in the console.
Reference#
Install with npm install @flagswift/nestjs @flagswift/node. The app still boots when FlagSwift is unreachable.
| Option | Type | Description |
|---|---|---|
| userFromRequest | (request) => FlagSwiftUser | How a request becomes a person. Default: request.user id, sub, userId or email as the identifier and accountId, tenantId, organizationId or orgId as the account; the user object becomes the attributes. |
| onDisabled | "not-found" | "forbidden" | What @RequireFlag answers when the flag is off: 404 (default) or 403. |
| all Node.js options | apiKey, baseUrl, snapshotPath, fallbacks and the rest. |
| Export | Description |
|---|---|
| FlagSwiftModule.forRoot(options) | A global module. Import it once in AppModule. |
| FlagSwiftModule.forRootAsync(options) | The same with a factory and injected dependencies. |
| FlagSwiftService | Inject anywhere: isEnabled, getVariant, getValue, evaluate and evaluateAll, plus isEnabledForRequest(flagKey, request, fallback?) and userOf(request). The raw property gives the Node.js client. |
| @RequireFlag(...flagKeys) | On a controller or route. Allows it only when every flag is on for the requester. |
| FlagGuard | The guard behind @RequireFlag. It injects its Reflector and service explicitly, so it also works under esbuild or tsx, which do not emit decorator metadata. |
| defaultUserFromRequest, FLAGSWIFT_OPTIONS, REQUIRE_FLAG_KEY | The default resolver, the options injection token and the metadata key @RequireFlag sets (for custom guards). |
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.
// default mapping reads request.user.segments (string or string[]) when present
flags.isEnabledForRequest("new-checkout", req);
// or explicitly
flags.isEnabled("new-checkout", { identifier: user.id, segments: ["beta"] });Trusted input