Next.js (App Router)

Set up Flaggish in a Next.js App Router app: the proxy, the provider, and flag checks in server and client components.

Flaggish works with Next.js 14, 15 and 16. Flags are fetched once, cached for 30 seconds and checked in memory, so a check is a lookup, not a network call. Everything for Next.js comes from @flaggish/sdk/next, except the client hooks, which come from @flaggish/sdk/react.

Install

Terminal
npm i @flaggish/sdk@beta

Copy the client key from Settings › API keys in the dashboard and add it to .env.local:

.env.local
NEXT_PUBLIC_FLAGGISH_CLIENT_KEY=your-client-key

# Optional: a self-hosted API
NEXT_PUBLIC_FLAGGISH_API_URL=https://flags.example.com
# Optional: which environment's flags to read, if not the one NODE_ENV implies
NEXT_PUBLIC_FLAGGISH_ENV=production

Use the NEXT_PUBLIC_ names: they cover both the server and the browser. Without NEXT_PUBLIC_FLAGGISH_ENV, next dev reads your Development flags and a production build reads Production.

Add the proxy

flaggishMiddleware sets an anonymous flaggish_id cookie on a visitor’s first request, so the server and the browser put that visitor in the same rollouts. Next.js 16 calls this file proxy.ts; Next.js 14 and 15 call it middleware.ts. Put it at the project root, or in src/ if you use one.

proxy.ts
import { flaggishMiddleware } from '@flaggish/sdk/next';
import type { NextRequest } from 'next/server';

export function proxy(request: NextRequest) {
  return flaggishMiddleware(request);
}

With Clerk

Call flaggishMiddleware inside clerkMiddleware (the default export of proxy.ts or middleware.ts) and return its response:

proxy.ts
import { clerkMiddleware } from '@clerk/nextjs/server';
import { flaggishMiddleware } from '@flaggish/sdk/next';

export default clerkMiddleware((auth, req) => {
  // ...your auth logic
  return flaggishMiddleware(req);
});

Passing an existing response

If you already have a response, for example a redirect, pass it as the second argument. The cookie is set on that response, and it’s returned:

proxy.ts
import { flaggishMiddleware } from '@flaggish/sdk/next';
import { NextResponse, type NextRequest } from 'next/server';

export function proxy(req: NextRequest) {
  if (!req.cookies.has('session') && req.nextUrl.pathname !== '/login') {
    return flaggishMiddleware(req, NextResponse.redirect(new URL('/login', req.url)));
  }
  return flaggishMiddleware(req);
}

An existing flaggish_id cookie is never overwritten. On a visitor’s first request, the new cookie is also passed on to the page being rendered, so server components see the same ID the browser will keep. That works with a response you pass in too, including Clerk’s: any request-header overrides already on it are kept.

Add the provider

Wrap your app in FlaggishServerProvider in the root layout:

app/layout.tsx
import { FlaggishServerProvider } from '@flaggish/sdk/next';
import { Suspense } from 'react';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Suspense fallback={<p>Loading…</p>}>
          <FlaggishServerProvider>{children}</FlaggishServerProvider>
        </Suspense>
      </body>
    </html>
  );
}

FlaggishServerProvider is an async server component. It reads the visitor’s flaggish_id cookie, fetches your flags on the server and hands both to the client provider. Client components then render the right values on first paint, including partial rollouts for anonymous visitors, and nothing flips after hydration.

It takes the same props as FlaggishProvider (clientKey, env, apiUrl, defaults, userId, email, reach and the rest), except initialConfig, anonymousId and groupIds, which it fills in itself, plus a server-only secretKey option (default FLAGGISH_SECRET_KEY) that is never passed to the browser.

Suspense and cacheComponents

On Next.js 16 with cacheComponents (on by default in new create-next-app projects), anything that reads request data such as cookies must render inside <Suspense>, or next build fails. FlaggishServerProvider reads cookies, so keep the <Suspense> boundary around it.

The same goes for your own server components that call getFlag, getFlags or getAnonymousId, but the boundary in the root layout only covers a full page load. When someone navigates between pages, Next.js re-renders just the page, not the layout, so each page that calls them needs its own <Suspense> (or a loading.tsx). See Server components. Without one, Next.js shows “uncached data … outside of <Suspense>” in development the first time your flags load. Everything inside a boundary renders per request, so if you want a static shell, put the boundary as low in the tree as you can.

Without cacheComponents

On Next.js 14, 15, or 16 with cacheComponents off, the <Suspense> wrapper is optional: <FlaggishServerProvider>{children}</FlaggishServerProvider> works directly in the layout.

You can also wire up the client provider yourself:

app/layout.tsx
import { getAnonymousId, getFlaggishConfig } from '@flaggish/sdk/next';
import { FlaggishProvider } from '@flaggish/sdk/react';

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <FlaggishProvider initialConfig={await getFlaggishConfig()} anonymousId={await getAnonymousId()}>
          {children}
        </FlaggishProvider>
      </body>
    </html>
  );
}

