Getting started

Next.js

Learn how to start using the Flags SDK in your Next.js project.

From the creators of Next.js, the Flags SDK is a free open-source library for implementing feature flags and A/B tests in your applications.

  • Works with any flag provider or custom setup.
  • Compatible with App Router, Pages Router, and Middleware.

Installation

Install the Flags SDK using your preferred package manager:

Terminal
npm install flags

Declaring a feature flag

Create a flags.ts file in your project and declare a feature flag there:

flags.ts
import { flag } from 'flags/next';
 
export const exampleFlag = flag({
  key: 'example-flag',
  decide() {
    return Math.random() > 0.5;
  },
});

This produces an exampleFlag function.

App Router

If you're using the App Router, you can call the flag function from a page, component, or middleware to evaluate the flag.

app/page.tsx
import { exampleFlag } from '../flags';
 
export default async function Page() {
  const example = await exampleFlag();
 
  return <div>{example ? 'Flag is on' : 'Flag is off'}</div>;
}

That's it! Run next dev and open your browser to see the "Flag is on" or "Flag is off" text.

Pages Router

If you're using the Pages Router, you can call the flag function inside getServerSideProps and pass the values to the page as props.

pages/index.tsx
import { exampleFlag } from '../flags';
 
export const getServerSideProps = (async ({ req }) => {
  const example = await exampleFlag(req);
  return { props: { example } };
}) satisfies GetServerSideProps<{ example: boolean }>;
 
export default function Page({ example }: { example: boolean }) {
  return <div>{example ? 'Flag is on' : 'Flag is off'}</div>;
}

That's it! Run next dev and open your browser to see the "Flag is on" or "Flag is off" text.

Flags Explorer

The Flags Explorer is a feature of the Vercel Toolbar which allows overriding feature flags for your session only, without affecting your team members. The Flags SDK will automatically respect overrides set by the Flags Explorer.

This is useful when working with feature flags, as you can try out different states without actually changing the feature flag configuration in the flag provider.

Next steps

Learn how to precompute values at build time
Learn how to identify users with the evaluation context
Learn how to integrate the Flags Explorer

See the API reference page for flags/next

Clone the Flags SDK example