The @flagsync/nextjs-sdk integrates into Next.js applications with Vercel Flags for feature management and event tracking—ideal for SSR and static site generation workflows.
Create a type-safe feature flag and use it in your Server Components.
Copy
import { flag } from 'flags/next';import { client } from '@/lib/flagsync';import { createStringFlagAdaptor } from '@flagsync/nextjs-sdk';// Flag definitionexport const myFlag = flag({ key: 'my-flag', // Unique flag key identify: () => ({ key: 'user-123' }), // Link flag to user context adapter: createStringFlagAdaptor(client), // Retrieves the flag with type safety});
Ensure the key in FsUserContext is unique and persistent for accurate MAU tracking and consistent flag evaluations. See User Context Best Practices for details.
Copy
import { createIdentify } from '@flagsync/nextjs-sdk';import { getFlagSyncUserContext } from '@/lib/flagsync.user-context.ts';export const identify = createIdentify(getFlagSyncUserContext);
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 Up Identification
Create identify with the helper, linking flags to user contexts.
lib/flagsync.ts
Copy
import { createIdentify } from '@flagsync/nextjs-sdk';import { getFlagSyncUserContext } from '@/lib/flagsync.user-context.ts';export const identify = createIdentify(getFlagSyncUserContext);
3
Set Cookies in Middleware (Optional)
Set user identification cookies in middleware to simplify context retrieval
Middleware is optional—user identification logic can be implemented directly in createIdentify() or getFlagSyncUserContext().
Evaluate flags in Server Components using the Vercel Flags flag function, which applies targeting rules, rollouts, and defaults for the user context:
An Impression is automatically registered when you evaluate the flag.
Copy
import { myFlag } from '@/app/dashboard/flags';export default async function DashboardPage() { const value = await myFlag(); return ( <div>The value of {myFlag.key} is {value}</div> );}
Ensure the key in FsUserContext is unique and persistent for accurate MAU tracking and consistent flag evaluations. See User Context Best Practices for details.