A basic example of using the SDK in a Node.js application (e.g., an Express server):
Copy
import express, { Request, Response } from 'express';import { FlagSyncFactory, FsUserContext } from '@flagsync/node-sdk';import { getFlagSyncUserContext } from '@/lib/flagsync.user-context.js';const app = express();const port = 3000;// Initialize the SDKconst factory = FlagSyncFactory({ sdkKey: 'your-sdk-key'});// Get the clientconst client = factory.client();// Wait for SDK to be readyawait client.waitForReady();app.get('/', async (req: Request, res: Response) => { const context = getFlagSyncUserContext(req); // Evaluate a flag with user context const isEnabled: boolean = client.flag(context, 'feature-enabled', false); if (isEnabled) { res.send('Feature is ON'); } else { res.send('Feature is OFF'); }});app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`);});
Ensure the key in FsUserContext is unique and persistent for accurate MAU tracking and consistent flag evaluations. See User Context Best Practices for details.
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.js
Copy
import { nanoid } from 'nanoid';import { verify } from 'jsonwebtoken';const MAX_AGE = 60 * 60 * 24 * 7; // 7 daysexport function identifyUser(req, res, next) { const jwt = req.cookies['jwt']; const visitorId = req.cookies['visitor-id'] ?? nanoid(); // Replace this with your own logic to identify the user let user; if (jwt) { try { user = verify(jwt, process.env.JWT_SECRET); } catch (error) { console.error('JWT verification failed:', error); } } if (user?.userId) { // Set the user-id cookie if the JWT contains a userId res.cookie('user-id', user.userId, { maxAge: MAX_AGE, httpOnly: true }); } else { // Set the visitor-id cookie if the JWT does not contain a userId res.cookie('visitor-id', visitorId, { maxAge: MAX_AGE, httpOnly: true }); } 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.js
Copy
import express from 'express';import cookieParser from 'cookie-parser';import { identifyUser } from '@/lib/flagsync.identify.js';import { getFlagSyncUserContext } from '@/lib/flagsync-context.js';const app = express();app.use(cookieParser());app.use(identifyUser); // Identify the userapp.post('/feature', async (req, res) => { const context = getFlagSyncUserContext(req); const isEnabled = client.flag(context, '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.