Chris Tam · Last updated 13 November 2026
Product analytics can start after your application receives a consent grant. I'll build a small first-party controller with Allow, Decline, and Record controls. It stores the choice locally and sends a synthetic action only while the current choice allows it.
In this tutorial, I'll defer SDK loading, handle withdrawal during startup, and verify behavior after reload. The React analytics tutorial covers the broader setup; this example includes its own files.
What you'll build
A banner that dynamically loads Amplitude after a grant, discards actions while off, and sends Consent Demo Action only when ready. Declined choice survives reload without initializing the SDK. Withdrawal gates new actions; it does not erase existing SDK storage or retract requests already sent.
Prerequisites
- Node.js 22.12 or later and Corepack for pnpm.
- An Amplitude test project and its ingestion API key. Open Organization settings > API Keys and select the test project.
- The project data center, US or EU. Preserve your existing consent flow when adapting the example.
No Amplitude account yet? A free account is enough for this tutorial; nothing here needs a paid plan. Sign up for free to get your project API key.
1. Create the standalone app
I'll use the Browser Unified SDK package installation in a small Vite app. The versions below are pinned to the tested example.
mkdir react-consent-banner
cd react-consent-banner
mkdir -p src tests
corepack enable{
"name": "amplitude-react-consent-banner",
"version": "1.0.0",
"private": true,
"type": "module",
"packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
"engines": {
"node": ">=22.12.0",
"pnpm": ">=10.21.0"
},
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "vite build",
"preview": "vite preview --host 127.0.0.1",
"test": "node --test tests/*.test.mjs"
},
"dependencies": {
"@amplitude/unified": "1.2.1",
"react": "19.3.1",
"react-dom": "19.3.1"
},
"devDependencies": {
"vite": "8.3.6"
}
}minimumReleaseAge: 10080
trustPolicy: no-downgradenode_modules/
dist/
.env
.env.local
.env.*.local<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Consent banner demo</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=UScorepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.localPut the test-project key in VITE_AMPLITUDE_API_KEY in .env.local, and set VITE_AMPLITUDE_SERVER_ZONE to US or EU. Vite exposes VITE_ variables in the browser bundle. The project API key is public and has the minimum scope needed to ingest data; a server secret key stays out of browser code.
In an existing application, merge the changes into its current Amplitude module and application flow. Keep authentication, consent, routes, and other instrumentation. Don't add another SDK installation or replace production files with the demo.
2. Gate events on the current choice
I'll keep the consent decision outside React rendering and make the controller the only route to this demo's tracking call. The cookie and consent guide explains why opting out alone isn't a substitute for deferred initialization.
export const choiceKey = 'build-consent-choice-v1';
export function readChoice(storage) {
try { return storage.getItem(choiceKey) === 'granted' ? 'granted' : 'denied'; }
catch { return 'denied'; }
}
export function writeChoice(storage, choice) {
try { storage.setItem(choiceKey, choice); }
catch {
// Remove a stale grant if saving a new choice fails (for example, quota).
storage.removeItem(choiceKey);
throw new Error('Choice could not be saved. Tracking remains off.');
}
}
export function createConsentController({ initialChoice, persist, loadClient }) {
let choice = initialChoice === 'granted' ? 'granted' : 'denied';
let phase = 'off';
let client;
let pending;
let snapshot = { choice, phase, deviceId: null };
const listeners = new Set();
function publish(error = null) {
snapshot = { choice, phase, error, deviceId: client?.getDeviceId() ?? null };
for (const listener of listeners) listener(snapshot);
}
async function start() {
if (choice !== 'granted') return;
phase = 'starting'; publish();
try {
if (!pending) pending = (async () => {
const loaded = await loadClient();
if (choice !== 'granted') return null;
client = loaded;
await client.initialize();
return client;
})();
const result = await pending;
if (!result) { pending = null; phase = 'off'; publish(); return; }
result.setOptOut(choice !== 'granted');
phase = choice === 'granted' ? 'ready' : 'off'; publish();
} catch (error) {
client?.setOptOut(true); phase = 'error'; publish(error.message);
}
}
return {
getSnapshot: () => snapshot,
subscribe(listener) { listeners.add(listener); listener(snapshot); return () => listeners.delete(listener); },
restore: start,
async grant() {
try { persist('granted'); }
catch (error) { choice = 'denied'; client?.setOptOut(true); phase = 'error'; publish(error.message); return; }
choice = 'granted'; await start();
},
deny() {
choice = 'denied'; client?.setOptOut(true); phase = 'off';
try { persist('denied'); publish(); }
catch (error) { publish(error.message); }
},
async record() {
if (choice !== 'granted' || phase !== 'ready') return false;
const result = await client.track();
return result.code === 200;
},
};
}The controller persists its own choice. It loads a client only after a grant, checks the latest choice again before initialization, and checks again when initialization completes. A withdrawal while startup is pending cannot turn into a stale grant when that promise resolves.
Why. SDK calls made before initialization can queue. This example doesn't call the SDK for actions while off, so it doesn't replay those actions after consent. Both the UI and record guard enforce that choice.
If saving the choice fails, the storage helper removes its stale grant rather than leaving it authoritative. The current controller keeps collection off on errors. An SDK initialization error preserves the user's selected choice while reporting a non-ready error state.
3. Load and initialize the SDK after a grant
I'll put the SDK import in a separate module and dynamically import that module from the controller. It starts opted out, with automatic capture off. Only the current grant can enable tracking after initialization.
import * as amplitude from '@amplitude/unified';
let initialization;
export const client = {
initialize() {
if (!initialization) initialization = amplitude.initAll(import.meta.env.VITE_AMPLITUDE_API_KEY.trim(), {
serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
analytics: { optOut: true, autocapture: false, remoteConfig: { fetchRemoteConfig: false } },
sessionReplay: { sampleRate: 0 }, engagement: { skip: true },
});
return initialization;
},
setOptOut: (value) => amplitude.setOptOut(value),
getDeviceId: () => amplitude.getDeviceId(),
track: () => amplitude.track('Consent Demo Action', { surface: 'local_preferences' }).promise,
};setOptOut(true) is the SDK's additional event gate. The application gate stops new demo calls immediately on withdrawal; SDK opt-out is also set. Replay sampling is zero, guides and surveys are skipped, and analytics remote fetching is disabled. A regrant reuses the initialized instance instead of initializing it again.
Withdrawing doesn't undo an earlier grant's initialization, delete existing identity or event storage, remove ingested events, or retract requests already in flight. This example controls new analytics actions in one client. Other products, destinations, SDK instances, and your storage-retention choices need their own integration.
MCP. Use the Docs MCP server to check the current initialization and opt-out options. It reads public docs and doesn't determine the consent policy for your application.
4. Connect the banner controls
I'll subscribe the UI to the controller and keep the withdrawal button available while startup is pending. The React effect only subscribes to display state; it doesn't initialize analytics or send an event.
import React, { useEffect, useState } from 'react';
export function App({ controller, configured }) {
const [state, setState] = useState(controller.getSnapshot);
const [message, setMessage] = useState('Choose whether to enable analytics for this demo.');
useEffect(() => controller.subscribe(setState), [controller]);
async function record() {
try { setMessage(await controller.record() ? 'Demo event accepted.' : 'No demo event accepted.'); }
catch { setMessage('The demo event could not be uploaded.'); }
}
return (
<main>
<p className="eyebrow">CONSENT CONTROL DEMO</p><h1>Choose analytics collection</h1>
<p>This first-party demo stores your choice locally. It imports and initializes Amplitude only after a grant, discards actions while off, and keeps replay disabled. Withdrawal stops new actions; it doesn't erase prior SDK storage or retract requests already sent.</p>
{!configured && <p>No test key configured. Tracking stays off.</p>}
<button id="grant" disabled={!configured} onClick={() => controller.grant()}>Allow analytics</button>
<button id="deny" onClick={() => controller.deny()}>Decline or withdraw</button>
<button id="record" disabled={state.phase !== 'ready'} onClick={record}>Record demo action</button>
<p>Choice: <strong id="choice">{state.choice}</strong></p>
<p>Analytics: <strong id="phase">{state.phase}</strong></p>
<p role="status">{state.error ?? message}</p>
<p>Device ID: <code id="device-id">{state.deviceId ?? 'not initialized'}</code></p>
</main>
);
}:root { font-family: Helvetica, Arial, sans-serif; color: #000000; background: #F2F4F8; }
body { margin: 0; }
main { max-width: 760px; margin: 40px auto; padding: 32px; background: #FFFFFF; border-radius: 16px; }
h1 { font-size: 36px; }
p { line-height: 1.5; }
.eyebrow { font-size: 12px; letter-spacing: 0.08em; }
nav { display: flex; gap: 20px; flex-wrap: wrap; padding: 16px 0; }
a { color: #0052F2; }
section, aside { border-top: 1px solid #D5D9E0; margin-top: 24px; padding-top: 24px; }
label { display: block; margin-bottom: 8px; }
button, select, [role='button'] { font: inherit; padding: 10px 14px; margin: 0 12px 12px 0; border: 1px solid #000000; border-radius: 6px; color: #000000; background: #FFFFFF; }
button, [role='button'] { cursor: pointer; }
#save-settings { color: #FFFFFF; background: #0052F2; border-color: #0052F2; }
[role='button'] { display: inline-block; }
:focus-visible { outline: 3px solid #0052F2; outline-offset: 3px; }
code { overflow-wrap: anywhere; }
@media (max-width: 800px) { main { margin: 16px; padding: 24px; } }
button:disabled, select:disabled { opacity: 0.6; cursor: wait; }
form { margin-top: 24px; }A missing key leaves tracking off. The Record control only becomes available when the client is ready and the current choice is granted. The controller also checks the choice, so a disabled button isn't the only guard.
This is a technical first-party example, not a verified integration with a named consent platform or a legal-compliance guarantee. Adapt the stored-choice lifecycle to your application's actual policy.
5. Mount and test the app
I'll start the app once outside the React component tree and retain Strict Mode. The tests exercise the operation or session behavior separately from the UI.
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.jsx';
import { createConsentController, readChoice, writeChoice } from './consent.js';
import './style.css';
const configured = Boolean(import.meta.env.VITE_AMPLITUDE_API_KEY?.trim());
const controller = createConsentController({
initialChoice: configured ? readChoice(localStorage) : 'denied',
persist: (choice) => writeChoice(localStorage, choice),
loadClient: async () => (await import('./analytics-client.js')).client,
});
createRoot(document.getElementById('root')).render(<StrictMode><App controller={controller} configured={configured} /></StrictMode>);
if (configured) void controller.restore();import test from 'node:test';
import assert from 'node:assert/strict';
import { createConsentController, readChoice, writeChoice, choiceKey } from '../src/consent.js';
test('off actions are discarded, grant initializes once and withdrawal gates new actions', async () => {
let loads = 0, starts = 0, tracks = 0; const optOut = [];
const client = { initialize: async () => { starts++; }, getDeviceId: () => 'demo-device',
setOptOut: (value) => optOut.push(value), track: async () => { tracks++; return { code: 200 }; } };
const control = createConsentController({ initialChoice: 'denied', persist: () => {}, loadClient: async () => { loads++; return client; } });
assert.equal(await control.record(), false); assert.equal(loads, 0);
await control.grant(); assert.equal(await control.record(), true);
control.deny(); assert.equal(await control.record(), false);
await control.grant(); assert.equal(starts, 1); assert.equal(loads, 1); assert.equal(tracks, 1);
assert.deepEqual(optOut, [false, true, false]);
});
test('withdrawal while initialization is pending never enables the completed client', async () => {
let release; let started; const entered = new Promise((r) => { started = r; }); const optOut = [];
const client = { initialize: () => { started(); return new Promise((r) => { release = r; }); },
setOptOut: (value) => optOut.push(value), getDeviceId: () => 'demo-device' };
const control = createConsentController({ initialChoice: 'denied', persist: () => {}, loadClient: async () => client });
const granting = control.grant(); await entered; control.deny(); release(); await granting;
assert.equal(control.getSnapshot().phase, 'off'); assert.ok(optOut.every(Boolean));
});
test('declining during client import prevents initialization; malformed storage stays off', async () => {
let release; let starts = 0;
const control = createConsentController({ initialChoice: 'denied', persist: () => {},
loadClient: () => new Promise((r) => { release = r; }) });
const granting = control.grant(); control.deny(); release({ initialize: () => { starts++; } }); await granting;
assert.equal(starts, 0); assert.equal(readChoice({ getItem: () => 'unknown' }), 'denied');
});
test('storage-write failure removes a stale grant and does not enable collection', async () => {
let removed;
const storage = { setItem: () => { throw new Error('Quota'); }, removeItem: (key) => { removed = key; } };
assert.throws(() => writeChoice(storage, 'denied'), /Tracking remains off/); assert.equal(removed, choiceKey);
});
test('initialization failure keeps tracking off without changing the persisted choice', async () => {
const persisted = []; const optOut = [];
const control = createConsentController({ initialChoice: 'denied', persist: (value) => persisted.push(value),
loadClient: async () => ({ initialize: async () => { throw new Error('Startup failed'); },
setOptOut: (value) => optOut.push(value), getDeviceId: () => undefined }) });
await control.grant();
assert.equal(control.getSnapshot().choice, 'granted');
assert.equal(control.getSnapshot().phase, 'error');
assert.equal(await control.record(), false);
assert.deepEqual(persisted, ['granted']); assert.deepEqual(optOut, [true]);
});pnpm test
pnpm build
pnpm devOpen the local URL printed by Vite.
Verify it worked
Test both choices, their reload behavior, and an interrupted initialization. Use synthetic events in an existing test project.
- Before a grant: Open the app in a fresh browser context. Confirm Record is disabled and no Amplitude network request occurs. The SDK module should not load yet. A blank key also keeps the Allow control disabled.
- Grant and record: Allow analytics, wait until ready, then record a demo action. Confirm upload HTTP 200. Use Instrumentation Explorer to inspect
Consent Demo Actionwithsurface: local_preferences; larger SDK payloads can be compressed. - Withdraw and reload: Decline or withdraw. Record should be disabled and new actions should be discarded. Reload and confirm the saved declined choice stays off without loading or initializing the SDK. This does not require deleting SDK cookies created during an earlier grant.
- Regrant and persisted grant: Allow again and record. Reload while granted and confirm startup restores that choice; another deliberate action should send an event. In User Lookup, search the displayed device ID and inspect the processed actions, allowing ten seconds to one minute for them to appear.
- Pending startup: Run the tests that hold the client import and initialization promises pending, then withdraw before resolving them. Confirm initialization is skipped when import finishes after denial, and that a started client never gets enabled by a stale completion. The real browser check should also exercise an Allow-then-withdraw sequence before recording. In-flight requests from an earlier allowed action are a separate boundary.
Troubleshooting
Events arrive immediately after allowing analytics
Look for SDK calls made before initialization or another script/instance that tracks independently. This controller discards off-state actions; it doesn't call track early and rely on the SDK queue.
The SDK creates cookies even while opted out
SDK initialization can create cookies independently of event opt-out. Defer initialization until the grant if your application's policy needs that boundary. The demo imports its client dynamically after the grant.
A quick withdrawal is followed by ready state
Check the current choice after every asynchronous import/initialization boundary. Don't capture the original granted value in a callback and enable tracking unconditionally when it resolves.
Declining disappears after reload
Persist the application choice successfully. Treat invalid or unreadable storage conservatively. If writing fails, remove a stale grant where possible and keep collection off rather than proceeding as if the choice was saved.
An earlier event still finishes uploading after withdrawal
A captured or in-flight event isn't retracted by changing the banner. Gate new actions immediately and define the handling of existing queues and storage separately. Don't claim that this example cancels every pending network operation.
Full code reference
The complete runnable example includes the lockfile. These are the complete application and test files, combined for copying. Keep environment values local.
===== package.json =====
{
"name": "amplitude-react-consent-banner",
"version": "1.0.0",
"private": true,
"type": "module",
"packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
"engines": {
"node": ">=22.12.0",
"pnpm": ">=10.21.0"
},
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "vite build",
"preview": "vite preview --host 127.0.0.1",
"test": "node --test tests/*.test.mjs"
},
"dependencies": {
"@amplitude/unified": "1.2.1",
"react": "19.3.1",
"react-dom": "19.3.1"
},
"devDependencies": {
"vite": "8.3.6"
}
}
===== pnpm-workspace.yaml =====
minimumReleaseAge: 10080
trustPolicy: no-downgrade
===== .gitignore =====
node_modules/
dist/
.env
.env.local
.env.*.local
===== index.html =====
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Consent banner demo</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
===== .env.example =====
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US
===== src/consent.js =====
export const choiceKey = 'build-consent-choice-v1';
export function readChoice(storage) {
try { return storage.getItem(choiceKey) === 'granted' ? 'granted' : 'denied'; }
catch { return 'denied'; }
}
export function writeChoice(storage, choice) {
try { storage.setItem(choiceKey, choice); }
catch {
// Remove a stale grant if saving a new choice fails (for example, quota).
storage.removeItem(choiceKey);
throw new Error('Choice could not be saved. Tracking remains off.');
}
}
export function createConsentController({ initialChoice, persist, loadClient }) {
let choice = initialChoice === 'granted' ? 'granted' : 'denied';
let phase = 'off';
let client;
let pending;
let snapshot = { choice, phase, deviceId: null };
const listeners = new Set();
function publish(error = null) {
snapshot = { choice, phase, error, deviceId: client?.getDeviceId() ?? null };
for (const listener of listeners) listener(snapshot);
}
async function start() {
if (choice !== 'granted') return;
phase = 'starting'; publish();
try {
if (!pending) pending = (async () => {
const loaded = await loadClient();
if (choice !== 'granted') return null;
client = loaded;
await client.initialize();
return client;
})();
const result = await pending;
if (!result) { pending = null; phase = 'off'; publish(); return; }
result.setOptOut(choice !== 'granted');
phase = choice === 'granted' ? 'ready' : 'off'; publish();
} catch (error) {
client?.setOptOut(true); phase = 'error'; publish(error.message);
}
}
return {
getSnapshot: () => snapshot,
subscribe(listener) { listeners.add(listener); listener(snapshot); return () => listeners.delete(listener); },
restore: start,
async grant() {
try { persist('granted'); }
catch (error) { choice = 'denied'; client?.setOptOut(true); phase = 'error'; publish(error.message); return; }
choice = 'granted'; await start();
},
deny() {
choice = 'denied'; client?.setOptOut(true); phase = 'off';
try { persist('denied'); publish(); }
catch (error) { publish(error.message); }
},
async record() {
if (choice !== 'granted' || phase !== 'ready') return false;
const result = await client.track();
return result.code === 200;
},
};
}
===== src/analytics-client.js =====
import * as amplitude from '@amplitude/unified';
let initialization;
export const client = {
initialize() {
if (!initialization) initialization = amplitude.initAll(import.meta.env.VITE_AMPLITUDE_API_KEY.trim(), {
serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
analytics: { optOut: true, autocapture: false, remoteConfig: { fetchRemoteConfig: false } },
sessionReplay: { sampleRate: 0 }, engagement: { skip: true },
});
return initialization;
},
setOptOut: (value) => amplitude.setOptOut(value),
getDeviceId: () => amplitude.getDeviceId(),
track: () => amplitude.track('Consent Demo Action', { surface: 'local_preferences' }).promise,
};
===== src/App.jsx =====
import React, { useEffect, useState } from 'react';
export function App({ controller, configured }) {
const [state, setState] = useState(controller.getSnapshot);
const [message, setMessage] = useState('Choose whether to enable analytics for this demo.');
useEffect(() => controller.subscribe(setState), [controller]);
async function record() {
try { setMessage(await controller.record() ? 'Demo event accepted.' : 'No demo event accepted.'); }
catch { setMessage('The demo event could not be uploaded.'); }
}
return (
<main>
<p className="eyebrow">CONSENT CONTROL DEMO</p><h1>Choose analytics collection</h1>
<p>This first-party demo stores your choice locally. It imports and initializes Amplitude only after a grant, discards actions while off, and keeps replay disabled. Withdrawal stops new actions; it doesn't erase prior SDK storage or retract requests already sent.</p>
{!configured && <p>No test key configured. Tracking stays off.</p>}
<button id="grant" disabled={!configured} onClick={() => controller.grant()}>Allow analytics</button>
<button id="deny" onClick={() => controller.deny()}>Decline or withdraw</button>
<button id="record" disabled={state.phase !== 'ready'} onClick={record}>Record demo action</button>
<p>Choice: <strong id="choice">{state.choice}</strong></p>
<p>Analytics: <strong id="phase">{state.phase}</strong></p>
<p role="status">{state.error ?? message}</p>
<p>Device ID: <code id="device-id">{state.deviceId ?? 'not initialized'}</code></p>
</main>
);
}
===== src/style.css =====
:root { font-family: Helvetica, Arial, sans-serif; color: #000000; background: #F2F4F8; }
body { margin: 0; }
main { max-width: 760px; margin: 40px auto; padding: 32px; background: #FFFFFF; border-radius: 16px; }
h1 { font-size: 36px; }
p { line-height: 1.5; }
.eyebrow { font-size: 12px; letter-spacing: 0.08em; }
nav { display: flex; gap: 20px; flex-wrap: wrap; padding: 16px 0; }
a { color: #0052F2; }
section, aside { border-top: 1px solid #D5D9E0; margin-top: 24px; padding-top: 24px; }
label { display: block; margin-bottom: 8px; }
button, select, [role='button'] { font: inherit; padding: 10px 14px; margin: 0 12px 12px 0; border: 1px solid #000000; border-radius: 6px; color: #000000; background: #FFFFFF; }
button, [role='button'] { cursor: pointer; }
#save-settings { color: #FFFFFF; background: #0052F2; border-color: #0052F2; }
[role='button'] { display: inline-block; }
:focus-visible { outline: 3px solid #0052F2; outline-offset: 3px; }
code { overflow-wrap: anywhere; }
@media (max-width: 800px) { main { margin: 16px; padding: 24px; } }
button:disabled, select:disabled { opacity: 0.6; cursor: wait; }
form { margin-top: 24px; }
===== src/main.jsx =====
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.jsx';
import { createConsentController, readChoice, writeChoice } from './consent.js';
import './style.css';
const configured = Boolean(import.meta.env.VITE_AMPLITUDE_API_KEY?.trim());
const controller = createConsentController({
initialChoice: configured ? readChoice(localStorage) : 'denied',
persist: (choice) => writeChoice(localStorage, choice),
loadClient: async () => (await import('./analytics-client.js')).client,
});
createRoot(document.getElementById('root')).render(<StrictMode><App controller={controller} configured={configured} /></StrictMode>);
if (configured) void controller.restore();
===== tests/consent.test.mjs =====
import test from 'node:test';
import assert from 'node:assert/strict';
import { createConsentController, readChoice, writeChoice, choiceKey } from '../src/consent.js';
test('off actions are discarded, grant initializes once and withdrawal gates new actions', async () => {
let loads = 0, starts = 0, tracks = 0; const optOut = [];
const client = { initialize: async () => { starts++; }, getDeviceId: () => 'demo-device',
setOptOut: (value) => optOut.push(value), track: async () => { tracks++; return { code: 200 }; } };
const control = createConsentController({ initialChoice: 'denied', persist: () => {}, loadClient: async () => { loads++; return client; } });
assert.equal(await control.record(), false); assert.equal(loads, 0);
await control.grant(); assert.equal(await control.record(), true);
control.deny(); assert.equal(await control.record(), false);
await control.grant(); assert.equal(starts, 1); assert.equal(loads, 1); assert.equal(tracks, 1);
assert.deepEqual(optOut, [false, true, false]);
});
test('withdrawal while initialization is pending never enables the completed client', async () => {
let release; let started; const entered = new Promise((r) => { started = r; }); const optOut = [];
const client = { initialize: () => { started(); return new Promise((r) => { release = r; }); },
setOptOut: (value) => optOut.push(value), getDeviceId: () => 'demo-device' };
const control = createConsentController({ initialChoice: 'denied', persist: () => {}, loadClient: async () => client });
const granting = control.grant(); await entered; control.deny(); release(); await granting;
assert.equal(control.getSnapshot().phase, 'off'); assert.ok(optOut.every(Boolean));
});
test('declining during client import prevents initialization; malformed storage stays off', async () => {
let release; let starts = 0;
const control = createConsentController({ initialChoice: 'denied', persist: () => {},
loadClient: () => new Promise((r) => { release = r; }) });
const granting = control.grant(); control.deny(); release({ initialize: () => { starts++; } }); await granting;
assert.equal(starts, 0); assert.equal(readChoice({ getItem: () => 'unknown' }), 'denied');
});
test('storage-write failure removes a stale grant and does not enable collection', async () => {
let removed;
const storage = { setItem: () => { throw new Error('Quota'); }, removeItem: (key) => { removed = key; } };
assert.throws(() => writeChoice(storage, 'denied'), /Tracking remains off/); assert.equal(removed, choiceKey);
});
test('initialization failure keeps tracking off without changing the persisted choice', async () => {
const persisted = []; const optOut = [];
const control = createConsentController({ initialChoice: 'denied', persist: (value) => persisted.push(value),
loadClient: async () => ({ initialize: async () => { throw new Error('Startup failed'); },
setOptOut: (value) => optOut.push(value), getDeviceId: () => undefined }) });
await control.grant();
assert.equal(control.getSnapshot().choice, 'granted');
assert.equal(control.getSnapshot().phase, 'error');
assert.equal(await control.record(), false);
assert.deepEqual(persisted, ['granted']); assert.deepEqual(optOut, [true]);
});Hand it to your agent
Use this prompt to adapt the example to an existing application.
Use https://amplitude.com/build/react-consent-banner and its linked source.
Inspect the current SDK entry point and application flow first. Merge into existing
files; preserve auth, consent, routes, and other instrumentation. Fetch current
Amplitude docs for the installed SDK. Keep the ingestion key in the existing
environment mechanism and never add server secrets to browser code.
Defer SDK import and initialization until the application's current grant. Gate
all relevant application tracking paths so off-state actions aren't queued for
later. Initialize opted out with automatic capture disabled, then enable only
after checking the latest choice. A withdrawal during import/startup must not
be overwritten by stale async completion. Persist choices and fail closed on
storage/startup errors; preserve the distinction between selected consent and
SDK readiness. Keep withdrawal available while a record/upload is pending.
Do not promise deletion of prior storage/history or cancellation of in-flight
requests. Verify each additional product/destination separately.
Test blank-key startup and failure paths as well as success. Confirm real SDK
uploads and processed data separately from local tests. Report changed files and
remaining coverage limits.What this unlocks
Product analytics can analyze the deliberately collected Consent Demo Action events.
Session replay can be introduced after its own capture, masking, and consent behavior is configured and tested.
Feature flags can be integrated with the application's approved identity and collection lifecycle separately.
Guides and surveys can collect feedback when their own startup and consent behavior is configured.
Frequently asked questions
Does opt-out delete stored cookies and events?
Opt-out is an event-collection control. This example doesn't erase prior SDK storage, delete stored Amplitude history, or retract sent requests. Treat those as separate operations with their own requirements.
Do declined actions get sent after a later grant?
The controller returns before calling the SDK while off, so those actions aren't queued by this example. Keep every relevant application tracking path behind the same decision.
Does this cover session replay and other products?
Replay stays disabled and guides and surveys are skipped here. Implement and verify each product's own consent and storage behavior before enabling it. This demo doesn't claim that one analytics setting controls every product.
Next steps
Reference docs
Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.