Set up visitor cookie identity
Create a stable visitor ID in middleware and use it when evaluating flags
Cookie identity gives a visitor the same bucketing subject across requests. Use it when sticky, client-stored bucketing is the policy for a family of flags. If client storage is not appropriate, use request identity and salt rotation instead.
Create the visitor identity
Create one identity at module scope. Its middleware result forwards the visitor ID to the application and persists it on the eventual response.
// visitor-identity.ts
import { createVisitorCookieIdentity } from "@octopus-energy/flags/identity";
export const visitorIdentity = createVisitorCookieIdentity();Apply identity in middleware
For middleware that has no other routing work, resolve the identity and return its response directly.
// proxy.ts
import { visitorIdentity } from "./visitor-identity";
import type { NextRequest } from "next/server";
export async function proxy(request: NextRequest) {
const visitor = await visitorIdentity.resolve(request);
return visitor.response();
}If your application uses middleware.ts, use the same code and export a
function named middleware instead.
Add cookie identity to a flag
Add the cookie identity to each flag that uses this bucketing policy. The example uses the Vercel adapter, but cookie identity works with any Flags SDK adapter.
import { vercelAdapter } from "@flags-sdk/vercel";
import { createCookieIdentity } from "@octopus-energy/flags/identity";
import { flag } from "flags/next";
export const accountFlag = flag({
key: "account-flag",
adapter: vercelAdapter(),
identify: createCookieIdentity(),
defaultValue: false,
options: [true, false],
});Compose with routing middleware (optional)
Resolve the identity first, pass its request headers to downstream middleware, then materialise its response after routing has selected the final response.
import { NextRequest } from "next/server";
export async function proxy(request: NextRequest) {
const visitor = await visitorIdentity.resolve(request);
const routedRequest = new NextRequest(request, {
headers: visitor.requestHeaders,
});
const response = handleI18nRouting(routedRequest);
return visitor.response(response);
}