Chris Tam · Last updated 25 September 2026
Feature flags let me change who sees a pricing experience after shipping its code. I keep the current table available while I test the replacement and control its rollout in Amplitude.
In this tutorial, I build a small pricing demo with two complete table branches and simulated account controls. I replace a boolean, test canonical users, release to 10%, and verify rollback. The controls simulate sign-in and purchases; they do not authenticate users or charge money.
What you'll build
A standalone Next.js app displays a Starter table or a Team table from pricing-page-v2. It hides pricing while a fetch is pending, reports a failed fetch visibly, and tracks exposure after the selected table renders.
Every application file is included. When adding this to an existing app, I merge the helper into its single Amplitude initialization module and connect real auth transitions to the serialized operation. I preserve existing routes, providers, consent, replay masking, and engagement cleanup. I do not replace production auth with demo buttons.
Prerequisites
- Node.js 24, Corepack, and pnpm. The package file pins pnpm with its integrity hash.
- An Amplitude test project, its project API key, and access to feature flags in that project. In Settings > Projects > the project > General, I select Manage beside API Key.
- A client deployment key for the flag. Server deployment keys stay on the server.
Sign up for free to create an Amplitude account. I use a test project so the exercise does not affect production targeting.
1. Create the standalone app
I create an empty directory and use the Next.js installation guide's Unified SDK package. The configuration below supplies the full app setup.
Terminal
mkdir nextjs-flags-demo
cd nextjs-flags-demopackage.json
{
"name": "nextjs-feature-flags-refresh-2026-11-12",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build --webpack",
"start": "next start",
"typecheck": "tsc --noEmit"
},
"engines": {
"node": ">=24.0.0"
},
"packageManager": "pnpm@10.21.0+sha512.da3337267e400fdd3d479a6c68079ac6db01d8ca4f67572083e722775a796788a7a9956613749e000fac20d424b594f7a791a5f4e2e13581c5ef947f26968a40",
"dependencies": {
"@amplitude/unified": "1.2.1",
"next": "16.4.5",
"react": "19.3.0",
"react-dom": "19.3.0"
},
"devDependencies": {
"@types/node": "24.10.0",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.7",
"typescript": "5.9.3"
}
}pnpm-workspace.yaml
packages:
- .
minimumReleaseAge: 10080
trustPolicy: no-downgradetsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"baseUrl": ".",
"paths": {
"@/*": [
"./*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}.gitignore
node_modules/
.next/
data/
.env*
!.env.example
*.tsbuildinfo.env.example
NEXT_PUBLIC_AMPLITUDE_API_KEY=your-project-api-key
NEXT_PUBLIC_AMPLITUDE_DEPLOYMENT_KEY=your-client-deployment-keyapp/layout.tsx
// Keep existing fonts, metadata, authentication and providers when merging.
import type { ReactNode } from 'react';
export default function RootLayout({ children }: { children: ReactNode }) {
return <html lang="en"><body><main>{children}</main></body></html>;
}After saving the files, I enable the pinned package manager, install dependencies, and copy the environment template.
Terminal
corepack enable
pnpm install
cp .env.example .env.localThe project API key is public and has the minimum scope needed to ingest data. I still keep it in an environment variable. The lockfile generated by this install belongs in version control; subsequent installs use pnpm install --frozen-lockfile.
2. Configure the flag and canonical test users
In Experiment deployments, I create a client-side web deployment in the same project as analytics and copy its key into .env.local. I create a remotely evaluated flag named Pricing page v2, confirm its key is pricing-page-v2, and attach it to that deployment.
I use user-level bucketing, one on variant, and 0% rollout on every general audience, including All Other Users. I save and activate the flag. I then add these individual test users in its Assignment panel:
QA identity contract
user-build-flags-on -> on
user-build-flags-off -> OFF
flag key -> pricing-page-v2OFF is the reserved exclusion choice. I do not create a variant named OFF. These exact strings match the demo controls; an existing app must use its established canonical IDs instead.
3. Serialize identity changes and fresh variant fetches
I initialize once and send every identity change and fetch through one queue. This prevents this helper from overlapping requests for different users. I turn off automatic identity fetches and background retries so they cannot write outside that queue.
lib/amplitude.ts
// Keep replay/consent/engagement settings from other Next.js Build pages when merging.
'use client';
import * as amplitude from '@amplitude/unified';
let ready: Promise<void> | undefined;
let queue: Promise<unknown> = Promise.resolve();
export function amplitudeReady() {
if (!ready) {
const key = process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY;
const deploymentKey = process.env.NEXT_PUBLIC_AMPLITUDE_DEPLOYMENT_KEY;
if (!key || !deploymentKey) return Promise.reject(new Error('Set both Amplitude keys'));
ready = Promise.resolve(amplitude.initAll(key, {
analytics: { autocapture: true, remoteConfig: { fetchRemoteConfig: false } },
sessionReplay: { sampleRate: 0 },
engagement: { skip: true },
experiment: {
deploymentKey, fetchTimeoutMillis: 3000,
automaticFetchOnAmplitudeIdentityChange: false,
retryFetchOnFailure: false, fetchOnStart: false, pollOnStart: false,
throwOnError: true, automaticExposureTracking: false,
},
}));
}
return ready;
}
export function loadPricing(userId: string | null, signOut = false): Promise<{ value: string | null; userId: string | null }> {
const task = queue.catch(() => {}).then(async () => {
await amplitudeReady();
const experiment = amplitude.experiment();
if (!experiment) throw new Error('Experiment did not initialize');
// All identity changes and variant reads belong to this serialized operation.
if (signOut) amplitude.reset();
else if (userId) amplitude.setUserId(userId);
experiment.clear();
await experiment.fetch({ user_id: amplitude.getUserId(), device_id: amplitude.getDeviceId() });
return { value: experiment.all()['pricing-page-v2']?.value ?? null, userId: amplitude.getUserId() ?? null };
});
queue = task;
return task;
}
export function exposePricing() { amplitude.experiment()?.exposure('pricing-page-v2'); }initAll returns a promise in the pinned Unified SDK. I await setup before accessing the experiment client. all() reads the assigned value without recording exposure; the component records exposure only after rendering pricing.
Why. A UI generation counter can ignore an old result while that request still overwrites the SDK cache. Serializing the SDK operations addresses that cache race. Other code must not call fetch(), setUserId(), or reset() outside this helper. During a failed fetch I leave pricing hidden and show a retry control, rather than present cached pricing as a successful remote update. throwOnError: true makes a rejected fetch observable in this pinned SDK.
Session recording is disabled with a zero sample rate, and guides and surveys initialization is skipped. In an existing integration I preserve the site's consent flow and existing product settings. For an EU project, I add serverZone: 'EU' at the top level of initAll and use that project's keys.
4. Replace the hardcoded pricing switch
Before flags, I can choose a table only by editing and deploying a boolean. This before-example shows that decision in isolation; the complete flag version follows it.
Hardcoded decision before the change
const showNewPricing = false;
const plan = showNewPricing
? { name: 'Team', price: 20, projects: 5 }
: { name: 'Starter', price: 10, projects: 1 };I replace that switch with the fetched flag and keep both complete branches. The account buttons are local QA controls, and their selected ID appears above the table. A loading or failed-fetch state does not render a pricing branch.
components/PricingDemo.tsx
// Keep your existing auth flow; these buttons simulate account selection for QA.
'use client';
import { useEffect, useRef, useState } from 'react';
import { loadPricing, exposePricing } from '@/lib/amplitude';
export function PricingDemo() {
const [user, setUser] = useState<string | null>(null);
const [value, setValue] = useState<string | null>(null);
const [status, setStatus] = useState('Loading flags');
const generation = useRef(0);
async function load(id: string | null, signOut = false) {
const current = ++generation.current;
setUser(id); setStatus('Loading flags'); setValue(null);
try {
const next = await loadPricing(id, signOut);
if (current !== generation.current) return;
setUser(next.userId); setValue(next.value); setStatus('Fresh fetch succeeded');
} catch (error) {
if (current === generation.current) setStatus(`Fetch failed: ${String(error)}`);
}
}
useEffect(() => { void load(null); return () => { generation.current += 1; }; }, []);
const loading = status === 'Loading flags';
const fetched = status === 'Fresh fetch succeeded';
useEffect(() => { if (fetched) exposePricing(); }, [fetched, value, user]);
return <>
<h1>Pricing rollout demo</h1>
<p>These controls simulate sign-in. They do not authenticate an account or charge a card.</p>
<p>Canonical user: {user ?? 'anonymous'}</p>
<button disabled={loading} onClick={() => void load('user-build-flags-on')}>Use on test account</button>
<button disabled={loading} onClick={() => void load('user-build-flags-off')}>Use OFF test account</button>
<button disabled={loading} onClick={() => void load(null, true)}>Simulate sign-out</button>
<button disabled={loading} onClick={() => void load(user)}>Fetch latest flag</button>
<p role="status">{status}</p>
{fetched && (value === 'on'
? <section><h2>New pricing</h2><p>Team: $20 per month, up to 5 projects.</p><button onClick={() => alert('Demo only: no purchase')}>Choose Team</button></section>
: <section><h2>Current pricing</h2><p>Starter: $10 per month, 1 project.</p><button onClick={() => alert('Demo only: no purchase')}>Choose Starter</button></section>)}
</>;
}app/page.tsx
import { PricingDemo } from '@/components/PricingDemo';
export default function Home() { return <PricingDemo />; }app/pricing/page.tsx
export { default } from '../page';Why. The generation counter protects component state and cleanup, while the queue protects SDK mutations. They solve different parts of the transition. The exposure effect runs after React commits the table. Remounts and refetches can affect exposure counts, so I verify identity and variant rather than require exactly one event per page load.
For a real sign-out, I close any active guides and surveys first, then let the queued operation call reset(), clear variants, and fetch for the new anonymous device. I never reset a visitor merely because their session is still loading. Client-side pricing is presentation; the server enforces actual prices and entitlements.
5. Test both pricing branches
I start the app and open /pricing.
Terminal
pnpm devI select Use on test account and wait for Fresh fetch succeeded. The canonical ID must be user-build-flags-on, and the Team table must display New pricing. I then select Use OFF test account, wait for another successful fetch, and confirm Current pricing with Starter. During each transition the previous table disappears.
In the Network tab I confirm the variant request succeeds. I inspect browser analytics in the Instrumentation Explorer, because analytics request bodies can be compressed. In Users > User Profiles, I search the canonical on ID and confirm [Experiment] Exposure, [Experiment] Flag Key: pricing-page-v2, and [Experiment] Variant: on. I allow ten seconds to one minute for processing. An OFF exclusion may have no on exposure; its visible fallback and fresh evaluation are the branch check.
MCP. I can use Amplitude MCP to inspect existing flags before adapting this app, so I reuse real keys and event names.
6. Release to 10% and verify rollback
I set the intended general audience to 10% rollout and keep the single on variant's distribution at 100%. For this all-user exercise I use All Other Users at 10% and remove unintended audience rules. I save the flag.
Rollout contract
General audience: All Other Users
Rollout: 10%
Included users: 100% on
Rollback: all general rules 0%, remove on inclusions as neededI use an ordinary identity without an individual assignment to inspect delivery. Bucketing is based on the configured identity, not page views; repeatedly reloading one account does not make new random draws. A handful of test users cannot establish the population percentage.
For rollback I set every general rule, including All Other Users, to 0%. I remove the individual on inclusion or assign that user OFF, save, and select Fetch latest flag for a user that previously saw Team. I require Fresh fetch succeeded and Current pricing before calling the rollback verified. A failed request leaves an error and hidden pricing. Already-open tabs do not receive a guaranteed immediate push; this demo fetches on startup or an explicit control action.
Verify it worked
I check the browser first, then Amplitude:
- Both deterministic users return successful fresh evaluations and the correct table. A failed evaluation shows an error, not a success label.
- Analytics uploads return HTTP 200. I inspect event contents and canonical IDs in Instrumentation Explorer.
- The on user's profile contains the experiment exposure and expected flag/variant properties. I compare identity, visible experience, and assignment rather than exposure counts.
- After rollback, a previously included user gets a successful fresh fetch and sees Starter. I separately check general rules and individual assignments.
Troubleshooting
No pricing table appears
I read the status message. A failed request is intentionally visible. I check both environment variables, restart Next.js after changes, and select Fetch latest flag.
Every user sees Starter after a successful fetch
I confirm the flag is active, attached to the client deployment, and uses the exact key pricing-page-v2. A missing deployment key can otherwise use the project API key's default deployment; this demo rejects missing keys before initialization.
The wrong user appears on the exposure
I compare the displayed ID with the Assignment panel's exact string. In a real app, I route all auth changes and evaluations through the queue and preserve the established canonical format.
The on user still receives Team after rollback
I check individual on inclusions and every general audience. I save the targeting changes and require a successful new evaluation before judging rollback.
Events do not appear in the expected project
I check that the analytics key and deployment belong to the same project and data center. EU keys require top-level serverZone: 'EU'.
Full code reference
These complete files match the numbered steps. The example lockfile pins the dependency tree; Next.js generates next-env.d.ts on first run.
package.json
{
"name": "nextjs-feature-flags-refresh-2026-11-12",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build --webpack",
"start": "next start",
"typecheck": "tsc --noEmit"
},
"engines": {
"node": ">=24.0.0"
},
"packageManager": "pnpm@10.21.0+sha512.da3337267e400fdd3d479a6c68079ac6db01d8ca4f67572083e722775a796788a7a9956613749e000fac20d424b594f7a791a5f4e2e13581c5ef947f26968a40",
"dependencies": {
"@amplitude/unified": "1.2.1",
"next": "16.4.5",
"react": "19.3.0",
"react-dom": "19.3.0"
},
"devDependencies": {
"@types/node": "24.10.0",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.7",
"typescript": "5.9.3"
}
}pnpm-workspace.yaml
packages:
- .
minimumReleaseAge: 10080
trustPolicy: no-downgradetsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"baseUrl": ".",
"paths": {
"@/*": [
"./*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}.gitignore
node_modules/
.next/
data/
.env*
!.env.example
*.tsbuildinfo.env.example
NEXT_PUBLIC_AMPLITUDE_API_KEY=your-project-api-key
NEXT_PUBLIC_AMPLITUDE_DEPLOYMENT_KEY=your-client-deployment-keyapp/layout.tsx
// Keep existing fonts, metadata, authentication and providers when merging.
import type { ReactNode } from 'react';
export default function RootLayout({ children }: { children: ReactNode }) {
return <html lang="en"><body><main>{children}</main></body></html>;
}lib/amplitude.ts
// Keep replay/consent/engagement settings from other Next.js Build pages when merging.
'use client';
import * as amplitude from '@amplitude/unified';
let ready: Promise<void> | undefined;
let queue: Promise<unknown> = Promise.resolve();
export function amplitudeReady() {
if (!ready) {
const key = process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY;
const deploymentKey = process.env.NEXT_PUBLIC_AMPLITUDE_DEPLOYMENT_KEY;
if (!key || !deploymentKey) return Promise.reject(new Error('Set both Amplitude keys'));
ready = Promise.resolve(amplitude.initAll(key, {
analytics: { autocapture: true, remoteConfig: { fetchRemoteConfig: false } },
sessionReplay: { sampleRate: 0 },
engagement: { skip: true },
experiment: {
deploymentKey, fetchTimeoutMillis: 3000,
automaticFetchOnAmplitudeIdentityChange: false,
retryFetchOnFailure: false, fetchOnStart: false, pollOnStart: false,
throwOnError: true, automaticExposureTracking: false,
},
}));
}
return ready;
}
export function loadPricing(userId: string | null, signOut = false): Promise<{ value: string | null; userId: string | null }> {
const task = queue.catch(() => {}).then(async () => {
await amplitudeReady();
const experiment = amplitude.experiment();
if (!experiment) throw new Error('Experiment did not initialize');
// All identity changes and variant reads belong to this serialized operation.
if (signOut) amplitude.reset();
else if (userId) amplitude.setUserId(userId);
experiment.clear();
await experiment.fetch({ user_id: amplitude.getUserId(), device_id: amplitude.getDeviceId() });
return { value: experiment.all()['pricing-page-v2']?.value ?? null, userId: amplitude.getUserId() ?? null };
});
queue = task;
return task;
}
export function exposePricing() { amplitude.experiment()?.exposure('pricing-page-v2'); }components/PricingDemo.tsx
// Keep your existing auth flow; these buttons simulate account selection for QA.
'use client';
import { useEffect, useRef, useState } from 'react';
import { loadPricing, exposePricing } from '@/lib/amplitude';
export function PricingDemo() {
const [user, setUser] = useState<string | null>(null);
const [value, setValue] = useState<string | null>(null);
const [status, setStatus] = useState('Loading flags');
const generation = useRef(0);
async function load(id: string | null, signOut = false) {
const current = ++generation.current;
setUser(id); setStatus('Loading flags'); setValue(null);
try {
const next = await loadPricing(id, signOut);
if (current !== generation.current) return;
setUser(next.userId); setValue(next.value); setStatus('Fresh fetch succeeded');
} catch (error) {
if (current === generation.current) setStatus(`Fetch failed: ${String(error)}`);
}
}
useEffect(() => { void load(null); return () => { generation.current += 1; }; }, []);
const loading = status === 'Loading flags';
const fetched = status === 'Fresh fetch succeeded';
useEffect(() => { if (fetched) exposePricing(); }, [fetched, value, user]);
return <>
<h1>Pricing rollout demo</h1>
<p>These controls simulate sign-in. They do not authenticate an account or charge a card.</p>
<p>Canonical user: {user ?? 'anonymous'}</p>
<button disabled={loading} onClick={() => void load('user-build-flags-on')}>Use on test account</button>
<button disabled={loading} onClick={() => void load('user-build-flags-off')}>Use OFF test account</button>
<button disabled={loading} onClick={() => void load(null, true)}>Simulate sign-out</button>
<button disabled={loading} onClick={() => void load(user)}>Fetch latest flag</button>
<p role="status">{status}</p>
{fetched && (value === 'on'
? <section><h2>New pricing</h2><p>Team: $20 per month, up to 5 projects.</p><button onClick={() => alert('Demo only: no purchase')}>Choose Team</button></section>
: <section><h2>Current pricing</h2><p>Starter: $10 per month, 1 project.</p><button onClick={() => alert('Demo only: no purchase')}>Choose Starter</button></section>)}
</>;
}app/page.tsx
import { PricingDemo } from '@/components/PricingDemo';
export default function Home() { return <PricingDemo />; }app/pricing/page.tsx
export { default } from '../page';Hand it to your agent
I give my agent this tutorial and the following constraints.
Agent prompt
Implement the supplied Next.js feature-flags tutorial as a standalone demo, or
merge into an existing app without deleting routes, auth, providers, consent,
replay masking, or engagement cleanup. Keep its existing Amplitude singleton.
Keep both full pricing branches. Serialize identity mutations and SDK fetches,
disable competing automatic fetches/retries, hide pricing while pending or
failed, and record exposure after rendering. Never use flags for billing auth.
Use individual canonical on/OFF test users at 0% general rollout, then 10% of
the eligible audience with 100% on distribution. Verify rollback only after a
successful new fetch and the current branch. Do not alter real targeting or
publish without instruction. Report changed files and what was actually tested.What this unlocks
Product analytics can compare a real upgrade event with [Experiment] Exposure when I instrument the actual purchase flow.
Session replay can help investigate a pricing journey after I explicitly configure recording and its privacy controls.
Next steps
- Use feature flags with server-side rendering to evaluate before the browser renders pricing.
- Add product analytics to Next.js for a separate event instrumentation walkthrough.
FAQ
Is this an A/B test?
This walkthrough controls a rollout. To analyze an experiment, I also define its hypothesis, control/treatment allocation, and success metric in Feature Experiment. The simulated purchase button sends no upgrade event.
Does 10% rollout mean 10% of page views?
The percentage applies to the configured bucketing unit in the eligible audience. One user can produce many page views while keeping the same assignment.
Does rollback update every open tab immediately?
This app reads a fresh evaluation on startup or control action. I verify success and the rendered branch after saving the rollback; the remote change alone does not prove an open tab refreshed.