---
title: "How to set up cookieless web analytics"
description: "Set up cookieless web analytics with Amplitude and browser JavaScript. Store identity in localStorage and verify cookies, sessions, and events."
canonical: "https://amplitude.com/build/javascript-cookieless-analytics"
---

# How to set up cookieless web analytics

Set up cookieless web analytics with Amplitude and browser JavaScript. Store identity in localStorage and verify cookies, sessions, and events.

Source: https://amplitude.com/build/javascript-cookieless-analytics

---

# How to set up cookieless web analytics

Store your analytics identity in localStorage and check the result in your browser and Amplitude.

- JavaScript
- Web analytics
- Cookies
- 20 min

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](https://amplitude.com/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](https://app.amplitude.com/signup) 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](https://github.com/amplitude/ampli-examples/tree/build/javascript-cookieless-analytics-2026-11-18/browser/javascript/v2/cookieless-analytics) 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](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/get-started) documents the package and its product configuration.

Terminal

```sh
mkdir cookieless-analytics
cd cookieless-analytics
mkdir src
corepack enable
```

Create these two files before installing dependencies.

package.json

```json
{
  "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"
  }
}
```

pnpm-workspace.yaml

```yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
```

Terminal

```sh
corepack pnpm install
```

Create `.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.

.env.example

```text
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US
```

.gitignore

```text
node_modules/
dist/
.env.local
```

Terminal

```sh
cp .env.example .env.local
```

The 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](https://amplitude.com/docs/apis/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.

index.html

```html
<!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>
```

src/style.css

```css
* { 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](https://amplitude.com/docs/sdks/analytics/browser/cookies-and-consent-management#disable-cookies-using-localstorage) documents this cookieless configuration.

src/analytics.js

```javascript
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.

src/main.js

```javascript
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

Terminal

```sh
corepack pnpm dev
```

Open 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.

DevTools Console

```javascript
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:

DevTools Console

```javascript
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:

DevTools Console

```javascript
delete document.cookie;
```

## Verify it worked

1. **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.
2. **Identity.** Note `deviceId` and `sessionId`. 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.
3. **Delivery.** In DevTools **Network**, confirm an analytics POST returns `200`. Use the [Amplitude Instrumentation Explorer](https://amplitude.com/docs/analytics/debug-analytics#instrumentation-explorer) to read event contents and `demo_run_id`, since request compression can make them unreadable in Network.
4. **Processed data.** In Amplitude, open **User Profiles**, search the displayed device ID, and open the event stream. Find `Cookieless Demo Opened` and `Cookieless Report Generated`, then compare `demo_run_id`, device ID, and session ID. Accepted uploads and processed events are separate checks.
5. **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 `identityStorage` is passed to `init()`, 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 correct `US` or `EU` region, 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](https://github.com/amplitude/ampli-examples/tree/build/javascript-cookieless-analytics-2026-11-18/browser/javascript/v2/cookieless-analytics) 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.

Full code reference

```sh
corepack enable
corepack pnpm install --frozen-lockfile
cp .env.example .env.local
corepack pnpm dev
```

package.json

```json
{
  "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"
  }
}
```

pnpm-workspace.yaml

```yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
```

.env.example

```text
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US
```

.gitignore

```text
node_modules/
dist/
.env.local
```

index.html

```html
<!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>
```

src/analytics.js

```javascript
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); }
}
```

src/main.js

```javascript
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.';
});
```

src/style.css

```css
* { 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

Using Cursor or Claude Code? Paste this prompt

```text
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](https://amplitude.com/web-analytics) can count the report interaction while browser identity persists in localStorage.

[Product analytics](https://amplitude.com/amplitude-analytics) can use `Cookieless Report Generated` to explore report adoption and repeat usage.

[Experimentation](https://amplitude.com/amplitude-experiment) 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.

## Next steps

[Web AnalyticsReact web analyticsAdd page and interaction tracking to a React app.](https://amplitude.com/build/react-web-analytics)[IdentityBrowser identity and sessionsPlan how your app handles signed-in users and navigation.](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/instrument-and-configure)[VerificationDebug analyticsInspect event delivery and processed user activity.](https://amplitude.com/docs/analytics/debug-analytics)

Reference docs

[Get started with Browser SDK 2 →](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/get-started)[Cookies and consent management →](https://amplitude.com/docs/sdks/analytics/browser/cookies-and-consent-management)[Instrument and configure Browser SDK 2 →](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/instrument-and-configure)[Browser SDK 2 reference →](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/reference)[Debug analytics →](https://amplitude.com/docs/analytics/debug-analytics)[API keys and tokens →](https://amplitude.com/docs/apis/keys-and-tokens)

For agents

[View raw .md](/build/javascript-cookieless-analytics.md)[llms.txt](/llms.txt)

## Ship the instrumentation, then read the data

Create an Amplitude project, send the sample report event, and verify its identity and storage behavior in your browser.

[Create a free account](https://app.amplitude.com/signup)[Browse all Build tutorials](https://amplitude.com/build)
