Guide
Feature flags in Next.js and React
Check flags on the server and pass the values down. In the App Router, a Server Component checks a flag in memory, with no network call, and the HTML leaves your server with the right variation. Add the browser SDK only where a component should change while the page is open.
A feature flag in Next.js is a value your code reads at request time to decide what to render or which code path to run: a new checkout for 10% of users, a beta page for one customer, a kill switch for a slow API. Where you read it decides how fast the check is, whether the page flickers, and whether the value can change without a reload.
Next.js feature flags: server or browser?
| Where the code runs | Use | Why |
|---|---|---|
| Server Components, Route Handlers, Server Actions | The server SDK with a server key | The rules are in memory, so a check makes no network call, and the HTML arrives with the right variation. |
| Client Components that need the value when the page loads | A prop from the Server Component above | No flag SDK in the browser bundle, and nothing flickers. |
| Client Components that should update while the page is open | The browser SDK with a client key, bootstrapped from the server | Changes reach the open page within a second; the first render still uses the server's value. |
1. Set up the server SDK once
npm install @railflag/sdk-node @openfeature/server-sdk \
@openfeature/core server-only
Create the provider in one module, lib/flags.ts, and import it wherever you check a flag:
import 'server-only';
import { OpenFeature, type Client } from '@openfeature/server-sdk';
import { RailflagProvider } from '@railflag/sdk-node';
// One provider per server process. It lives on globalThis so that
// hot reloads in development don't open a second one.
const g = globalThis as typeof globalThis & { railflag?: Promise<Client> };
export function flags(): Promise<Client> {
g.railflag ??= OpenFeature.setProviderAndWait(
new RailflagProvider({
sdkKey: process.env.RAILFLAG_SERVER_KEY!, // never a NEXT_PUBLIC_ var
baseUrl: 'https://relay.railflag.com',
}),
)
.catch((err) => {
console.error('Railflag unavailable, serving code defaults', err);
g.railflag = undefined; // try again on the next request
})
.then(() => OpenFeature.getClient());
return g.railflag;
}
The provider downloads your environment's rules when the first request needs them and keeps them current over a stream, so every check after that is a lookup in memory. If Railflag can't be reached at that moment, checks return the defaults in your code and the next request tries again.
- Keep the server key server-side. Server keys can read every rule, and Next.js copies
NEXT_PUBLIC_variables into the browser bundle.import 'server-only'makes the build fail if a Client Component imports this file. - Use the Node.js runtime, the default for Server Components and Route Handlers. The provider keeps the rules and a connection for the life of the process; on serverless hosts, each new instance downloads the rules once.
2. Check a flag in a Server Component
import { cookies } from 'next/headers';
import { flags } from '@/lib/flags';
export default async function CheckoutPage() {
// Your session's user id; a cookie stands in for it here.
const userId = (await cookies()).get('uid')?.value ?? 'anonymous';
const client = await flags();
const newCheckout = await client.getBooleanValue('new-checkout', false, {
targetingKey: userId, // a stable id keeps each user in one variation
plan: 'pro', // attributes your targeting rules can match
});
return <h1>{newCheckout ? 'New checkout' : 'Checkout'}</h1>;
}
The targetingKey decides who lands in a percentage rollout, so use your stable user id. The other attributes are what targeting rules match on, such as plan, country or company. The default, false here, is what users get if the flag doesn't exist or Railflag can't answer, so make it the safe path.
Watch for prerendered pages. A page Next.js renders at build time checks its flags once, at build, and serves that answer until the next deploy. Reading cookies makes the route dynamic, as any per-user check does. For a flag that applies to everyone on an otherwise static page, call await connection() from next/server before the check.
3. Pass the value to Client Components
Most flags in client code need nothing more: the Server Component checks, the Client Component gets a prop.
// app/checkout/page.tsx: after the check above
return <CheckoutButton newFlow={newCheckout} />;
'use client';
export function CheckoutButton({ newFlow }: { newFlow: boolean }) {
const label = newFlow ? 'Pay with one click' : 'Continue to payment';
return <button>{label}</button>;
}
The value is already in the HTML, so the button never shows the old version first, and the browser downloads no flag SDK. It changes on the next request.
4. Live updates with React hooks
When an open page should react to a change within a second, for example a kill switch on a widget or a rollout you are watching, add the browser SDK. It is an OpenFeature web provider, so the OpenFeature React SDK's hooks work with it.
npm install @railflag/sdk-js @openfeature/web-sdk @openfeature/core \
@openfeature/react-sdk
A provider component, app/flags-provider.tsx:
'use client';
import { OpenFeature, OpenFeatureProvider } from '@openfeature/react-sdk';
import { RailflagWebProvider } from '@railflag/sdk-js';
import { useEffect, type ReactNode } from 'react';
type Props = {
userId: string;
bootstrap: Record<string, boolean | string | number>;
children: ReactNode;
};
export function FlagsProvider({ userId, bootstrap, children }: Props) {
useEffect(() => {
// Runs in the browser only. bootstrap holds the values the server
// rendered, so the provider is ready at once.
void OpenFeature.setProviderAndWait(
new RailflagWebProvider({
clientKey: process.env.NEXT_PUBLIC_RAILFLAG_CLIENT_KEY!, // public
baseUrl: 'https://relay.railflag.com',
bootstrap,
}),
{ targetingKey: userId },
);
}, [userId]); // eslint-disable-line react-hooks/exhaustive-deps
return <OpenFeatureProvider>{children}</OpenFeatureProvider>;
}
The page wraps its content in it and hands over what the server already decided:
import { cookies } from 'next/headers';
import { flags } from '@/lib/flags';
import { FlagsProvider } from '@/app/flags-provider';
import { CheckoutButton } from './checkout-button';
export default async function CheckoutPage() {
// Your session's user id; a cookie stands in for it here.
const userId = (await cookies()).get('uid')?.value ?? 'anonymous';
const client = await flags();
const newCheckout = await client.getBooleanValue('new-checkout', false, {
targetingKey: userId,
plan: 'pro',
});
return (
<FlagsProvider userId={userId} bootstrap={{ 'new-checkout': newCheckout }}>
<h1>{newCheckout ? 'New checkout' : 'Checkout'}</h1>
<CheckoutButton newFlow={newCheckout} />
</FlagsProvider>
);
}
And the button reads the flag through a hook:
'use client';
import { useBooleanFlagValue } from '@openfeature/react-sdk';
export function CheckoutButton({ newFlow }: { newFlow: boolean }) {
// The server's answer is the default, so the first render matches
// the HTML. After that the value follows live changes.
const oneClick = useBooleanFlagValue('new-checkout', newFlow);
const label = oneClick ? 'Pay with one click' : 'Continue to payment';
return <button>{label}</button>;
}
Two details remove the flicker. bootstrap gives the provider the values the server rendered, so it is ready at once. The hook's default is the server's answer, so the first browser render matches the HTML. After that, components that use a hook re-render when the flag changes; server-rendered parts, like the heading above, change on the next request.
- Client keys are public, so a
NEXT_PUBLIC_variable is the right place. The browser sends its context to the Railflag relay and gets values back; targeting rules and segment lists never reach the page. - Browser users count towards your plan: each distinct
targetingKeyevaluated through a client key in a month. Starter includes 10,000 a month. Server SDK checks are never counted.
5. Route Handlers and Server Actions
The same helper works anywhere on the server. A flag can open an endpoint to some users before the UI for it exists:
import { flags } from '@/lib/flags';
export async function GET(req: Request) {
const userId = req.headers.get('x-user-id') ?? 'anonymous'; // your auth
const client = await flags();
const on = await client.getBooleanValue('csv-export', false, {
targetingKey: userId,
});
if (!on) return Response.json({ error: 'not_enabled' }, { status: 404 });
return new Response('id,name\n1,Ada\n', {
headers: { 'content-type': 'text/csv' },
});
}
A Server Action checks a flag the same way, before it does the work.
The Pages Router
Apps on the pages/ directory check flags in getServerSideProps and API routes, with the same helper:
import type { GetServerSideProps } from 'next';
import { flags } from '@/lib/flags';
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
const userId = req.cookies.uid ?? 'anonymous'; // your session
const client = await flags();
const newCheckout = await client.getBooleanValue('new-checkout', false, {
targetingKey: userId,
});
return { props: { newCheckout } };
};
Next.js leaves getServerSideProps and the modules only it imports out of the browser bundle, so the server key stays on the server. The server-only package works only with the App Router: if files in pages/ import lib/flags.ts, leave that import out. For live updates, render the FlagsProvider from step 4 in the page and give it the values from getServerSideProps.
Middleware, proxy and the Edge runtime
Middleware runs before a route renders, so it suits flags that decide where a request goes: a rewrite to a new route for users in a rollout, or a redirect while a section is switched off. Flags that change what a page shows belong in the page, where the value can be passed straight to components.
- Next.js 16 renamed middleware to proxy, and
proxy.tsalways runs on the Node.js runtime. Railflag's server SDK is built for Node.js, soflags()works there as it does in a Route Handler. - Older middleware runs on the Edge runtime unless you switch it to Node.js where your version supports it. On Edge, check the flag in the page or a Route Handler instead.
- Keep the matcher narrow. Middleware runs for every request it matches, static files included unless the matcher leaves them out.
Testing flags in Next.js
Tests should never call Railflag. A Client Component that takes the value as a prop needs no flag setup at all: render it once with true and once with false. For server code, replace lib/flags.ts in tests with OpenFeature's in-memory provider, so every check returns the value the test chose:
// checkout.test.ts (Vitest)
vi.mock('@/lib/flags', async () => {
const { OpenFeature, InMemoryProvider } = await import('@openfeature/server-sdk');
await OpenFeature.setProviderAndWait(new InMemoryProvider({
'new-checkout': {
disabled: false, variants: { on: true, off: false }, defaultVariant: 'on',
},
}));
return { flags: async () => OpenFeature.getClient() };
});
Run the important tests with the flag on and off, so a change that breaks the path you aren't looking at fails the build. Testing feature flags covers both paths, defaults and end-to-end tests.
Vercel's Flags SDK
Vercel's Flags SDK declares each flag as a function in your code and reads its value through an adapter. Its OpenFeature adapter accepts a Node.js OpenFeature provider, which is what Railflag's server SDK is, so you can keep that style of declaring flags and have Railflag answer them. Without it, the OpenFeature calls above work on their own, with one dependency fewer.
Percentage rollouts that agree everywhere
A rollout to 20% puts each user in a bucket computed from the flag and their targetingKey. The server SDK and the relay that answers the browser run the same evaluator, so a user in the 20% gets the new checkout in the Server Component, in the Client Component and in your Python, Go or Java services alike. Raising the rollout to 50% only adds users; nobody who had the feature loses it. How bucketing works.
Common mistakes
- A server key in a
NEXT_PUBLIC_variable. Next.js puts those in the browser bundle, where anyone can read every rule with it. Browsers get client keys. - Flags frozen at build time. A prerendered page checks once. Make sure per-user pages are dynamic, or call
connection()first. - A new provider per request. Creating the provider inside a component downloads the rules on every request. Create it once per process, as
lib/flags.tsdoes. - Checking only in the browser for what's on screen at load. The page renders the default first and swaps it a moment later. Render the server's answer, then let the browser take over.
- No
targetingKey. Every visitor without one lands in the same bucket, so a 20% rollout is all or nothing for them, and browser users go uncounted. Use an anonymous id stored in a cookie for visitors who aren't signed in.
Frequently asked questions
How do I add feature flags to a Next.js app?
Install a server SDK, create its provider once per server process, and check flags in Server Components, Route Handlers and Server Actions. Pass the values to Client Components as props, or use the OpenFeature React hooks with a browser provider bootstrapped from the server when a value should change while the page is open.
Should feature flags be evaluated on the server or in the browser in Next.js?
On the server by default: the HTML arrives with the right variation, nothing flickers, and server keys never reach the browser. Use the browser SDK for components that must update live or that depend on context only the browser knows.
How do I stop feature flags from flickering in React?
Render the server's answer into the HTML, start the browser provider with those values as bootstrap, and use them as the hooks' defaults. The first browser render then matches the server, and later changes update in place.
Can I check feature flags in Next.js middleware?
Yes, on the Node.js runtime. In Next.js 16 middleware is called proxy and always runs on Node.js, so a server SDK works there. Use it for flags that decide where a request goes, such as a rewrite to a new route, and check flags that change what a page shows in the page itself.
Do feature flags work with the App Router and Server Components?
Yes. A Server Component can await a flag check like any other data. With an SDK that evaluates in memory, the check adds no network call to the request. Watch for prerendered pages: they evaluate once, at build time.
Feature flags for your Next.js app
Railflag's server SDK checks flags in your process, the browser SDK updates open pages within a second, and both give a user the same variation. Free to start.
Start for free