Overview
The@flagsync/nest-sdk integrates into Nest.js applications for server-side feature management and event tracking—ideal for backend services and APIs.
npm
Latest version available on npm
GitHub
Explore the source code on GitHub
Installation
Install the SDK with your preferred package manager:Quickstart
A basic example of using the SDK in a Nest.js application—set up the SDK in two steps:1
Configure the Module
Import
FlagSyncModule in your app.module.ts:app.module.ts
2
Inject the Client
Use
@InjectFlagSync() to inject the client into a Provider (e.g., service, controller, etc.):app.controller.ts
Initialization
Get Your SDK Key
Find your server-side SDK key in your workspace settings. Keep server-side keys private to protect flag rules.Initialize the SDK
Initialize the SDK in your Nest.js application using one of these methods:Synchronous Configuration
Configure the SDK synchronously withforRoot:
Asynchronous Configuration
Configure the SDK asynchronously withforRootAsync, ideal for dynamic configuration with ConfigService:
Wait for Readiness
The SDK initializes automatically during module setup—no need to manually wait for readiness with the injectedFsClient.
User Context Decorator
Simplify user context access by creating a custom decorator that returns anFsUserContext object. Pass this object to flag() and track() functions.
This decorator enables passing @UserContext() as a parameter in controller methods.
Usage
Evaluate Flags
Evaluates a feature flag for a given user context. Applies targeting rules, rollouts, and defaults values.app.service.ts
FlagSync CLI
When using the CLI, flag values are automatically inferred from the generated types:Track Events
Submit user actions with thetrack function:
checkout.service.ts
SDK Event Listeners
The SDK emits these events for SDK lifecycle management:SDK_UPDATE: Emitted when flags are updatedSDK_READY: Emitted when the SDK is readyERROR: Emitted when an error occurs during initialization
SDK_UPDATE does not fire if syncing is disabled.Configuration
Configure the SDK with theFsConfig interface:
Custom Attributes
- Define user attributes for targeting in Flags: User Segments.
- See User Context Decorator for the recommended approach to building the context.
Flag Syncing
Configure flag update strategies with thesync object: ws, sse, poll, or off.
1
WebSocket (Default)
Stream updates over a WebSocket connection—flag updates are reevaluated on the server and pushed to the client in real time:
2
SSE
Stream updates via server-sent events (SSE):
3
Polling
Poll the server on an interval:
4
Off
Disable syncing:
Bootstrapping
Initialize the SDK with a set of bootstrap flags:Best Practices
- Select a sync strategy (
ws/sse/poll/off) based on your application’s needs. - Create a User Context Decorator for simplified context management.
- Add user attributes for targeted feature rollouts.
Environment Variables
Set the following environment variable:FLAGSYNC_SDK_KEY: Your server-side FlagSync SDK key (required)