Skip to main content

Overview

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.

npm

View the latest version on npm

GitHub

Explore the source code on GitHub

Installation

Install the SDK and required dependencies with your preferred package manager:

Quickstart

Integrate FlagSync with Vercel Flags in your Next.js app in just a few steps:
1

Initialize the Client

Create the client and export a boolean adapter helper:
@/lib/flagsync
2

Define Your Feature Flag

Use the flag() function to define your feature flag, and connect it to the adapter.
@/lib/flagsync/flags
See User Context Identification for the recommended approach to building the context.
3

Use the Flag in a Server Component

Call your feature flag like an async function in a Server Component to get the evaluated value.
app/page.tsx

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 FlagSync client singleton with your server-side SDK key:
lib/flagsync.ts

Wait for Readiness

The SDK automatically initializes during the Next.js App Router lifecycle—no manual waiting is required for Server Components.

User Context Identification

Define the user context with a custom identify function that returns an FsUserContext object. Pass this function to Vercel’s flag() function.
User contexts enable personalized flag evaluations via Individual Targeting and consistent experiences during Percentage Rollouts.
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 identify with the createIdentify helper, linking flags to user contexts.
@/lib/flagsync
2

Set Up Identification

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.
@/lib/flagsync/user-context
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.
3

Set Cookies in Middleware (Optional)

Use middleware to set user identification cookies, simplifying context retrieval in getFlagSyncUserContext.
middleware.ts
4

Use the Helper in Flag Definitions

Pass identify to the flag definition. This connects flag evaluation to the user context.
@/lib/flagsync/flags

Usage

Evaluate Flags

The are two distinct approaches for evaluating flags, each with different setup requirements and type-safety guarantees.
  • With the FlagSync CLI (Recommended): This approach provides maximum type safety. It automatically generates types that validate your flag keys and infer their specific return values.
  • Manual Typing: If you aren’t using the CLI, this method still provides strong type safety for a flag’s return value, but requires you to create and manage type-specific adapters manually.

FlagSync CLI

When using the CLI, you must use the createTypedFlag function from the @flagsync/nextjs-sdk to build a type-safe flag function. This approach provides full type safety: from key validation to inferred return values, which isn’t possible with the native flags/next package as it’s unaware of your custom types.
1

Generate Types

First, run the FlagSync CLI to generate a flags.d.ts file, mapping your flag keys to their specific data types.
gen/flags.d.ts
2

Build the Type-Safe Flag Function

Create and export a flag function with the createTypedFlag factory.
@lib/flagsync
3

Define Your Flags

Now you can define all your flags. Thanks to the generated types, you’ll get full autocompletion for keys, and TypeScript will automatically infer the correct return type for each flag.
@lib/flagsync/flags
There’s no need for an adapter when using the typed flag function.
4

Use in a Server Component

Await the flag definition in Server Components:
app/page.tsx
An Impression is automatically registered when you evaluate the flag.

Manual Typing

If you’re not using the FlagSync CLI, you can still achieve type safety on your flag’s return values. This approach requires you to manually specify each flag’s expected type by creating and using type-specific adapters. You’ll use the native flag function from flags/next and provide it with an adapter that has been pre-typed.
1

Use the AdapterFactory

Create an adapter for each data type you need. This ensures that the return value of your flag function is correctly typed.
@lib/flagsync
2

Use the Correct Adapter

When defining your flags, import the native flag function from flags/next and pass the corresponding typed adapter you created. This ensures the flag’s return value and defaultValue are correctly typed.
@lib/flagsync/flags
3

Use in a Server Component

Await the flag definition in Server Components:
app/page.tsx

Track Events

Submit user actions with the track function:
api/checkout/route.js
See Events: Tracking to learn about numeric and property events.

SDK Event Listeners

The SDK emits these events for SDK lifecycle management:
  • SDK_UPDATE: Emitted when flags are updated
  • SDK_READY: Emitted when the SDK is ready
  • ERROR: Emitted when an error occurs during initialization
SDK_UPDATE does not fire if syncing is disabled.

Configuration

Configure the SDK with the FsConfig interface:

Custom Attributes

Ensure the key in FsUserContext is unique and persistent for accurate MAU tracking and consistent flag evaluations. See User Context Best Practices for details.

Flag Syncing

Configure flag update strategies with the sync object: ws, sse, poll, or off.
By default, flag updates propagate in milliseconds over a WebSocket connection, ensuring the latest values are used in evaluations.
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.
  • Follow User Context Identification 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)