getAnonymousId() returns null when there’s no cookie. Without anonymousId, the provider reads the cookie after mount, so a partial rollout can switch on after the first paint.

Server components

app/page.tsx
import { getFlag } from '@flaggish/sdk/next';
import { Suspense } from 'react';

export default function Page() {
  return (
    <Suspense fallback={null}>
      <BannerSlot />
    </Suspense>
  );
}

async function BannerSlot() {
  const showBanner = await getFlag('new-banner');
  return showBanner ? <Banner /> : null;
}

getFlag(key, ctx?, fallback?) returns true or false, and getFlags(ctx?) returns every flag as an object. Both read the flaggish_id cookie for you, and both work in route handlers and server actions too.

The server helpers take no options. They read the client key, secret key, API URL and environment from environment variables: FLAGGISH_CLIENT_KEY or NEXT_PUBLIC_FLAGGISH_CLIENT_KEY, FLAGGISH_SECRET_KEY, FLAGGISH_API_URL or NEXT_PUBLIC_FLAGGISH_API_URL, and FLAGGISH_ENV or NEXT_PUBLIC_FLAGGISH_ENV. With cacheComponents, wrap them in a <Suspense> inside the page, as above, or add a loading.tsx next to it. The root-layout boundary doesn’t cover navigations between pages. Without cacheComponents, the page can call getFlag directly.

Client components

app/checkout/checkout.tsx
'use client';
import { useFlag } from '@flaggish/sdk/react';

export const Checkout = () => {
  const enabled = useFlag('new-checkout');
  return enabled ? <NewCheckout /> : <OldCheckout />;
};

useFlag(key, fallback?) returns a boolean. Under FlaggishServerProvider the flags arrive with the page, so there’s no loading state. useFlags() returns { flags, isLoading, error }; isLoading is only true when the provider has to fetch in the browser (no initialConfig, or the server couldn’t reach Flaggish).

Signed-in users

Pass the user’s ID and Flaggish uses it in place of the anonymous ID, so a signed-in person gets the same answer on every device. On the provider:

app/layout.tsx
import { auth } from '@clerk/nextjs/server';
import { FlaggishServerProvider } from '@flaggish/sdk/next';
import { Suspense } from 'react';

async function Flags({ children }: { children: React.ReactNode }) {
  const { userId } = await auth(); // null when signed out
  return <FlaggishServerProvider userId={userId}>{children}</FlaggishServerProvider>;
}

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Suspense>
          <Flags>{children}</Flags>
        </Suspense>
      </body>
    </html>
  );
}

And in server code, as the second argument to getFlag or the first to getFlags:

app/checkout/page.tsx
import { auth } from '@clerk/nextjs/server';
import { getFlag } from '@flaggish/sdk/next';

export default async function CheckoutPage() {
  const { userId } = await auth();
  const newCheckout = await getFlag('new-checkout', { userId });
  return newCheckout ? <NewCheckout /> : <Checkout />;
}

This example uses Clerk (inside your existing ClerkProvider); any auth library that gives you the user’s ID works the same way. userId can be null for signed-out visitors, who then use the anonymous ID.

Someone who browses anonymously and then signs in switches from their anonymous ID to their user ID, so in a partial rollout their answer can change at sign-in.

Groups

Groups give a flag to specific people first. They need the person’s email next to userId, and, for lists, your secret key on the server.

Add the secret key to your server environment only, for example in .env.local. Never give it a NEXT_PUBLIC_ name:

.env.local
# Server only. Not NEXT_PUBLIC_.
FLAGGISH_SECRET_KEY=your-secret-key

Then pass email wherever you pass userId, on the provider and in server code:

app/layout.tsx
import { currentUser } from '@clerk/nextjs/server';
import { FlaggishServerProvider } from '@flaggish/sdk/next';

async function Flags({ children }: { children: React.ReactNode }) {
  const user = await currentUser(); // null when signed out
  return (
    <FlaggishServerProvider userId={user?.id} email={user?.primaryEmailAddress?.emailAddress}>
      {children}
    </FlaggishServerProvider>
  );
}
app/checkout/page.tsx
import { getFlag } from '@flaggish/sdk/next';
import { getCurrentUser } from '@/lib/auth'; // your auth helper
import { Checkout } from '@/components/Checkout';
import { NewCheckout } from '@/components/NewCheckout';

export default async function CheckoutPage() {
  const { userId, email } = await getCurrentUser(); // null values when signed out
  const newCheckout = await getFlag('new-checkout', { userId, email });
  return newCheckout ? <NewCheckout /> : <Checkout />;
}

FlaggishServerProvider checks lists on your server, with the secret key, and sends the browser only the IDs of the groups this person is in, never who else is in them. Company domains are checked from email wherever you pass it.

email is used only for groups. Percentage rollouts still use userId, or the anonymous ID. Without a secret key, people in list groups count as not in the group and fall to the percentage, with one console warning.

Was this page helpful?

Request early access

Become a beta user, or stay up to date with the project.