Skip to content
FlagSwiftDocs

Next.js SDK

Server components, middleware and no-flicker client flags. Flags are evaluated on the server and the result is handed to the browser, so the first paint is already correct.

Use this SDK in the App Router, route handlers, server actions, middleware and the edge runtime. The server side is built on the Node.js SDK engine, and the client entry re-exports the React SDK. Options and behaviour every SDK shares are on Options and behaviour.

At a glance#

Install
npm install @flagswift/nextjs
Requires
Next.js 13.4+, React 18+
Key
Server key; client entry takes a client key
Evaluates
Locally, in memory
Real-time updates
Client entry only
Works offline from
In memory per process
Outcome analytics
Yes
Verified
Unit tests

Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.

Installation#

bash
npm install @flagswift/nextjs

There are two entry points. The package root, @flagswift/nextjs, is the server entry. @flagswift/nextjs/client is for client components and re-exports every hook from the React SDK.

Initialization#

Create one instance on the server with a server key (fs_srv_…) kept in a private environment variable.

lib/flags.ts
import { createFlagSwift } from "@flagswift/nextjs";

export const flags = createFlagSwift({
  apiKey: process.env.FLAGSWIFT_SERVER_KEY!, // fs_srv_... never NEXT_PUBLIC
  baseUrl: process.env.FLAGSWIFT_URL!,
  environment: process.env.FLAGSWIFT_ENV,
  fallbacks: { "new-hero": false },
});

Two keys

Evaluate on the server with a server key (FLAGSWIFT_SERVER_KEY, never prefixed NEXT_PUBLIC) and give the browser a separate client key (fs_client_…), which may be NEXT_PUBLIC.

The configuration is cached in memory and refreshed on use, with a conditional request. Stale configuration is served at once while the refresh runs, so there are no timers to keep alive on serverless. The first request waits for the first download, but only up to initTimeout (5 seconds).

Connection options#

apiKey and baseUrl are required. The options are those of the server client, minus the polling and streaming options, plus maxAgeMs.

Common options of createFlagSwift
OptionTypeDescription
apiKey*stringA server key (fs_srv_…). Keep it in a private variable.
baseUrl*stringYour server address, starting with http:// or https://.
environmentstringOnly for keys that cover every environment of a project.
maxAgeMsmsHow long the configuration counts as fresh. Default 30000. A stale one is refreshed in the background on use.
fallbacks{ [flag]: value }Served for flags the server does not know, and until a configuration has loaded.
bootstrapConfigPayloadA configuration to start from, for example one saved at build time with getSnapshot().
overridesRecord<string, FlagOverride>Runtime-only server values for local tests. Never sent to Enterprise.
timeout / maxRetries / initTimeoutms / number / msPer request 5000, 3 retries, and the first call waits at most 5000.
autoExposuresbooleanReport an exposure the first time each person gets each outcome. Default false.
onErrorfunctionCalled when a refresh fails. The last good configuration stays.

One instance is kept per process on globalThis. Options are ignored if an instance already exists.

Check flags#

Server methods are asynchronous because they may wait for the first load. Pass the person as the second argument.

app/page.tsx
import { flags } from "@/lib/flags";

export default async function Page() {
  const user = { identifier: session.userId, account: session.orgId };
  const enabled = await flags.isEnabled("new-hero", user);

  return enabled ? <NewHero /> : <Hero />;
}

Middleware#

Evaluation is local and fast enough to run at the edge.

middleware.ts
import { NextResponse, type NextRequest } from "next/server";
import { flags } from "@/lib/flags";

export async function middleware(req: NextRequest) {
  const userId = req.cookies.get("uid")?.value;
  if (!(await flags.isEnabled("beta-area", { identifier: userId }))) {
    return NextResponse.redirect(new URL("/", req.url));
  }
  return NextResponse.next();
}

export const config = { matcher: "/beta/:path*" };

Check variants and values#

tsx
const user = { identifier: session.userId };

const theme = await flags.getValue("theme", user, "light");     // the variant's value, or "light"
const layout = await flags.getVariant("checkout-layout", user);  // "compact" | undefined
const result = await flags.evaluate("new-hero", user);           // { enabled, reason, variant?, value?, found }

No-flicker client flags#

Evaluate on the server, pass the result to the client provider, and client components read it with the usual hooks. The first paint is already correct, and fresh values arrive by polling.

app/layout.tsx
import { FlagSwiftProvider } from "@flagswift/nextjs/client";
import { flags } from "@/lib/flags";

export default async function Layout({ children }) {
  const user = { identifier: session.userId, account: session.orgId };
  const initialFlags = await flags.getBootstrapFlags(user); // outcomes only

  return (
    <FlagSwiftProvider
      config={{ apiKey: process.env.NEXT_PUBLIC_FLAGSWIFT_KEY!, baseUrl: process.env.NEXT_PUBLIC_FLAGSWIFT_URL! }}
      initialFlags={initialFlags}
      user={user}
    >
      {children}
    </FlagSwiftProvider>
  );
}
components/hero.tsx
"use client";
import { useFlag } from "@flagswift/nextjs/client";

