Next.js (Official SDK)
Integrate server-seeded feature flags with a guarded client provider, safe public snapshots, and explicit refresh behavior.
Integrate with your AI agent
A prompt tailored to this guide, with the relevant Basestack skills.
Preview prompt
Paste this into your coding agent. It will inspect your app and ask for any missing configuration. Keep private tokens out of the conversation.
Use @basestack/flags-react/server to evaluate flags on the server and
@basestack/flags-react/client for client providers, hooks, and components.
For new integrations, Basestack defaults to a server-seeded provider. This is
an integration recommendation, not a requirement imposed by Next.js.
The implementation below matches the reviewed agent reference. It exposes one public boolean decision, preserves ordinary content when keys are missing, and does not automatically fetch flags in the browser.
Choose your integration
- App-wide provider or client hooks: reuse one provider in
RootLayout. - Only a route group needs flags: scope the provider to that layout deliberately. Do not add a page-level provider by accident.
- Server-rendered gate only: choose server-only evaluation explicitly; no provider is required. Preserve an intentional existing architecture.
- Static export: server prefetch runs at build time. Do not copy the request-time layout below unchanged. Rebuild to update the snapshot or deliberately choose public browser evaluation.
Also choose snapshot-only versus browser evaluation. Hydration alone does not decide freshness, and a modern App Router app can use either architecture.
Install and configure
Use your application's existing package manager. Check the installed SDK's exports and React/React DOM peer requirements before installing; do not upgrade the framework automatically to fit an example.
npm install @basestack/flags-reactBASESTACK_PROJECT_KEY=""
BASESTACK_ENVIRONMENT_KEY=""
BASESTACK_FLAGS_BASE_URL="https://flags-api.basestack.co/v1"Get evaluation keys from the dashboard. Use the verified API base URL above, or your self-hosted API URL. Keep environment files out of version control. This example reads configuration on the server, then passes only public evaluation identifiers and the API URL to the client provider. They are visible in the rendered app; a server-only environment variable name does not make serialized values secret. Never pass private API/MCP tokens.
Build a public snapshot
Copy the five files below into an App Router app. Replace new-checkout
consistently with your actual slug. The request-time layout targets Next.js 15+
with connection(); follow the installed version's rendering and Suspense rules.
The adapter accepts only the exact slug and a strict boolean. It checks errors before stripping payloads, descriptions, and remote timestamps. Failures become an explicit disabled entry. Metadata required by the SDK is created locally as documented placeholders, not represented as real flag history.
import type { Flag } from "@basestack/flags-react/client";
export const FLAG_SLUG = "new-checkout";
export interface FlagSnapshot {
slug: typeof FLAG_SLUG;
enabled: boolean;
}
export interface PublicFlagsConfig {
projectKey: string;
environmentKey: string;
baseURL: string;
}
export function publicSnapshot(value: unknown): FlagSnapshot {
const enabled =
typeof value === "object" &&
value !== null &&
"slug" in value &&
value.slug === FLAG_SLUG &&
"enabled" in value &&
value.enabled === true &&
(!("error" in value) || value.error === false);
return { slug: FLAG_SLUG, enabled };
}
export function toSDKFlags(snapshot: FlagSnapshot): Flag[] {
return [
{
...publicSnapshot(snapshot),
// Local adapter placeholders required by Flag, NOT remote flag metadata.
description: "",
createdAt: new Date(0),
updatedAt: new Date(0),
},
];
}For payload-driven features, add a separately validated public payload schema.
Do not cast the DTO to Flag or serialize raw API responses.
Load the server snapshot
Missing keys return a disabled snapshot before constructing an SDK client. The timeout is an example three-second latency budget; adjust it for your app. Both HTTP error values and thrown failures fail closed.
import "server-only";
import { fetchFlag } from "@basestack/flags-react/server";
import {
FLAG_SLUG,
publicSnapshot,
type FlagSnapshot,
type PublicFlagsConfig,
} from "./snapshot";
export interface FlagsBootstrap {
configuration: PublicFlagsConfig | null;
snapshot: FlagSnapshot;
}
export async function loadFlags(input: {
projectKey?: string;
environmentKey?: string;
baseURL?: string;
}): Promise<FlagsBootstrap> {
const projectKey = input.projectKey?.trim();
const environmentKey = input.environmentKey?.trim();
const snapshot = publicSnapshot(null);
if (!projectKey || !environmentKey) {
return { configuration: null, snapshot };
}
const configuration: PublicFlagsConfig = {
projectKey,
environmentKey,
baseURL: input.baseURL?.trim() || "https://flags-api.basestack.co/v1",
};
try {
const flag = await fetchFlag(FLAG_SLUG, {
...configuration,
cache: { enabled: false },
fetchImpl: (url, init) =>
fetch(url, {
...init,
cache: "no-store",
signal: AbortSignal.timeout(3000),
}),
});
return { configuration, snapshot: publicSnapshot(flag) };
} catch {
return { configuration, snapshot };
}
}This disables local SDK and Next fetch caching, not upstream API/CDN caches.
Guard and hydrate the provider
The availability guard lets ordinary children render when configuration is absent, but does not mount the hook-consuming gate without an SDK provider. Use this guard for every provider-dependent consumer; simply returning children without the provider would make unguarded hooks throw.
"use client";
import { FlagsProvider, useFlag } from "@basestack/flags-react/client";
import { createContext, useContext, useMemo, type ReactNode } from "react";
import {
FLAG_SLUG,
toSDKFlags,
type FlagSnapshot,
type PublicFlagsConfig,
} from "./snapshot";
const FlagsAvailable = createContext(false);
export function SnapshotFlags({
configuration,
snapshot,
children,
}: {
configuration: PublicFlagsConfig | null;
snapshot: FlagSnapshot;
children: ReactNode;
}) {
if (!configuration?.projectKey || !configuration.environmentKey) {
return <FlagsAvailable value={false}>{children}</FlagsAvailable>;
}
return (
<ConfiguredFlags configuration={configuration} snapshot={snapshot}>
{children}
</ConfiguredFlags>
);
}
function ConfiguredFlags({
configuration,
snapshot,
children,
}: {
configuration: PublicFlagsConfig;
snapshot: FlagSnapshot;
children: ReactNode;
}) {
const { projectKey, environmentKey, baseURL } = configuration;
const config = useMemo(
() => ({ projectKey, environmentKey, baseURL }),
[projectKey, environmentKey, baseURL],
);
const initialFlags = useMemo(() => toSDKFlags(snapshot), [snapshot]);
return (
<FlagsProvider config={config} initialFlags={initialFlags} preload={false}>
<FlagsAvailable value={true}>{children}</FlagsAvailable>
</FlagsProvider>
);
}
export function CheckoutGate({
children,
fallback,
}: {
children: ReactNode;
fallback: ReactNode;
}) {
const available = useContext(FlagsAvailable);
// The hook-consuming component is never mounted without a valid provider.
if (!available) return fallback;
return <ReadyCheckoutGate fallback={fallback}>{children}</ReadyCheckoutGate>;
}
function ReadyCheckoutGate({
children,
fallback,
}: {
children: ReactNode;
fallback: ReactNode;
}) {
const result = useFlag(FLAG_SLUG, { defaultEnabled: false, fetch: false });
// Snapshot-only: ignore local preview overrides in result.enabled.
if (
result.isLoading ||
result.error ||
result.flag?.error ||
result.flag?.enabled !== true
)
return fallback;
return children;
}Keep configuration stable to avoid rebuilding the SDK client on unrelated
renders. A changed initialFlags prop is synchronized by the SDK in an effect,
not an atomic replacement; do not remount the whole app to refresh a flag.
Compose RootLayout and the gate
RootLayout
Suspense
ServerFlags (server snapshot boundary)
SnapshotFlags (client guard + FlagsProvider)
childrenKeep the root layout server-rendered. The fallback renders ordinary children with flag-dependent UI disabled while the snapshot is pending; unrelated header content remains outside the boundary. Request-time evaluation still delays the resolved wrapped subtree. Scope more narrowly if app-wide blocking is unsuitable.
import { Suspense, type ReactNode } from "react";
import { connection } from "next/server";
import { SnapshotFlags } from "../lib/flags/client";
import { FLAG_SLUG } from "../lib/flags/snapshot";
import { loadFlags } from "../lib/flags/server";
async function ServerFlags({ children }: { children: ReactNode }) {
await connection();
const bootstrap = await loadFlags({
projectKey: process.env.BASESTACK_PROJECT_KEY,
environmentKey: process.env.BASESTACK_ENVIRONMENT_KEY,
baseURL: process.env.BASESTACK_FLAGS_BASE_URL,
});
return <SnapshotFlags {...bootstrap}>{children}</SnapshotFlags>;
}
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<header>My app</header>
<Suspense
fallback={
<SnapshotFlags
configuration={null}
snapshot={{ slug: FLAG_SLUG, enabled: false }}
>
{children}
</SnapshotFlags>
}
>
<ServerFlags>{children}</ServerFlags>
</Suspense>
</body>
</html>
);
}import { CheckoutGate } from "../lib/flags/client";
export default function HomePage() {
return (
<main>
<h1>Store</h1>
<p>This ordinary content is not gated by flags.</p>
<CheckoutGate fallback={<p>Standard checkout</p>}>
<p>New checkout</p>
</CheckoutGate>
</main>
);
}Only the public DTO and evaluation configuration cross to the client, never full
server configuration. Passing initialFlags is sufficient: a hydration script
is not required. If you deliberately choose FlagsHydrationScript, apply the
same public-data review and CSP nonce handling. Never expose raw flags from
Server Actions or Route Handlers either; return a reviewed DTO.
Refresh, navigation, and previews
This is a snapshot-only example: preload={false} prevents provider preload;
fetch: false prevents the hook fetching a missing flag automatically. Neither
setting blocks an explicit SDK refresh() call. Hook refresh runs the browser
SDK, not ServerFlags, and SDK cache may still serve an old value.
Shared layouts retain snapshots during ordinary navigation. A hard reload or
router.refresh() requests server reevaluation, but does not guarantee upstream
cache freshness. router.refresh() does not invalidate server caches. Choose an
explicit refresh policy or a narrower boundary for per-navigation decisions.
Local preview state can override useFlag().enabled. This snapshot-only gate
uses flag.enabled instead and intentionally ignores that override, including
during hydration. For deliberate browser evaluation or opt-in preview UI, use
the React guide, validate refreshed
responses, check flag.error, and explain that browser-visible data is public.
No automatic polling or streaming is promised.
Other architectures
- Server-only: use
loadFlagsin a Server Component and render fromsnapshot.enabled. No provider is needed when that alternative is intentional. - Pages Router: evaluate in
getServerSideProps, return the JSON-compatible bootstrap DTO, and hydrate the existing_appprovider. Pages without a snapshot need a disabled/null bootstrap, not the previous page's flags.getStaticPropsevaluates at build/revalidation time. Do not put SDKFlag[]with Date metadata into JSON props. - Static export: remove the request-time
connection()boundary and choose a build-time snapshot or public browser evaluation. Do not promise per-request SSR. - Cache Components: follow your installed Next.js version's layout/Suspense rules. Cache only deliberately public, appropriately scoped data with an explicit lifetime/invalidation policy. Do not cache one tenant's configuration globally.
- Preview and feedback components: see the Web Components guide. They are optional, not part of this snapshot-only setup.
Verify before rollout
Test missing/blank keys, ordinary content preservation, exact slug/strict boolean
validation, disabled/error/malformed/timeout snapshots, metadata stripping,
hydration, duplicate fetching, preview overrides, changed snapshot props, and
layout persistence. Exercise navigation and router.refresh() in your actual
Next.js app. Check serialized data and browser bundles for sensitive values.
Use mocks first; obtain approval before live requests or resource changes.
Feature flags are not authorization controls. Enforce permissions on the server. See the React contracts and reviewed server signatures for the exact SDK APIs.