Integrate with Next.js
Server components, middleware and no-flicker client flags.
Before you start#
- A server key (
fs_srv_…) from the API Keys page of your console. See API keys for how keys differ. - The address of your FlagSwift server, for example
https://flags.example.com. - A flag to read. Create one in the console and turn it on in an environment.
Keep the key on the server
Store the key in your secrets manager or an environment variable. Never commit it and never send it to a browser.
Your server#
Enter your server address and, if your key covers every environment of the project, the environment to read. The examples below fill in as you type. Nothing is sent anywhere: the values stay in this browser.
Set up#
Environment
bash FLAGSWIFT_URL=https://flags.example.com FLAGSWIFT_SERVER_KEY=fs_srv_... # private, never NEXT_PUBLIC # Only if you also use flags in client components: NEXT_PUBLIC_FLAGSWIFT_URL=https://flags.example.com NEXT_PUBLIC_FLAGSWIFT_KEY=fs_client_...Install
bash npm install @flagswift/nextjsSet up
ts // lib/flags.ts import { createFlagSwift } from "@flagswift/nextjs"; export const flags = createFlagSwift({ apiKey: process.env.FLAGSWIFT_SERVER_KEY!, baseUrl: process.env.FLAGSWIFT_URL!, });Use
tsx // app/page.tsx (server component) import { flags } from "@/lib/flags"; const enabled = await flags.isEnabled("new-hero", { identifier: session.userId }); // app/layout.tsx: flicker-free flags in client components import { FlagSwiftProvider } from "@flagswift/nextjs/client"; const initialFlags = await flags.getBootstrapFlags({ identifier: session.userId }); <FlagSwiftProvider config={{ apiKey: process.env.NEXT_PUBLIC_FLAGSWIFT_KEY!, baseUrl: process.env.NEXT_PUBLIC_FLAGSWIFT_URL! }} initialFlags={initialFlags} user={{ identifier: session.userId }} > {children} </FlagSwiftProvider>
Verify it works#
Before you run your app, check the key, the address and the environment with one request. A server key downloads the configuration your app will evaluate locally.
curl -s "https://flags.example.com/api/v1/evaluation/server?mode=config" \
-H "Authorization: Bearer $FLAGSWIFT_SERVER_KEY"A 200 response with your flags means everything is wired up. If it fails, Troubleshooting lists the usual causes.