Chris Tam · Last updated 12 November 2026
Autocapture in product analytics collects browser interactions without a tracking call on every control. I'll use a small workspace-settings demo with settings, billing, admin, and welcome pages. Its save button changes local display state; it doesn't save to a backend or charge a card.
In this tutorial, I'll mark the controls to capture, limit them to selected pages, and check the resulting events. The React analytics tutorial covers the broader installation; this example includes its own complete setup.
What you'll build
A React app that captures [Amplitude] Element Clicked for its save button and [Amplitude] Element Changed for its plan dropdown on /app/settings/ and /app/billing/. It also captures page views on those pages. Help controls, /app/admin/, and /welcome/ are excluded from these streams. The save event includes static action and area attributes.
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. Use the project API key, not a secret key.
- 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 a small Vite app directly so every file below has a defined place. This uses Amplitude's recommended Browser Unified SDK installation.
mkdir react-autocapture
cd react-autocapture
mkdir -p src tests
corepack enableThe example pins the versions used here. Add these files before installing dependencies.
{
"name": "amplitude-react-autocapture",
"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 settings 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 your test project's key. Keep VITE_AMPLITUDE_SERVER_ZONE=US, or change it to EU for an EU project. Vite exposes VITE_ variables to browser code. A project API key is public and its scope is limited to the minimum needed to ingest data; a server secret key does not belong here.
For an existing app, merge the configuration into your current Amplitude initialization module. Keep your authentication, routes, and other instrumentation. Don't initialize another SDK instance or replace the app's entry file with this demo.
2. Define the capture policy
Element filters and page-view filters need separate rules. I'll capture marked elements on /app/ pages, exclude the /app/admin branch, and apply the same path boundary to page views.
const applicationUrl = /^https?:\/\/[^/]+\/app\//;
const adminUrl = /^https?:\/\/[^/]+\/app\/admin(?:\/|$)/;
export function isMeasuredPath(pathname) {
return pathname.startsWith('/app/') && !/^\/app\/admin(?:\/|$)/.test(pathname);
}
export const analyticsOptions = {
// Keep this tutorial's local policy authoritative for analytics autocapture.
remoteConfig: { fetchRemoteConfig: false },
autocapture: {
attribution: false,
sessions: false,
formInteractions: false,
fileDownloads: false,
pageUrlEnrichment: false,
frustrationInteractions: false,
networkTracking: false,
webVitals: false,
performanceTracking: false,
pageViews: {
trackOn: () => isMeasuredPath(window.location.pathname),
trackHistoryChanges: 'pathOnly',
},
elementInteractions: {
cssSelectorAllowlist: ['[data-analytics-action]'],
actionClickAllowlist: [],
pageUrlAllowlist: [applicationUrl],
pageUrlExcludelist: [adminUrl],
dataAttributePrefix: 'data-amp-track-',
viewportContentUpdated: { enabled: false },
},
},
};The element-interaction options make three details worth keeping explicit:
cssSelectorAllowlistreplaces the default selector list. Only controls withdata-analytics-actionqualify in this example.actionClickAllowlist: []removes the additional path that captures clicks ondiv,span, and heading elements when they change the DOM or navigate. An unmarked custom help control stays outside the selected set.pageUrlExcludelistwins overpageUrlAllowlist. Admin pages are excluded even though they are under/app/.
viewportContentUpdated is a separate element-interaction option. I'll disable it here because this recipe focuses on clicks and changes rather than the supplemental viewport exposure stream. Its setting is documented in the configuration reference.
The page-view trackOn predicate uses the pathname; the element lists match the full URL. trackHistoryChanges: 'pathOnly' ignores query-only or hash-only URL changes. The demo uses ordinary links that load a new page; the SDK also supports client-side history navigation.
I turn off the other autocapture categories to keep the expected result small. In an existing application, preserve categories you deliberately use and review their policies separately. These element filters do not govern your explicit track() calls or other products.
Why. Analytics remote configuration normally overrides local feature settings. analytics.remoteConfig.fetchRemoteConfig: false makes this example's analytics configuration authoritative without changing the shared project settings. It doesn't turn off configuration for every product bundled in Unified.
3. Initialize Amplitude once
I'll initialize before rendering the controls and keep the initialization promise in one module. A missing key leaves the demo usable with analytics disabled.
import * as amplitude from '@amplitude/unified';
import { analyticsOptions } from './capture-policy.js';
let ready;
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: analyticsOptions,
sessionReplay: { sampleRate: 0 },
engagement: { skip: true },
}).then(() => ({ status: 'ready', deviceId: amplitude.getDeviceId() }))
.catch((error) => {
console.error('Amplitude initialization failed', error);
return { status: 'error', deviceId: null };
});
}
return ready;
}The Unified SDK takes serverZone at the top level and Browser SDK options inside analytics. It includes analytics, session replay, experimentation, and guides and surveys. This example sets the local replay sample rate to zero and skips guides and surveys. It doesn't fetch any experiment flags. The Unified configuration guide explains each product block.
ready describes SDK initialization, not proof that Amplitude received an event. I'll check delivery separately in Verify it worked.
4. Add the demo controls
I'll mark the save button and dropdown, then leave the help controls unmarked. The same controls appear on all four pages so the page filters can be tested independently of the element selectors.
import React, { useState } from 'react';
export function App({ analytics }) {
const [message, setMessage] = useState('No changes yet.');
const [helpOpen, setHelpOpen] = useState(false);
const path = window.location.pathname;
const heading = path === '/app/billing/' ? 'Billing preferences'
: path === '/app/admin/' ? 'Admin preview'
: path === '/app/settings/' ? 'Workspace settings' : 'Welcome';
return (
<main>
<p className="eyebrow">WORKSPACE DEMO</p>
<h1>{heading}</h1>
<p>This demo changes local display state. It does not save settings or charge a card.</p>
<nav aria-label="Demo pages">
<a href="/app/settings/">Settings</a>
<a href="/app/billing/">Billing</a>
<a href="/app/admin/">Admin</a>
<a href="/welcome/">Welcome</a>
</nav>
<section aria-label="Workspace controls">
<label htmlFor="plan">Preview plan</label>
<select id="plan" defaultValue="starter" data-analytics-action="plan">
<option value="starter">Starter</option>
<option value="pro">Pro</option>
</select>
<button id="save" data-analytics-action="save"
data-amp-track-action="settings_saved" data-amp-track-area="workspace"
onClick={() => setMessage('Saved in this tab.')}>
<span>Save preferences</span>
</button>
<button id="help" data-amp-default-track=""
onClick={() => setHelpOpen((value) => !value)}>Toggle help</button>
<div id="help-panel" role="button" tabIndex={0}
onClick={() => setHelpOpen((value) => !value)}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
setHelpOpen((value) => !value);
}
}}>More help</div>
{helpOpen && <p>Changes apply only to this demo tab.</p>}
<p role="status">{message}</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>
);
}: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 { 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; } }data-analytics-action is the selector marker I chose for this app. It has no built-in Amplitude behavior; the selector in the configuration gives it meaning.
On the save button, data-amp-track-action and data-amp-track-area intentionally add the static values settings_saved and workspace. With the configured prefix, they appear inside [Amplitude] Element Attributes as action and area. These describe the demo control; they don't prove a backend save succeeded.
Keep these attributes free of names, emails, tokens, and other sensitive values. Explicitly added attributes are intentional event data. The autocapture privacy documentation explains the handling of displayed text and attributes. Element allowlists are a capture policy, not a substitute for consent or a complete data-privacy review.
The help button includes data-amp-default-track as a test case. Replacing the default selector list means that marker alone doesn't qualify it under this example's policy. The custom More help element also changes the page but remains unselected.
MCP. If your coding agent is adapting these selectors, give it access to the Docs MCP server so it can look up current option names. Keep the existing app's initialization and instrumentation when merging the changes.
5. Mount and run the app
I'll mount React after the SDK initialization attempt completes. Initialization happens outside React, so development Strict Mode doesn't run it as a repeated component effect.
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { initializeAnalytics } from './analytics.js';
import { App } from './App.jsx';
import './style.css';
// Initialize outside React so development Strict Mode doesn't initialize twice.
initializeAnalytics().then((analytics) => {
createRoot(document.getElementById('root')).render(
<StrictMode><App analytics={analytics} /></StrictMode>,
);
});These small tests check URL boundaries, including lookalike paths and an admin descendant. They test application policy; the browser and Amplitude checks below test SDK behavior.
import test from 'node:test';
import assert from 'node:assert/strict';
import { analyticsOptions, isMeasuredPath } from '../src/capture-policy.js';
test('path rules separate the application boundary from lookalike paths', () => {
for (const path of ['/app/settings/', '/app/billing/', '/app/administration/']) {
assert.equal(isMeasuredPath(path), true, path);
}
for (const path of ['/welcome/', '/application/settings/', '/app', '/app/admin', '/app/admin/users/']) {
assert.equal(isMeasuredPath(path), false, path);
}
});
test('element URL policy agrees with page policy on normal and excluded fixtures', () => {
const { pageUrlAllowlist: allow, pageUrlExcludelist: deny } = analyticsOptions.autocapture.elementInteractions;
for (const origin of ['http://localhost:5173', 'https://example.com']) {
for (const path of ['/app/settings/', '/app/billing/', '/app/admin/', '/app/admin/users/', '/welcome/']) {
const url = origin + path;
assert.equal(allow.some((r) => r.test(url)) && !deny.some((r) => r.test(url)), isMeasuredPath(path), url);
}
}
});pnpm test
pnpm devOpen http://127.0.0.1:5173/app/settings/. The app shows its initialization status and anonymous device ID. If Vite reports a different port, use that port for every test page.
Verify it worked
Check the browser first, then inspect stored events for the device ID displayed by the demo. The debugging guide distinguishes transport checks from the user event stream.
- In the browser Network tab, confirm an event upload to
api2.amplitude.com/2/httpapireturns200. EU projects useapi.eu.amplitude.com/2/httpapi. Use the Instrumentation Explorer extension to inspect event contents locally. The app'sreadystatus alone does not establish delivery. - On Settings, click Save preferences once, change the dropdown from Starter to Pro, then click Toggle help and More help.
- In Amplitude User Lookup, find the device ID shown by the demo and open its Activity stream. Confirm a page view, an Element Clicked event with element ID
save, and an Element Changed event with element IDplan. On the save event, confirm[Amplitude] Element Attributes.actionissettings_savedand[Amplitude] Element Attributes.areaisworkspace. There should be no element-interaction event forhelporhelp-panelfrom those actions. - Open Billing and click Save preferences. Confirm a page view and save click whose
[Amplitude] Page URLends in/app/billing/. - Open Admin, click Save preferences, and change the dropdown. Repeat on Welcome. After allowing the uploads and stream to settle, confirm no new page-view or element-interaction events from
/app/admin/or/welcome/in that test window. Click events from earlier pages remain in the stream.
The default event names are [Amplitude] Page Viewed, [Amplitude] Element Clicked, and [Amplitude] Element Changed. The UI can display descriptive labels such as Clicked "Save preferences". Open the event to inspect its properties.
To check the production build too:
pnpm build
pnpm previewUse the URL Vite prints, append /app/settings/, and repeat the checks. If you change a Vite environment variable, restart development or rebuild production before testing again.
Troubleshooting
Analytics says disabled
The API-key variable is empty. Set VITE_AMPLITUDE_API_KEY in .env.local and restart Vite. A production build needs a new pnpm build after the key changes.
Analytics says ready, but no event appears
Initialization isn't an ingestion result. Confirm the key and top-level serverZone, inspect the upload response, and search for the displayed device ID in the correct test project. Check whether a browser extension blocks the request.
Help controls produce interaction events
Check that cssSelectorAllowlist replaces the defaults and that actionClickAllowlist is empty. A shouldTrackEventResolver copied from another setup overrides allowlists. Also check for a second SDK entry point or manual tracking code.
Admin page views still appear
The element URL lists don't configure page views. Keep the separate pageViews.trackOn predicate and check the full page URL and event timestamp before treating an older event as a new failure.
Viewport Content Updated appears alongside clicks
Keep elementInteractions.viewportContentUpdated.enabled: false for this example. Viewport exposure tracking is separate from the clicked and changed events being tested.
The selected plan value isn't an event property
The demo verifies a change to the plan element. It doesn't send the selected option value as a business property. Add a deliberate custom event when a product action needs validated business data, such as a server-confirmed subscription upgrade.
Full code reference
The complete runnable example includes the lockfile and tests. The files above are complete. This combined reference repeats the application and setup files in one place; the environment values remain local.
===== package.json =====
{
"name": "amplitude-react-autocapture",
"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 settings 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/capture-policy.js =====
const applicationUrl = /^https?:\/\/[^/]+\/app\//;
const adminUrl = /^https?:\/\/[^/]+\/app\/admin(?:\/|$)/;
export function isMeasuredPath(pathname) {
return pathname.startsWith('/app/') && !/^\/app\/admin(?:\/|$)/.test(pathname);
}
export const analyticsOptions = {
// Keep this tutorial's local policy authoritative for analytics autocapture.
remoteConfig: { fetchRemoteConfig: false },
autocapture: {
attribution: false,
sessions: false,
formInteractions: false,
fileDownloads: false,
pageUrlEnrichment: false,
frustrationInteractions: false,
networkTracking: false,
webVitals: false,
performanceTracking: false,
pageViews: {
trackOn: () => isMeasuredPath(window.location.pathname),
trackHistoryChanges: 'pathOnly',
},
elementInteractions: {
cssSelectorAllowlist: ['[data-analytics-action]'],
actionClickAllowlist: [],
pageUrlAllowlist: [applicationUrl],
pageUrlExcludelist: [adminUrl],
dataAttributePrefix: 'data-amp-track-',
viewportContentUpdated: { enabled: false },
},
},
};
===== src/analytics.js =====
import * as amplitude from '@amplitude/unified';
import { analyticsOptions } from './capture-policy.js';
let ready;
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: analyticsOptions,
sessionReplay: { sampleRate: 0 },
engagement: { skip: true },
}).then(() => ({ status: 'ready', deviceId: amplitude.getDeviceId() }))
.catch((error) => {
console.error('Amplitude initialization failed', error);
return { status: 'error', deviceId: null };
});
}
return ready;
}
===== src/App.jsx =====
import React, { useState } from 'react';
export function App({ analytics }) {
const [message, setMessage] = useState('No changes yet.');
const [helpOpen, setHelpOpen] = useState(false);
const path = window.location.pathname;
const heading = path === '/app/billing/' ? 'Billing preferences'
: path === '/app/admin/' ? 'Admin preview'
: path === '/app/settings/' ? 'Workspace settings' : 'Welcome';
return (
<main>
<p className="eyebrow">WORKSPACE DEMO</p>
<h1>{heading}</h1>
<p>This demo changes local display state. It does not save settings or charge a card.</p>
<nav aria-label="Demo pages">
<a href="/app/settings/">Settings</a>
<a href="/app/billing/">Billing</a>
<a href="/app/admin/">Admin</a>
<a href="/welcome/">Welcome</a>
</nav>
<section aria-label="Workspace controls">
<label htmlFor="plan">Preview plan</label>
<select id="plan" defaultValue="starter" data-analytics-action="plan">
<option value="starter">Starter</option>
<option value="pro">Pro</option>
</select>
<button id="save" data-analytics-action="save"
data-amp-track-action="settings_saved" data-amp-track-area="workspace"
onClick={() => setMessage('Saved in this tab.')}>
<span>Save preferences</span>
</button>
<button id="help" data-amp-default-track=""
onClick={() => setHelpOpen((value) => !value)}>Toggle help</button>
<div id="help-panel" role="button" tabIndex={0}
onClick={() => setHelpOpen((value) => !value)}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
setHelpOpen((value) => !value);
}
}}>More help</div>
{helpOpen && <p>Changes apply only to this demo tab.</p>}
<p role="status">{message}</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 { 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; } }
===== 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';
// Initialize outside React so development Strict Mode doesn't initialize twice.
initializeAnalytics().then((analytics) => {
createRoot(document.getElementById('root')).render(
<StrictMode><App analytics={analytics} /></StrictMode>,
);
});
===== tests/policy.test.mjs =====
import test from 'node:test';
import assert from 'node:assert/strict';
import { analyticsOptions, isMeasuredPath } from '../src/capture-policy.js';
test('path rules separate the application boundary from lookalike paths', () => {
for (const path of ['/app/settings/', '/app/billing/', '/app/administration/']) {
assert.equal(isMeasuredPath(path), true, path);
}
for (const path of ['/welcome/', '/application/settings/', '/app', '/app/admin', '/app/admin/users/']) {
assert.equal(isMeasuredPath(path), false, path);
}
});
test('element URL policy agrees with page policy on normal and excluded fixtures', () => {
const { pageUrlAllowlist: allow, pageUrlExcludelist: deny } = analyticsOptions.autocapture.elementInteractions;
for (const origin of ['http://localhost:5173', 'https://example.com']) {
for (const path of ['/app/settings/', '/app/billing/', '/app/admin/', '/app/admin/users/', '/welcome/']) {
const url = origin + path;
assert.equal(allow.some((r) => r.test(url)) && !deny.some((r) => r.test(url)), isMeasuredPath(path), url);
}
}
});Hand it to your agent
Use this prompt to adapt the policy to an existing React application.
Configure Amplitude autocapture for selected controls and pages in this React app.
Use the React Autocapture tutorial and its linked runnable source as the reference.
Inspect the existing Amplitude initialization before editing. Merge changes into it;
do not create another SDK instance or remove existing auth, routes, or instrumentation.
Use current Amplitude docs for the installed package and SDK version.
Keep page-view and element-interaction policies separate. Limit selected elements
with cssSelectorAllowlist and set actionClickAllowlist to [] for a strict selector
policy. Exclude the admin branch and test the same marked controls on an excluded
page. Do not add shouldTrackEventResolver unless its override behavior is intentional.
Explicitly configure viewportContentUpdated for the intended event scope.
Use only static, non-sensitive data-amp-track- attributes. Preserve consent handling.
Do not overwrite existing product settings without explaining the change. Keep the
key in the existing environment mechanism and never use a server secret in browser code.
Test selected and unselected controls, allowed and excluded pages, and missing-key
startup. Report local checks, upload results and processed Amplitude verification
separately. Explain every changed file and any remaining verification limit.What this unlocks
Product analytics can compare the captured save interactions by [Amplitude] Page URL and static element attributes. A click records intent; use a separate confirmed business event when the analysis needs a completed save, purchase, or upgrade.
Session replay can add visual context when you enable it separately with an appropriate privacy policy.
Feature flags can control a later version of the settings experience while you keep the capture markers stable.
Guides and surveys can collect feedback in that experience when configured separately. This example skips their SDK initialization.
Frequently asked questions
Does an element URL allowlist also filter page views?
No. The element-interaction URL lists govern that capture path. Configure page views separately with pageViews.trackOn. This demo uses the same application/admin boundary in both places, disables the supplemental viewport stream, and tests the same selected controls on allowed and excluded pages.
Do I need a custom tracking call on each selected control?
No. The SDK captures the selected click and change events. The save button's static attributes add context without a manual call. For business-critical actions, send a separate custom event from the place that confirms success, so a click isn't mistaken for a completed transaction.
Can project settings override this configuration?
Analytics remote configuration normally overrides local settings per feature. This example sets analytics.remoteConfig.fetchRemoteConfig to false, keeping its local analytics policy authoritative. In an existing application, decide with your team whether local code or project settings owns the policy; other bundled products have their own configuration.
Can I put customer data in data attributes?
Explicit data-amp-track- attributes intentionally send event data. Keep them to stable, non-sensitive categories such as the control's action or area. Don't put names, email addresses, credentials, or free text there. Review displayed text and other event fields separately; selector filtering alone isn't a complete privacy control.
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.