Chris Tam · Last updated 13 November 2026
I'll use product analytics in a React form that saves preferences in browser storage. Its delay and failure switch simulate a request; there is no backend or email service.
In this tutorial, I'll add a custom save event alongside autocapture and verify failed attempts. The React autocapture tutorial covers filters; this example includes its own setup.
What you'll build
A React form that autocaptures [Amplitude] Element Clicked on its save button and sends Settings Saved after preferences are stored successfully. The custom event includes settings_section, theme, digest_frequency, and save_source. Failed saves keep the old values and send no success event.
Prerequisites
- Node.js 22.12 or later, with Corepack available for pnpm.
- An Amplitude test project and its ingestion API key. In Organization settings, open API Keys and select the test project.
- Your project's data center, US or EU.
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 React app
I'll create the app directly with Vite and use the Browser Unified SDK installation. The files below pin the versions used for this example.
mkdir react-custom-events
cd react-custom-events
mkdir -p src tests
corepack enable{
"name": "amplitude-react-custom-events",
"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>Workspace preferences 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.localSet VITE_AMPLITUDE_API_KEY in .env.local to the test project's API key. Keep VITE_AMPLITUDE_SERVER_ZONE=US, or use EU for an EU project. Vite exposes VITE_ variables in the browser bundle. A project API key is public and has the minimum scope needed to ingest data; a server secret key stays out of browser code.
For an existing app, merge the analytics changes into its current initialization and save handler. Keep its routes, authentication, consent handling, and other instrumentation. Use the existing SDK entry point rather than adding another instance.
2. Initialize Amplitude and define the custom event
I'll autocapture only the save button and use a separate track call for the completed save. The custom-event guide recommends sending business events where the action completes.
import * as amplitude from '@amplitude/unified';
let ready;
let enabled = false;
export function initializeAnalytics() {
const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
if (!apiKey) return Promise.resolve({ status: 'disabled', deviceId: null });
if (!ready) {
ready = amplitude.initAll(apiKey, {
serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
analytics: {
remoteConfig: { fetchRemoteConfig: false },
autocapture: {
attribution: false,
pageViews: false,
sessions: false,
formInteractions: false,
fileDownloads: false,
pageUrlEnrichment: false,
frustrationInteractions: false,
networkTracking: false,
webVitals: false,
performanceTracking: false,
elementInteractions: {
cssSelectorAllowlist: ['#save-settings'],
actionClickAllowlist: [],
viewportContentUpdated: { enabled: false },
},
},
},
sessionReplay: { sampleRate: 0 },
engagement: { skip: true },
}).then(() => {
enabled = true;
return { status: 'ready', deviceId: amplitude.getDeviceId() };
}).catch((error) => {
console.error('Amplitude initialization failed', error);
return { status: 'error', deviceId: null };
});
}
return ready;
}
export function trackSettingsSaved(properties) {
if (!enabled) return;
// Upload completion doesn't control whether the preference save succeeded.
void amplitude.track('Settings Saved', properties).promise.then((result) => {
if (result.code !== 200) console.warn('Settings Saved upload:', result.message);
}).catch((error) => console.warn('Settings Saved upload failed', error));
}initAll initializes the products bundled in Unified. Here, replay has a sample rate of zero and guides and surveys are skipped. The analytics configuration enables selected element interactions and explicitly disables other autocapture streams, including the supplemental viewport stream. It also disables analytics remote configuration fetching so the local capture choices apply. In an existing application, agree on those settings with the team that owns analytics.
The element-interaction options replace the default selector list with #save-settings. An empty actionClickAllowlist removes the extra action-click selectors. The form's selects and failure checkbox aren't selected by this example.
trackSettingsSaved sends the event through the same SDK instance. Its upload result is logged separately from the save result. A save stays successful if analytics can't upload; the app doesn't repeat the business operation to repair telemetry.
MCP. Ask your coding agent to read the current tracking and autocapture options through the Docs MCP server before editing an existing setup. That server reads public documentation; it doesn't inspect your project's event taxonomy.
3. Track the completed save
I'll persist the validated preferences before calling trackSettingsSaved. Only the two allowed settings are copied into the saved object, and the event properties are listed explicitly.
export const storageKey = 'build-custom-events-settings-v1';
export const defaultSettings = { theme: 'light', digest: 'weekly' };
export function normalizeSettings(value) {
if (!['light', 'dark'].includes(value?.theme)
|| !['daily', 'weekly'].includes(value?.digest)) {
throw new Error('Choose a supported theme and digest frequency.');
}
return { theme: value.theme, digest: value.digest };
}
export function loadSettings(storage) {
try {
const value = storage.getItem(storageKey);
return value ? normalizeSettings(JSON.parse(value)) : { ...defaultSettings };
} catch {
return { ...defaultSettings };
}
}
export function createSettingsSaver({ persistSettings, trackSaved, pause }) {
let saving = false;
return async function saveSettings(value, { fail = false } = {}) {
if (saving) return { status: 'busy' };
saving = true;
try {
const settings = normalizeSettings(value);
await pause();
if (fail) throw new Error('Demo failure. Your saved preferences did not change.');
await persistSettings(settings);
try {
trackSaved({
settings_section: 'workspace',
theme: settings.theme,
digest_frequency: settings.digest,
save_source: 'preferences_form',
});
} catch (error) {
console.warn('Preferences saved; analytics could not be queued', error);
}
return { status: 'saved', settings };
} finally {
saving = false;
}
};
}The failure switch throws before persistence and tracking. A storage error also exits before the event. The saving guard prevents overlapping calls within this saver, and finally releases it after either outcome.
Why. Put the business event at the completion point. In this local example, that means after localStorage.setItem succeeds. With a real save API, use its confirmed result instead, or instrument the authoritative outcome on the server. A button-click event alone doesn't establish that a save completed.
The properties describe this event instance. Keep the event name stable as Settings Saved; use theme and digest_frequency for the chosen values. This form accepts only fixed categories and sends no free-text values in its custom event.
4. Connect the React form
I'll keep tracking in the save path rather than a React effect. A ref guards pending form submissions immediately, while state disables the controls and shows the saved result.
import React, { useRef, useState } from 'react';
import { createSettingsSaver, loadSettings, storageKey } from './settings.js';
import { trackSettingsSaved } from './analytics.js';
export function App({ analytics }) {
const [preferences, setPreferences] = useState(() => loadSettings(localStorage));
const [saved, setSaved] = useState(preferences);
const [failNext, setFailNext] = useState(false);
const [saving, setSaving] = useState(false);
const pending = useRef(false);
const [message, setMessage] = useState('Change a preference, then save.');
const [saveSettings] = useState(() => createSettingsSaver({
persistSettings: (settings) => localStorage.setItem(storageKey, JSON.stringify(settings)),
trackSaved: trackSettingsSaved,
pause: () => new Promise((resolve) => setTimeout(resolve, 650)),
}));
async function handleSubmit(event) {
event.preventDefault();
if (pending.current) return;
pending.current = true;
setSaving(true);
const fail = failNext;
setFailNext(false);
setMessage('Saving...');
try {
const result = await saveSettings(preferences, { fail });
if (result.status === 'saved') {
setSaved(result.settings);
setMessage('Preferences saved in this browser.');
}
} catch (error) {
setMessage(error.message);
} finally {
pending.current = false;
setSaving(false);
}
}
return (
<main>
<p className="eyebrow">WORKSPACE DEMO</p>
<h1>Workspace preferences</h1>
<p>This demo saves to this browser's local storage. The delay and failure switch simulate a save request; no backend or email service is involved.</p>
<form onSubmit={handleSubmit} aria-label="Workspace preferences">
<label htmlFor="theme">Theme</label>
<select id="theme" value={preferences.theme} disabled={saving}
onChange={(event) => setPreferences({ ...preferences, theme: event.target.value })}>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<label htmlFor="digest">Digest frequency</label>
<select id="digest" value={preferences.digest} disabled={saving}
onChange={(event) => setPreferences({ ...preferences, digest: event.target.value })}>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
</select>
<label>
<input id="fail-next" type="checkbox" checked={failNext} disabled={saving}
onChange={(event) => setFailNext(event.target.checked)} /> Fail the next save
</label>
<button id="save-settings" type="submit" disabled={saving}>
{saving ? 'Saving...' : 'Save preferences'}
</button>
<p role="status">{message}</p>
</form>
<section aria-label="Saved preferences">
<h2>Saved preferences</h2>
<p id="saved-values">Theme: {saved.theme}; digest: {saved.digest}</p>
</section>
<aside aria-label="Analytics status">
<p>Analytics: <strong id="analytics-status">{analytics.status}</strong></p>
<p>Device ID: <code id="device-id">{analytics.deviceId ?? 'not initialized'}</code></p>
</aside>
</main>
);
}The form snapshots the preferences for the pending save. Its failure switch resets after each attempt so the next attempt can succeed. Separate completed submissions each produce a new save event, even when the values are unchanged.
: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; }5. Mount and run the app
I'll initialize analytics before mounting the form. React Strict Mode remains enabled, and no mount effect fires a business event.
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { initializeAnalytics } from './analytics.js';
import { App } from './App.jsx';
import './style.css';
initializeAnalytics().then((analytics) => {
createRoot(document.getElementById('root')).render(
<StrictMode><App analytics={analytics} /></StrictMode>,
);
});Add tests for persistence order, overlapping submissions, failure, and the separation between analytics and application success.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createSettingsSaver, loadSettings, storageKey } from '../src/settings.js';
const value = { theme: 'dark', digest: 'daily', customerEmail: 'do-not-send@example.test' };
test('save commits before one custom event and projects only allowed properties', async () => {
const order = [];
const save = createSettingsSaver({ pause: async () => {},
persistSettings: async (settings) => { order.push(['persist', settings]); },
trackSaved: (properties) => { order.push(['event', properties]); },
});
assert.deepEqual(await save(value), { status: 'saved', settings: { theme: 'dark', digest: 'daily' } });
assert.deepEqual(order, [
['persist', { theme: 'dark', digest: 'daily' }],
['event', { settings_section: 'workspace', theme: 'dark', digest_frequency: 'daily', save_source: 'preferences_form' }],
]);
});
test('simulated and storage failures emit no success event; a later retry works', async () => {
const events = [];
let storageFails = true;
const save = createSettingsSaver({ pause: async () => {},
persistSettings: () => { if (storageFails) throw new Error('Storage unavailable'); },
trackSaved: (p) => events.push(p),
});
await assert.rejects(save(value, { fail: true }), /Demo failure/);
await assert.rejects(save(value), /Storage unavailable/);
assert.equal(events.length, 0);
storageFails = false;
await save(value);
assert.equal(events.length, 1);
});
test('overlapping submissions share a busy guard, separate completed saves remain separate', async () => {
let release;
let events = 0;
const save = createSettingsSaver({ pause: () => new Promise((resolve) => { release = resolve; }),
persistSettings: () => {}, trackSaved: () => { events += 1; },
});
const first = save(value);
assert.deepEqual(await save(value), { status: 'busy' });
release(); await first;
assert.equal(events, 1);
const next = save(value); release(); await next;
assert.equal(events, 2);
});
test('telemetry error does not turn a committed preference save into a failed save', async (t) => {
t.mock.method(console, 'warn', () => {});
let committed = false;
const save = createSettingsSaver({ pause: async () => {},
persistSettings: () => { committed = true; },
trackSaved: () => { throw new Error('Telemetry unavailable'); },
});
assert.equal((await save(value)).status, 'saved');
assert.equal(committed, true);
});
test('invalid input never commits; reload handles missing and malformed storage', async () => {
let writes = 0;
const save = createSettingsSaver({ pause: async () => {}, persistSettings: () => { writes += 1; }, trackSaved: () => {} });
await assert.rejects(save({ theme: 'private free text', digest: 'daily' }), /supported/);
assert.equal(writes, 0);
assert.deepEqual(loadSettings({ getItem: () => '{broken' }), { theme: 'light', digest: 'weekly' });
assert.deepEqual(loadSettings({ getItem: (key) => key === storageKey ? JSON.stringify(value) : null }), { theme: 'dark', digest: 'daily' });
});pnpm test
pnpm build
pnpm devOpen the local URL printed by Vite. With a blank key, the app reports analytics as disabled and still saves preferences. With the test-project key, it displays the device ID for the verification below.
Verify it worked
Test the complete sequence in one browser, then inspect that device's events in Amplitude.
- Local app: Choose Dark and Daily, then click Save preferences once. Confirm the saved values change. Choose Light and Weekly, enable Fail the next save, and click again. Confirm the error leaves Dark and Daily saved. Retry successfully, then reload to confirm Light and Weekly persist.
- Network: Confirm that analytics upload requests leave the browser and return HTTP 200. This confirms request acceptance; inspect event contents using Instrumentation Explorer rather than relying on the Network payload view, since the SDK can compress requests.
- Instrumentation Explorer: In the extension's Events tab, find the button's
[Amplitude] Element Clickedand the followingSettings Saved. Inspect the custom event'ssettings_section: workspace,theme,digest_frequency, andsave_source: preferences_form. Compare the device IDs. The failed attempt should have a click without aSettings Saved. - User Lookup: Search for the displayed device ID, open Activity, and enable Live event updates. Events normally populate in ten seconds to one minute. Open the two successful
Settings Savedevents and confirm their properties. Match the failed attempt's timestamp to its click and verify there is no success event for that attempt.
Try clicking again while Saving... is displayed. The pending guard prevents another save from starting. Reloading by itself doesn't call trackSettingsSaved. An earlier event history may contain other saves, so compare the timestamps and the number of attempts from this run.
Troubleshooting
Every save appears twice
Keep one trackSettingsSaved call at the completion point. Remove a second call from a button handler, effect, or API wrapper, and check that the page initializes one Amplitude instance. An autocaptured click and Settings Saved describe different stages; compare event names before treating the pair as a duplicate.
A failed save has a success event
Place the custom event after the persistence operation resolves. Keep the track call out of finally, which also runs after failure. Match timestamps so a previous successful save isn't confused with the failed attempt.
The saved UI updates but Amplitude has no custom event
Confirm analytics is ready, the project key and data center match, and browser policies or blockers permit uploads. Inspect the console for the Settings Saved upload warning. The UI confirms local persistence independently of telemetry.
Unexpected autocapture events appear
Check that the running bundle includes the explicit feature settings and remoteConfig.fetchRemoteConfig: false. Keep viewportContentUpdated.enabled: false for this example. Review any existing project-owned policy before changing it.
Preferences return to defaults after reload
Local storage belongs to an origin. Use the same scheme, host, and port; private browsing or storage restrictions can change persistence. A malformed stored value falls back to the defaults. Confirm the save completed before reloading.
Full code reference
The complete runnable example includes the lockfile and tests. These are the same complete files used above, combined for copying; keep your environment values local.
===== package.json =====
{
"name": "amplitude-react-custom-events",
"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>Workspace preferences 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/analytics.js =====
import * as amplitude from '@amplitude/unified';
let ready;
let enabled = false;
export function initializeAnalytics() {
const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
if (!apiKey) return Promise.resolve({ status: 'disabled', deviceId: null });
if (!ready) {
ready = amplitude.initAll(apiKey, {
serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
analytics: {
remoteConfig: { fetchRemoteConfig: false },
autocapture: {
attribution: false,
pageViews: false,
sessions: false,
formInteractions: false,
fileDownloads: false,
pageUrlEnrichment: false,
frustrationInteractions: false,
networkTracking: false,
webVitals: false,
performanceTracking: false,
elementInteractions: {
cssSelectorAllowlist: ['#save-settings'],
actionClickAllowlist: [],
viewportContentUpdated: { enabled: false },
},
},
},
sessionReplay: { sampleRate: 0 },
engagement: { skip: true },
}).then(() => {
enabled = true;
return { status: 'ready', deviceId: amplitude.getDeviceId() };
}).catch((error) => {
console.error('Amplitude initialization failed', error);
return { status: 'error', deviceId: null };
});
}
return ready;
}
export function trackSettingsSaved(properties) {
if (!enabled) return;
// Upload completion doesn't control whether the preference save succeeded.
void amplitude.track('Settings Saved', properties).promise.then((result) => {
if (result.code !== 200) console.warn('Settings Saved upload:', result.message);
}).catch((error) => console.warn('Settings Saved upload failed', error));
}
===== src/settings.js =====
export const storageKey = 'build-custom-events-settings-v1';
export const defaultSettings = { theme: 'light', digest: 'weekly' };
export function normalizeSettings(value) {
if (!['light', 'dark'].includes(value?.theme)
|| !['daily', 'weekly'].includes(value?.digest)) {
throw new Error('Choose a supported theme and digest frequency.');
}
return { theme: value.theme, digest: value.digest };
}
export function loadSettings(storage) {
try {
const value = storage.getItem(storageKey);
return value ? normalizeSettings(JSON.parse(value)) : { ...defaultSettings };
} catch {
return { ...defaultSettings };
}
}
export function createSettingsSaver({ persistSettings, trackSaved, pause }) {
let saving = false;
return async function saveSettings(value, { fail = false } = {}) {
if (saving) return { status: 'busy' };
saving = true;
try {
const settings = normalizeSettings(value);
await pause();
if (fail) throw new Error('Demo failure. Your saved preferences did not change.');
await persistSettings(settings);
try {
trackSaved({
settings_section: 'workspace',
theme: settings.theme,
digest_frequency: settings.digest,
save_source: 'preferences_form',
});
} catch (error) {
console.warn('Preferences saved; analytics could not be queued', error);
}
return { status: 'saved', settings };
} finally {
saving = false;
}
};
}
===== src/App.jsx =====
import React, { useRef, useState } from 'react';
import { createSettingsSaver, loadSettings, storageKey } from './settings.js';
import { trackSettingsSaved } from './analytics.js';
export function App({ analytics }) {
const [preferences, setPreferences] = useState(() => loadSettings(localStorage));
const [saved, setSaved] = useState(preferences);
const [failNext, setFailNext] = useState(false);
const [saving, setSaving] = useState(false);
const pending = useRef(false);
const [message, setMessage] = useState('Change a preference, then save.');
const [saveSettings] = useState(() => createSettingsSaver({
persistSettings: (settings) => localStorage.setItem(storageKey, JSON.stringify(settings)),
trackSaved: trackSettingsSaved,
pause: () => new Promise((resolve) => setTimeout(resolve, 650)),
}));
async function handleSubmit(event) {
event.preventDefault();
if (pending.current) return;
pending.current = true;
setSaving(true);
const fail = failNext;
setFailNext(false);
setMessage('Saving...');
try {
const result = await saveSettings(preferences, { fail });
if (result.status === 'saved') {
setSaved(result.settings);
setMessage('Preferences saved in this browser.');
}
} catch (error) {
setMessage(error.message);
} finally {
pending.current = false;
setSaving(false);
}
}
return (
<main>
<p className="eyebrow">WORKSPACE DEMO</p>
<h1>Workspace preferences</h1>
<p>This demo saves to this browser's local storage. The delay and failure switch simulate a save request; no backend or email service is involved.</p>
<form onSubmit={handleSubmit} aria-label="Workspace preferences">
<label htmlFor="theme">Theme</label>
<select id="theme" value={preferences.theme} disabled={saving}
onChange={(event) => setPreferences({ ...preferences, theme: event.target.value })}>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<label htmlFor="digest">Digest frequency</label>
<select id="digest" value={preferences.digest} disabled={saving}
onChange={(event) => setPreferences({ ...preferences, digest: event.target.value })}>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
</select>
<label>
<input id="fail-next" type="checkbox" checked={failNext} disabled={saving}
onChange={(event) => setFailNext(event.target.checked)} /> Fail the next save
</label>
<button id="save-settings" type="submit" disabled={saving}>
{saving ? 'Saving...' : 'Save preferences'}
</button>
<p role="status">{message}</p>
</form>
<section aria-label="Saved preferences">
<h2>Saved preferences</h2>
<p id="saved-values">Theme: {saved.theme}; digest: {saved.digest}</p>
</section>
<aside aria-label="Analytics status">
<p>Analytics: <strong id="analytics-status">{analytics.status}</strong></p>
<p>Device ID: <code id="device-id">{analytics.deviceId ?? 'not initialized'}</code></p>
</aside>
</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 { initializeAnalytics } from './analytics.js';
import { App } from './App.jsx';
import './style.css';
initializeAnalytics().then((analytics) => {
createRoot(document.getElementById('root')).render(
<StrictMode><App analytics={analytics} /></StrictMode>,
);
});
===== tests/settings.test.mjs =====
import test from 'node:test';
import assert from 'node:assert/strict';
import { createSettingsSaver, loadSettings, storageKey } from '../src/settings.js';
const value = { theme: 'dark', digest: 'daily', customerEmail: 'do-not-send@example.test' };
test('save commits before one custom event and projects only allowed properties', async () => {
const order = [];
const save = createSettingsSaver({ pause: async () => {},
persistSettings: async (settings) => { order.push(['persist', settings]); },
trackSaved: (properties) => { order.push(['event', properties]); },
});
assert.deepEqual(await save(value), { status: 'saved', settings: { theme: 'dark', digest: 'daily' } });
assert.deepEqual(order, [
['persist', { theme: 'dark', digest: 'daily' }],
['event', { settings_section: 'workspace', theme: 'dark', digest_frequency: 'daily', save_source: 'preferences_form' }],
]);
});
test('simulated and storage failures emit no success event; a later retry works', async () => {
const events = [];
let storageFails = true;
const save = createSettingsSaver({ pause: async () => {},
persistSettings: () => { if (storageFails) throw new Error('Storage unavailable'); },
trackSaved: (p) => events.push(p),
});
await assert.rejects(save(value, { fail: true }), /Demo failure/);
await assert.rejects(save(value), /Storage unavailable/);
assert.equal(events.length, 0);
storageFails = false;
await save(value);
assert.equal(events.length, 1);
});
test('overlapping submissions share a busy guard, separate completed saves remain separate', async () => {
let release;
let events = 0;
const save = createSettingsSaver({ pause: () => new Promise((resolve) => { release = resolve; }),
persistSettings: () => {}, trackSaved: () => { events += 1; },
});
const first = save(value);
assert.deepEqual(await save(value), { status: 'busy' });
release(); await first;
assert.equal(events, 1);
const next = save(value); release(); await next;
assert.equal(events, 2);
});
test('telemetry error does not turn a committed preference save into a failed save', async (t) => {
t.mock.method(console, 'warn', () => {});
let committed = false;
const save = createSettingsSaver({ pause: async () => {},
persistSettings: () => { committed = true; },
trackSaved: () => { throw new Error('Telemetry unavailable'); },
});
assert.equal((await save(value)).status, 'saved');
assert.equal(committed, true);
});
test('invalid input never commits; reload handles missing and malformed storage', async () => {
let writes = 0;
const save = createSettingsSaver({ pause: async () => {}, persistSettings: () => { writes += 1; }, trackSaved: () => {} });
await assert.rejects(save({ theme: 'private free text', digest: 'daily' }), /supported/);
assert.equal(writes, 0);
assert.deepEqual(loadSettings({ getItem: () => '{broken' }), { theme: 'light', digest: 'weekly' });
assert.deepEqual(loadSettings({ getItem: (key) => key === storageKey ? JSON.stringify(value) : null }), { theme: 'dark', digest: 'daily' });
});Hand it to your agent
Use this prompt to adapt the example to your application.
Use https://amplitude.com/build/react-custom-events and its linked source as a reference.
Inspect the existing Amplitude initialization and save flow first. Merge changes;
preserve authentication, consent, routing, and other instrumentation. Keep one SDK
entry point and fetch current SDK docs for the installed version.
Autocapture the intended save-button interaction. Add one Settings Saved track call
after the save's confirmed completion. Use the existing event taxonomy if it has
an equivalent business event. Keep event properties explicit and categorical;
do not spread form data or add customer text, credentials, or secrets.
Keep tracking out of render and mount effects. Guard overlapping submissions.
A failed persistence operation must emit no success event. Analytics failure must
not trigger a repeat save or turn a committed save into an application error.
Do not promise exactly-once delivery across reloads, tabs, or network retries.
Exercise success, failure, retry, rapid submissions, reload, and missing-key startup.
Check processed events and properties under the expected identity separately from
local assertions and HTTP acceptance. Report changed files and verification limits.What this unlocks
Product analytics can compare Settings Saved by theme or digest_frequency, while the captured click helps distinguish attempts from completions.
Session replay can add visual context to the save experience when enabled separately with the right privacy settings.
Feature flags can vary the preferences form while a stable Settings Saved event measures completed saves.
Guides and surveys can collect feedback on that form when configured separately. This example skips their initialization.
Frequently asked questions
Do custom events replace autocapture?
They can coexist in the same SDK instance. This example uses autocapture for a button interaction and a custom event for the completed save with business context. Avoid adding a manual event that merely repeats the same click.
Can I use visual labeling for this?
Visual labeling can name a captured interaction. This recipe uses code because its event depends on a persistence result and application properties. Naming the click doesn't make it a confirmed save.
Does this guarantee exactly-once delivery?
No. The guards prevent overlapping submissions in this mounted form and saver. Separate completed saves each emit an event. Cross-tab operations, reload recovery, network retries, and server idempotency need their own design.
Should I use a user property for the saved theme?
This tutorial records the theme at the moment of each save as an event property. Maintaining the person's current theme as a user property is a separate operation. Keep this event history even if you also maintain a current profile value.
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.