Use promises or events to ensure the SDK is ready before evaluating flags.Always wait for SDK initialization before evaluating any flags. Initialization usually completes within 30–50ms, depending on flag count and ruleset complexity.
1
Promises
Copy
await client.waitForReady();// SDK is ready
2
Events
Copy
import { FsEvent } from '@flagsync/node-sdk';client.once(FsEvent.SDK_READY, () => { // SDK is ready});
Ensure the key in FsUserContext is unique and persistent for accurate MAU tracking and consistent flag evaluations. See User Context Best Practices for details.
1
Create a Helper Function
Create a helper function to construct the user context from request cookies, headers, or your application’s auth system.Adjust the file below to meet your needs.
The key is set using a persistent userId or visitorId from cookies, falling back to a generated ID with nanoid(). For proper MAU tracking and consistent flag evaluations, ensure this key is unique and persistent across requests—see User Context Best Practices.
2
Set Cookies in Middleware (Optional)
Use Express middleware to set user identification cookies, simplifying context retrieval in the helper function.
Middleware is optional—user identification logic can be implemented directly in getFlagSyncUserContext() or elsewhere in your application.
lib/flagsync/identify.ts
Copy
import { nanoid } from 'nanoid';import { verify } from 'jsonwebtoken';export function identifyUser(req, res, next) { // Replace this with your own logic to identify the user const user = verify(req.cookies['jwt'], process.env.JWT_SECRET) if (user?.userId) { // Set the user-id cookie res.cookie('user-id', user.userId); } else { // Set the visitor-id cookie const visitorId = req.cookies['visitor-id'] ?? nanoid(); res.cookie('visitor-id', visitorId); } next();}
3
Use the Helper in Routes
In your Express routes, use the helper to build the FsUserContext for flag evaluations or event tracking.
app.ts
Copy
import express from 'express';import cookieParser from 'cookie-parser';import { identifyUser } from '@/lib/flagsync/identify';import { getFlagSyncUserContext } from '@/lib/flagsync/user-context';const app = express();app.use(cookieParser());app.use(identifyUser); // Identify user middlewareapp.post('/feature', async (req, res) => { const ctx = getFlagSyncUserContext(req); const isEnabled = client.flag(ctx, 'feature-enabled', false); res.status(200).json({ enabled: isEnabled });});
Ensure the key in FsUserContext is unique and persistent for accurate MAU tracking and consistent flag evaluations. See User Context Best Practices for details.