export const Hero = () => (useFlag("new-hero") ? <NewHero /> : <OldHero />);

Safe to serialise

getBootstrapFlags contains enabled, variant, value and version, never reasons, targeting or rollout numbers. When a flag is off because of its kill switch it also carries killSwitchActive: true, so the kill-switch hooks are right on the first paint. Both sides use the same engine and bucketing, so the server and client values agree.

Change the person#

On the server the person is an argument, so each call can use a different one. In the browser, when the server renders again for another person (a login, or router.refresh() after a persona switch), the provider sees the new user and initialFlags together and calls identify(user, { flags: initialFlags }): the new flags show at once, with no pass through the previous person's flags. A new initialFlags for the same user is ignored. It rebuilds its client only when apiKey, baseUrl or environment change.

Real-time updates#

The server side reads configuration lazily on use and serverless instances come and go, so there is no long-lived stream there. To have changes pushed to the browser, set streaming: true in the provider's config.

tsx
<FlagSwiftProvider config={{ apiKey, baseUrl, streaming: true }} initialFlags={initialFlags} user={user}>

Offline and errors#

Once a configuration has loaded, evaluation keeps working with no internet and through a server outage. It is local, in memory, and never throws.

What happens when something goes wrong
SituationDescription
A refresh failsThe last good configuration stays. getStatus() reports lastError and consecutiveFailures, and onError is called. After failures the check window doubles, up to five minutes.
First call, nothing loadedWaits at most initTimeout (5 seconds), then answers from fallbacks, then false, while the fetch carries on.
Restart during an outagePass bootstrap (from getSnapshot()), for example one saved at build time. Warm serverless instances keep the configuration in memory only while they stay warm.
A bad snapshotA malformed one, or one for another hash version, is ignored.

Outcome analytics#

Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or turn autoExposures on, and only the person's identifier, the flag, the variant and the event name leave your server.

ts
await flags.trackExposure("checkout-redesign", user); // evaluates locally and records what they got
await flags.track("purchase", user, 49.9);             // what they did, with an optional value
await flags.flushAnalytics();                          // call before a serverless function returns

At most 500 events wait in the queue. Once it is full, new ones are dropped silently (the ones already queued are kept) and counted in getStatus().analytics.dropped.

See Outcomes for how results are read in the console.

Reference#

Install with npm install @flagswift/nextjs. The package root is the server entry and @flagswift/nextjs/client is the browser entry.

Server entry
ExportDescription
createFlagSwift(options): FlagSwiftNextOne instance per process, kept on globalThis. The first instance is kept: calling it again with a different apiKey, baseUrl or environment warns once and the new options are ignored. Options are the server options plus maxAgeMs (default 30000): refresh happens on use, with no timers.
ready(): Promise<FlagSwiftServerClient>The first call waits for the load, but only up to initTimeout (and not at all when a bootstrap is already loaded). After that it serves at once and refreshes in the background once stale. The window grows after failures, up to five minutes. Reach status and the raw client through it.
isEnabled(flagKey, user?, fallback?): Promise<boolean>Local evaluation with the server key.
isKillSwitchEnabled(flagKey): Promise<boolean>Whether the server kill switch is active. Local overrides are ignored on purpose, so a kill can never be masked.
getVariant(flagKey, user?): Promise<string | undefined>The served variant.
getValue<T>(flagKey, user?, fallback?): Promise<T>The variant's value or boolean.
evaluate(flagKey, user?): Promise<ServerEvaluation>The full result with reason and found.
getBootstrapFlags(user?): Promise<Record<string, ClientFlag>>Per-flag enabled, variant, value and version, with no reasons or targeting, plus killSwitchActive: true when the flag is off because of its kill switch. Pass it as initialFlags so the browser renders without flicker.
getSnapshot(): ConfigPayload | nullThe loaded configuration. The only synchronous method.
trackExposure(flagKey, user?) / track(event, user?, value?)Outcome analytics for a person.
Client entry
ExportDescription
<FlagSwiftProvider config initialFlags? user?>Builds one client from config (client key) and wraps the React provider. It is rebuilt only when apiKey, baseUrl or environment change; a new user calls identify with the new initialFlags.
everything from @flagswift/reactHooks, FlagClient, FlagProvider and Feature.
<DeveloperToolbar>Development-only client toolbar for local flag and context overrides.

Segments from your own code#

Put segment keys on the user and they count as extra segment membership: a flag that targets segment beta is turned on for a user who passes segments: ["beta"], even if the segment has no members or rules of its own in FlagSwift. Segments only decide on or off, so a kill switch or a disabled flag still wins, and variants are still chosen by the flag's allocation weights when it is on and its off variant when it is off. Changing the segments re-evaluates the flags.

tsx
<FlagSwiftProvider config={config} user={{ identifier: user.id, segments: ["beta", "staff"] }}>
  {children}
</FlagSwiftProvider>

Trusted input

Segment keys you pass are trusted client input. With a client key anyone can claim any key from the browser, so use them for convenience and personalisation, never to gate anything that must stay protected. Do that check on your server.