Chris Tam · Last updated 18 November 2026
You can configure Amplitude's browser SDK to store identity in localStorage instead of cookies. I'll use a small JavaScript demo that simulates generating a report and sends that interaction to Amplitude web analytics.
In this tutorial, you'll configure cookieless tracking, inspect storage and cookie writes, and compare browser identity across reloads and tabs. Vite runs the demo locally; the analytics configuration works in browser JavaScript apps.
What you'll build
A page with two controls: Start demo analytics initializes Amplitude and sends Cookieless Demo Opened; Generate sample report updates a simulated report counter and sends Cookieless Report Generated. The page displays the current device and session IDs. It sends no report contents.
This setup keeps a persistent device ID in localStorage. Events still leave the browser and contain identifiers. Apply your site's consent and disclosure requirements to localStorage and event collection, too. The start button makes initialization explicit for this demo; connect initialization to your consent manager in a real app.
Prerequisites
- Node.js 22.12 or later and Corepack.
- An Amplitude project and its project API key, with access to User Profiles for verification.
- A browser with DevTools and localStorage available.
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.
I tested the example with Browser SDK 2.49.2 (@amplitude/analytics-browser), and Vite 8.3.6. The public example includes the tested lockfile.
For an existing app, merge the analytics configuration into its existing initialization and call the tracking helper from your real report-success handler. Keep your authentication, routes, consent controls, and other instrumentation. Use one Amplitude package entry point and initialize once per page.
1. Create the JavaScript project
I start with a small Vite project so you can run the example without a framework. The Browser SDK 2 installation guide documents the package and its product configuration.
mkdir cookieless-analytics
cd cookieless-analytics
mkdir src
corepack enableCreate these two files before installing dependencies.
{
"name": "amplitude-javascript-cookieless-analytics",
"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 --port 5173 --strictPort",
"build": "vite build",
"preview": "vite preview --host 127.0.0.1 --port 5173 --strictPort"
},
"dependencies": {
"@amplitude/analytics-browser": "2.49.2"
},
"devDependencies": {
"vite": "8.3.6"
}
}minimumReleaseAge: 10080
trustPolicy: no-downgradecorepack pnpm installCreate .env.example using the contents below. Copy it to .env.local, then set your project API key and use US or EU for your project's data region. Restart Vite after changing environment variables.
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=USnode_modules/
dist/
.env.localcp .env.example .env.localThe project API key is public and limited to ingestion. Vite exposes VITE_ variables in browser code. Use only the project API key here; keep secret keys and tokens out of the client bundle. See API keys and tokens.
2. Add the demo page
I keep the report simulation separate from delivery status. You can generate a sample report even when analytics is unavailable.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cookieless analytics demo</title>
</head>
<body>
<main>
<p>AMPLITUDE BUILD</p>
<h1>Cookieless analytics demo</h1>
<p>Generate a sample report and compare your browser identity across reloads.</p>
<button id="start">Start demo analytics</button>
<button id="report">Generate sample report</button>
<p id="report-result" aria-live="polite">No report generated yet.</p>
<p id="status" role="status">Analytics has not initialized.</p>
<h2>Current analytics identity</h2>
<pre id="identity">Not initialized</pre>
<p>This demo uses localStorage for identity. It does not ask you to sign in.</p>
</main>
<script type="module" src="/src/main.js"></script>
</body>
</html>* { box-sizing: border-box; }
body { margin: 0; padding: 48px 20px; background: #FFFFFF; color: #000000; font: 17px/1.6 Gellix, Poppins, Helvetica, sans-serif; }
main { max-width: 760px; margin: auto; padding: 36px; background: white; border: 1px solid #000000; border-radius: 16px; }
h1 { line-height: 1.2; }
button { padding: 12px 16px; margin: 4px 8px 4px 0; border: 0; border-radius: 6px; background: #0052F2; color: white; font: inherit; cursor: pointer; }
button:disabled { opacity: .55; cursor: default; }
button:focus-visible { outline: 3px solid #000000; outline-offset: 3px; }
pre { padding: 20px; overflow: auto; background: #FFFFFF; font-size: 14px; }3. Configure cookieless identity
I pass identityStorage: 'localStorage' to init(). This stores device, user, and session state in localStorage. The cookies and consent guide documents this cookieless configuration.
import * as amplitude from '@amplitude/analytics-browser';
let ready;
let enabled = false;
export function initializeAnalytics() {
if (!ready) ready = (async () => {
const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
if (!apiKey) return false;
const serverZone = import.meta.env.VITE_AMPLITUDE_SERVER_ZONE || 'US';
if (!['US', 'EU'].includes(serverZone)) throw new Error('Use US or EU for the server zone.');
await amplitude.init(apiKey, {
instanceName: 'build-cookieless',
serverZone,
identityStorage: 'localStorage',
remoteConfig: { fetchRemoteConfig: false },
autocapture: false,
flushMaxRetries: 0,
}).promise;
enabled = true;
return true;
})().catch(() => false);
return ready;
}
export function currentIdentity() {
return enabled ? {
deviceId: amplitude.getDeviceId(),
sessionId: amplitude.getSessionId(),
userId: amplitude.getUserId() ?? null,
} : null;
}
export async function record(name, runId) {
if (!enabled) return false;
let timer;
try {
const upload = (async () => {
const pending = amplitude.track(name, {
demo_run_id: runId,
demo_source: 'build-cookieless',
identity_storage: 'localStorage',
});
await amplitude.flush().promise;
return (await pending.promise).code === 200;
})();
return await Promise.race([upload, new Promise(resolve => {
timer = setTimeout(() => resolve(false), 3000);
})]);
} catch { return false; }
finally { clearTimeout(timer); }
}I use explicit events with autocapture: false. Disabling analytics remote configuration keeps this demo's configuration local. I use the analytics-only package so this example initializes analytics without adding session replay, experiments, or guides and surveys. Check other products, tags, and existing integrations separately when applying this to your site.
The initialization promise is cached so repeated calls use the same setup. record checks the tracked event's result rather than treating a completed flush as delivery proof. Its three-second limit bounds the UI wait; it does not cancel the SDK's upload. A timeout means delivery is unconfirmed.
Why. localStorage belongs to an origin: scheme, hostname, and port. It can preserve identity across tabs and visits on that origin, but it does not share that identity with another subdomain. Keep the test URL identical when comparing IDs.
4. Track the simulated report action
I initialize only after you click Start demo analytics. Each new page load requires that click again. The report counter updates before awaiting analytics, and both events carry the same demo_run_id from the URL for verification.
import { initializeAnalytics, currentIdentity, record } from './analytics.js';
import './style.css';
const url = new URL(window.location.href);
const runId = url.searchParams.get('demo_run_id') || crypto.randomUUID();
url.searchParams.set('demo_run_id', runId);
window.history.replaceState(null, '', url);
const start = document.querySelector('#start');
const report = document.querySelector('#report');
const status = document.querySelector('#status');
const identity = document.querySelector('#identity');
let reports = 0;
function showIdentity() {
identity.textContent = JSON.stringify({ runId, ...currentIdentity() }, null, 2);
}
start.addEventListener('click', async () => {
start.disabled = true;
status.textContent = 'Initializing analytics...';
if (!await initializeAnalytics()) {
status.textContent = 'Analytics unavailable. Check your key and server zone, then reload.';
return;
}
showIdentity();
status.textContent = 'Analytics ready. Sending demo event...';
const accepted = await record('Cookieless Demo Opened', runId);
status.textContent = accepted ? 'Demo event accepted (HTTP 200).' : 'Demo event not confirmed within 3 seconds.';
});
report.addEventListener('click', async () => {
reports += 1;
document.querySelector('#report-result').textContent = `Sample report ${reports} generated. No real report data is sent.`;
const accepted = await record('Cookieless Report Generated', runId);
showIdentity();
status.textContent = accepted ? 'Report event accepted (HTTP 200).' : 'Report generated; analytics delivery not confirmed.';
});The demo leaves userId unset. That is anonymous tracking in the SDK's identity model, with a persistent device ID. It does not make the event stream free of identifiers. Don't call reset() on every load; that creates a new device ID and breaks this persistence check.
5. Run the app and audit cookie writes
corepack pnpm devOpen the local URL printed by Vite. Before clicking Start demo analytics, open DevTools Console and run this temporary observer. It records cookie names without recording their values, including cookies written and immediately deleted during initialization.
window.buildCookieWrites = [];
const cookieDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
Object.defineProperty(document, 'cookie', {
configurable: true,
get() { return cookieDescriptor.get.call(document); },
set(value) {
window.buildCookieWrites.push(String(value).split('=')[0]);
return cookieDescriptor.set.call(document, value);
},
});Click Start demo analytics, then Generate sample report. Check the audit array:
window.buildCookieWrites;For this example's configuration, expect []. Also inspect Application > Storage > Cookies for the local origin. Start in a separate browser profile if you want a clean cookie jar: changing SDK storage does not remove cookies left by earlier integrations.
Under Application > Storage > Local Storage, inspect the local origin. Expect an AMP_ identity entry and SDK storage such as the unsent-event queue. An empty queue after upload is normal. Cookieless tracking here still uses persistent browser storage.
This observer covers JavaScript cookie writes in this document after it is installed. Inspect response cookies and other scripts separately on a production site. After the test, reload the page to remove the observer, or restore normal access with:
delete document.cookie;Verify it worked
- Cookie audit. Initialize and generate a report with the observer installed. Expect zero recorded cookie writes for this demo. Inspect the cookie jar as well; cookies from older integrations need a separate migration plan.
- Identity. Note
deviceIdandsessionId. Reload the same URL, start analytics again, then open that URL in another tab and start it there. With localStorage available, expect the same device ID. An immediate test within the active session should also keep the session ID; inactivity can start a new session. - Delivery. In DevTools Network, confirm an analytics POST returns
200. Use the Amplitude Instrumentation Explorer to read event contents anddemo_run_id, since request compression can make them unreadable in Network. - Processed data. In Amplitude, open User Profiles, search the displayed device ID, and open the event stream. Find
Cookieless Demo OpenedandCookieless Report Generated, then comparedemo_run_id, device ID, and session ID. Accepted uploads and processed events are separate checks. - App behavior. Generate a report before starting analytics. The counter still updates. A missing key or blocked upload should also leave that simulation usable.
Troubleshooting
- Cookie writes appear. Check: Confirm
identityStorageis passed toinit(), analytics remote configuration is disabled as shown, and another script or SDK instance isn't initializing with cookies. Audit a fresh page before pressing the start button. - Old
AMP_cookies remain. Check: localStorage configuration does not clean up a previous integration's cookies. Inspect their origin and owner and plan a scoped migration separately. - Device ID changes on reload. Check: Use the same scheme, host, port, project key, and browser profile. Check storage restrictions, cleared site data, and unexpected
reset()calls. - IDs differ between subdomains. Check: localStorage is scoped to an origin. Use an explicit identity handoff if your flow crosses domains; changing storage alone doesn't join them.
- Session ID changes later. Check: A new session can begin after inactivity. Compare immediately for this test; don't use an unchanging session ID as a long-term visitor identifier.
- Analytics is unavailable. Check: Set the project key in
.env.local, use the correctUSorEUregion, restart Vite, and reload the page. - Report succeeds but tracking is unconfirmed. Check: Inspect the analytics request status and blocking extensions. The three-second message does not establish that an event was rejected or lost.
Full code reference
The example source and lockfile contain this complete app. Copy .env.example to .env.local, fill in your project key, and run the commands below. With the repository lockfile, use a frozen install.
corepack enable
corepack pnpm install --frozen-lockfile
cp .env.example .env.local
corepack pnpm dev{
"name": "amplitude-javascript-cookieless-analytics",
"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 --port 5173 --strictPort",
"build": "vite build",
"preview": "vite preview --host 127.0.0.1 --port 5173 --strictPort"
},
"dependencies": {
"@amplitude/analytics-browser": "2.49.2"
},
"devDependencies": {
"vite": "8.3.6"
}
}minimumReleaseAge: 10080
trustPolicy: no-downgradeVITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=USnode_modules/
dist/
.env.local<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cookieless analytics demo</title>
</head>
<body>
<main>
<p>AMPLITUDE BUILD</p>
<h1>Cookieless analytics demo</h1>
<p>Generate a sample report and compare your browser identity across reloads.</p>
<button id="start">Start demo analytics</button>
<button id="report">Generate sample report</button>
<p id="report-result" aria-live="polite">No report generated yet.</p>
<p id="status" role="status">Analytics has not initialized.</p>
<h2>Current analytics identity</h2>
<pre id="identity">Not initialized</pre>
<p>This demo uses localStorage for identity. It does not ask you to sign in.</p>
</main>
<script type="module" src="/src/main.js"></script>
</body>
</html>import * as amplitude from '@amplitude/analytics-browser';
let ready;
let enabled = false;
export function initializeAnalytics() {
if (!ready) ready = (async () => {
const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
if (!apiKey) return false;
const serverZone = import.meta.env.VITE_AMPLITUDE_SERVER_ZONE || 'US';
if (!['US', 'EU'].includes(serverZone)) throw new Error('Use US or EU for the server zone.');
await amplitude.init(apiKey, {
instanceName: 'build-cookieless',
serverZone,
identityStorage: 'localStorage',
remoteConfig: { fetchRemoteConfig: false },
autocapture: false,
flushMaxRetries: 0,
}).promise;
enabled = true;
return true;
})().catch(() => false);
return ready;
}
export function currentIdentity() {
return enabled ? {
deviceId: amplitude.getDeviceId(),
sessionId: amplitude.getSessionId(),
userId: amplitude.getUserId() ?? null,
} : null;
}
export async function record(name, runId) {
if (!enabled) return false;
let timer;
try {
const upload = (async () => {
const pending = amplitude.track(name, {
demo_run_id: runId,
demo_source: 'build-cookieless',
identity_storage: 'localStorage',
});
await amplitude.flush().promise;
return (await pending.promise).code === 200;
})();
return await Promise.race([upload, new Promise(resolve => {
timer = setTimeout(() => resolve(false), 3000);
})]);
} catch { return false; }
finally { clearTimeout(timer); }
}import { initializeAnalytics, currentIdentity, record } from './analytics.js';
import './style.css';
const url = new URL(window.location.href);
const runId = url.searchParams.get('demo_run_id') || crypto.randomUUID();
url.searchParams.set('demo_run_id', runId);
window.history.replaceState(null, '', url);
const start = document.querySelector('#start');
const report = document.querySelector('#report');
const status = document.querySelector('#status');
const identity = document.querySelector('#identity');
let reports = 0;
function showIdentity() {
identity.textContent = JSON.stringify({ runId, ...currentIdentity() }, null, 2);
}
start.addEventListener('click', async () => {
start.disabled = true;
status.textContent = 'Initializing analytics...';
if (!await initializeAnalytics()) {
status.textContent = 'Analytics unavailable. Check your key and server zone, then reload.';
return;
}
showIdentity();
status.textContent = 'Analytics ready. Sending demo event...';
const accepted = await record('Cookieless Demo Opened', runId);
status.textContent = accepted ? 'Demo event accepted (HTTP 200).' : 'Demo event not confirmed within 3 seconds.';
});
report.addEventListener('click', async () => {
reports += 1;
document.querySelector('#report-result').textContent = `Sample report ${reports} generated. No real report data is sent.`;
const accepted = await record('Cookieless Report Generated', runId);
showIdentity();
status.textContent = accepted ? 'Report event accepted (HTTP 200).' : 'Report generated; analytics delivery not confirmed.';
});* { box-sizing: border-box; }
body { margin: 0; padding: 48px 20px; background: #FFFFFF; color: #000000; font: 17px/1.6 Gellix, Poppins, Helvetica, sans-serif; }
main { max-width: 760px; margin: auto; padding: 36px; background: white; border: 1px solid #000000; border-radius: 16px; }
h1 { line-height: 1.2; }
button { padding: 12px 16px; margin: 4px 8px 4px 0; border: 0; border-radius: 6px; background: #0052F2; color: white; font: inherit; cursor: pointer; }
button:disabled { opacity: .55; cursor: default; }
button:focus-visible { outline: 3px solid #000000; outline-offset: 3px; }
pre { padding: 20px; overflow: auto; background: #FFFFFF; font-size: 14px; }Hand it to your agent
Use https://amplitude.com/build/javascript-cookieless-analytics to add cookieless Amplitude web analytics to this browser JavaScript app.
Read the current docs and preserve existing routes, authentication, consent controls, and instrumentation. Merge into the existing initialization rather than adding a second SDK. Use the analytics-only @amplitude/analytics-browser package, initialize it once with init(...).promise, and set identityStorage to localStorage. Disable autocapture and analytics remote configuration for the demo. Do not initialize other Amplitude products as part of this example.
Initialize only after the site's required consent condition. For this standalone demo, use an explicit start button. Track Cookieless Demo Opened and Cookieless Report Generated with demo_run_id, and display device/session IDs for testing. Keep the simulated report usable when tracking is unavailable.
Verify cookie writes during initialization, inspect stored identity, compare IDs across an immediate reload and another tab on the same origin, and confirm processed events in User Profiles. Describe localStorage persistence accurately. Don't claim this removes all storage, identifiers, or consent requirements. Report what was actually tested.What this unlocks
Web analytics can count the report interaction while browser identity persists in localStorage.
Product analytics can use Cookieless Report Generated to explore report adoption and repeat usage.
Experimentation can use a report-success event as a metric when you add and configure an experiment separately.
FAQ
Does cookieless analytics mean no browser storage?
This tutorial uses localStorage to persist analytics identity and SDK state. The unsent-event queue also uses localStorage by default. Audit the complete SDK configuration and other tags when your requirement concerns all browser storage.
Can I use this outside Vite?
Yes. The storage and tracking options belong to Amplitude's browser SDK. In another browser app, adapt the environment-variable access and initialization location to that app. Vite supplies the local server and build for this example.
Do I still need consent controls?
Apply the consent and disclosure requirements for your data collection, including localStorage and events. Where consent is required, wait for it before initializing. This demo's start button does not implement a production consent manager.
Will visitors keep their identity across subdomains?
localStorage does not share identity across origins. Use the same origin for this tutorial's reload and new-tab tests. A flow spanning subdomains needs a separate identity design.