---
title: "How to identify users at login and reset at logout in React"
description: "Identify users at login and reset Amplitude identity at logout in React. Test a local session, reloads, failed login, and the next anonymous visit."
canonical: "https://amplitude.com/build/react-login-identity"
---

# How to identify users at login and reset at logout in React

Identify users at login and reset Amplitude identity at logout in React. Test a local session, reloads, failed login, and the next anonymous visit.

Source: https://amplitude.com/build/react-login-identity

---

# How to identify users at login and reset at logout in React

Set a stable Amplitude user ID after login and call reset after confirmed logout. Build a React app with a local session server, then verify anonymous, signed-in, and signed-out events in about 20 minutes.

- React
- Vite
- Unified SDK 1.2.1
- 20 min

Chris Tam · Last updated 13 November 2026

[Product analytics](https://amplitude.com/amplitude-analytics) connects activity to an account when the SDK receives its stable user ID. I'll use a local React app with two seeded demo users and a cookie-based Node session server. It runs on your computer and needs no auth-provider account.

In this tutorial, I'll identify a signed-in user, restore that identity after reload, and reset it on logout. The [React analytics tutorial](https://amplitude.com/build/react-product-analytics) covers installation; this example has its own setup.

## What you'll build

A local app that records `Identity Demo Viewed` before login, during an authenticated session, and after logout. The device ID stays stable through login and reload; logout clears the user ID and generates a new device ID.

## Prerequisites

- Node.js 22.12 or later and Corepack for pnpm.
- An Amplitude test project and its ingestion API key. Open Organization settings > API Keys and select the test project.
- The project data center, US or EU. Preserve your existing consent flow when adapting the example.

No Amplitude account yet? A free account is enough for this tutorial; nothing here needs a paid plan. [Sign up for free](https://app.amplitude.com/signup) to get your project API key.

## 1. Create the standalone app

I'll use the [Browser Unified SDK package installation](https://amplitude.com/docs/get-started/install-with-package-manager) in a small Vite app. The versions below are pinned to the tested example.

Terminal

```sh
mkdir react-login-identity
cd react-login-identity
mkdir -p src tests server
corepack enable
```

package.json

```json
{
  "name": "amplitude-react-login-identity",
  "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",
    "start": "node server/server.mjs"
  },
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "vite": "8.3.6"
  }
```

pnpm-workspace.yaml

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

.gitignore

```text
node_modules/
dist/
.env
.env.local
.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>Login identity demo</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
```

.env.example

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

Terminal

```sh
corepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.local
```

Put the test-project key in `VITE_AMPLITUDE_API_KEY` in `.env.local`, and set `VITE_AMPLITUDE_SERVER_ZONE` to `US` or `EU`. Vite exposes `VITE_` variables in the browser bundle. The project API key is public and has the minimum scope needed to ingest data; a server secret key stays out of browser code.

In an existing application, merge the changes into its current Amplitude module and application flow. Keep authentication, consent, routes, and other instrumentation. Don't add another SDK installation or replace production files with the demo.

## 2. Create the local session server

I'll use two seeded accounts, `alex` and `sam`, each with `local-demo-password`. The loopback-only server keeps sessions in memory and issues an HttpOnly, SameSite=Strict cookie. This is a local teaching fixture; use your existing authentication implementation in a real application.

server/server.mjs

```javascript
import http from 'node:http';
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const demoPassword = scryptSync('local-demo-password', 'local-build-demo', 32);
const users = {
  alex: { id: 'build-login-alex-v1', name: 'Alex' },
  sam: { id: 'build-login-sam-v1', name: 'Sam' },
};
const defaultRoot = fileURLToPath(new URL('../dist/', import.meta.url));

export function createDemoServer({ staticRoot = defaultRoot } = {}) {
  const sessions = new Map();
  return http.createServer(async (req, res) => {
    if (!/^127\.0\.0\.1:\d+$/.test(req.headers.host ?? '')) {
      res.writeHead(400); return res.end('Use the printed loopback URL.');
    }
    const origin = `http://${req.headers.host}`;
    const url = new URL(req.url, origin);
    const token = req.headers.cookie?.split(';').map((v) => v.trim())
      .find((v) => v.startsWith('build_demo_session='))?.split('=')[1];
    const session = token && sessions.get(token);
    const user = session && session.expiresAt > Date.now() ? users[session.username] : null;
    function json(status, body, cookie) {
      res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store',
        ...(cookie ? { 'Set-Cookie': cookie } : {}) });
      res.end(JSON.stringify(body));
    }
    try {
      if (url.pathname.startsWith('/api/')) {
        if (req.method === 'GET' && url.pathname === '/api/session') {
          return json(200, { user, state: user ? 'signed_in' : token ? 'expired' : 'anonymous' });
        }
        if (req.method !== 'POST' || req.headers.origin !== origin
          || !req.headers['content-type']?.startsWith('application/json')) {
          return json(403, { error: 'Use a same-origin JSON POST.' });
        }
        let body = '';
        for await (const chunk of req) {
          body += chunk;
          if (body.length > 2048) return json(413, { error: 'Request too large.' });
        }
        const input = JSON.parse(body || '{}');
        if (url.pathname === '/api/login') {
          const candidate = scryptSync(String(input.password ?? '').slice(0, 128), 'local-build-demo', 32);
          if (!Object.hasOwn(users, input.username) || !timingSafeEqual(candidate, demoPassword)) {
            return json(401, { error: 'The demo credentials did not match.' });
          }
          if (token) sessions.delete(token);
          const nextToken = randomBytes(32).toString('hex');
          sessions.set(nextToken, { username: input.username, expiresAt: Date.now() + 3600000 });
          return json(200, { user: users[input.username], state: 'signed_in' },
            `build_demo_session=${nextToken}; HttpOnly; SameSite=Strict; Path=/; Max-Age=3600`);
        }
        if (url.pathname === '/api/logout') {
          if (token) sessions.delete(token);
          return json(200, { user: null, state: 'anonymous' },
            'build_demo_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0');
        }
        return json(404, { error: 'Unknown demo endpoint.' });
      }
      if (req.method !== 'GET') { res.writeHead(405); return res.end(); }
      let filename = path.resolve(staticRoot, '.' + decodeURIComponent(url.pathname));
      if (url.pathname === '/') filename = path.join(staticRoot, 'index.html');
      if (!filename.startsWith(path.resolve(staticRoot) + path.sep)) {
        res.writeHead(403); return res.end();
      }
      const data = await readFile(filename);
      const mime = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css' };
      res.writeHead(200, { 'Content-Type': mime[path.extname(filename)] ?? 'application/octet-stream', 'Cache-Control': 'no-store' });
      res.end(data);
    } catch (error) {
      json(error.code === 'ENOENT' ? 404 : 400, { error: 'The demo request could not be completed.' });
    }
  });
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  createDemoServer().listen(5190, '127.0.0.1', () => console.log('Local demo: http://127.0.0.1:5190'));
}
```

src/session.js

```javascript
export async function sessionRequest(path, body) {
  const response = await fetch(`/api/${path}`, body === undefined ? {
    credentials: 'same-origin', cache: 'no-store',
  } : {
    method: 'POST', credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
  });
  const result = await response.json();
  if (!response.ok) throw new Error(result.error ?? 'Session request failed.');
  return result;
}
```

Successful login returns the account's stable ID. Failed credentials don't create a session. A session survives a page reload, expires after one hour, and becomes invalid after server restart. Keep the printed `127.0.0.1` URL: this fixture rejects other hosts and cross-origin write requests.

The local cookie uses HTTP on loopback. A production auth system needs its own HTTPS, secure-cookie, credential, session-store, and abuse controls; this server isn't a deployment template.

## 3. Connect identity to confirmed authentication

I'll initialize after the session request resolves and set the user ID only from the server's authenticated result. The SDK [identity methods](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/reference#identity) manage the identity on later events.

src/analytics.js

```javascript
import * as amplitude from '@amplitude/unified';

let ready;
let enabled = false;
export function initializeAnalytics(session) {
  const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
  if (!apiKey) return Promise.resolve({ status: 'disabled', needsSignout: false });
  if (!ready) {
    ready = amplitude.initAll(apiKey, {
      instanceName: 'build-login-identity',
      serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
      analytics: { autocapture: false, remoteConfig: { fetchRemoteConfig: false } },
      sessionReplay: { sampleRate: 0 }, engagement: { skip: true },
    }).then(() => {
      enabled = true;
      if (session.user) amplitude.setUserId(session.user.id);
      // Don't reset for null/loading state. An explicit sign-out clears stale identity.
      return { status: 'ready', needsSignout: !session.user && Boolean(amplitude.getUserId()) };
    }).catch((error) => {
      console.error('Analytics initialization failed', error);
      return { status: 'error', needsSignout: false };
    });
  }
  return ready;
}

export function analyticsIdentity() {
  return enabled ? { userId: amplitude.getUserId() ?? null, deviceId: amplitude.getDeviceId() } : { userId: null, deviceId: null };
}
export function identifySignedInUser(user) {
  if (enabled) amplitude.setUserId(user.id);
}
export function resetAfterSignout() {
  if (enabled) amplitude.reset();
}
export async function trackDemoVisit(signedIn) {
  if (!enabled) return 'Analytics disabled; the local session still works.';
  const result = await amplitude.track('Identity Demo Viewed', {
    auth_state: signedIn ? 'signed_in' : 'anonymous',
  }).promise;
  if (result.code !== 200) throw new Error(`Visit upload: ${result.message}`);
  return 'Visit event accepted. Check the identity in Amplitude.';
}
```

`setUserId` uses a stable account ID, not an email address or a new random value for every visit. The same SDK instance sends events before and after login. Autocapture is off in this fixture so the identity sequence is explicit. Replay sampling is zero and guides and surveys are skipped.

**Why.** A missing user while auth is loading isn't a logout. This module doesn't reset in response to null state. If an expired or absent local session disagrees with a cached analytics user, the UI blocks event recording until you explicitly clear it through the sign-out handler.

**MCP.** Ask your coding agent to read the current identity signatures with the [Docs MCP server](https://amplitude.com/docs/amplitude-ai/docs-mcp-server). It provides public documentation, not access to the authenticated session or Amplitude user profiles.

## 4. Handle login and logout once

I'll call `setUserId` after the server confirms login and `reset` after it confirms logout. A pending-action ref prevents overlapping UI requests. Recording a visit is a separate deliberate action so you can inspect each stage.

src/App.jsx

```jsx
import React, { useRef, useState } from 'react';
import { sessionRequest } from './session.js';
import { analyticsIdentity, identifySignedInUser, resetAfterSignout, trackDemoVisit } from './analytics.js';

export function App({ session: initialSession, analytics }) {
  const [session, setSession] = useState(initialSession);
  const [identity, setIdentity] = useState(analyticsIdentity);
  const [needsSignout, setNeedsSignout] = useState(analytics.needsSignout || initialSession.state === 'expired');
  const [username, setUsername] = useState('alex');
  const [password, setPassword] = useState('local-demo-password');
  const [busy, setBusy] = useState(false);
  const pending = useRef(false);
  const [message, setMessage] = useState('Ready. Record a visit, then sign in.');
  async function run(action) {
    if (pending.current) return;
    pending.current = true; setBusy(true);
    try { await action(); setIdentity(analyticsIdentity()); }
    catch (error) { setMessage(error.message); }
    finally { pending.current = false; setBusy(false); }
  }
  async function login(event) {
    event.preventDefault();
    await run(async () => {
      const result = await sessionRequest('login', { username, password });
      identifySignedInUser(result.user);
      setSession(result); setMessage(`Signed in as ${result.user.name}. Record a visit.`);
    });
  }
  async function logout() {
    await run(async () => {
      const result = await sessionRequest('logout', {});
      resetAfterSignout();
      setSession(result); setNeedsSignout(false);
      setMessage('Signed out. The next visit uses a new device ID.');
    });
  }
  return (
    <main>
      <p className="eyebrow">LOCAL SESSION DEMO</p><h1>Login and analytics identity</h1>
      <p>This local-only example has two seeded demo users, Alex and Sam. Use local-demo-password for either. Sessions are kept in server memory and expire after one hour; restarting the server invalidates them. Use your existing auth system in a real app.</p>
      <p id="session-state">Session: {session.user?.name ?? session.state}</p>
      {needsSignout ? <p>Clear the previous sign-in before recording another visit.</p> : !session.user && (
        <form onSubmit={login}>
          <label htmlFor="username">Demo user</label>
          <select id="username" value={username} disabled={busy} onChange={(e) => setUsername(e.target.value)}>
            <option value="alex">Alex</option><option value="sam">Sam</option>
          </select>
          <label htmlFor="password">Demo password</label>
          <input id="password" type="password" value={password} disabled={busy} onChange={(e) => setPassword(e.target.value)} />
          <button id="login" disabled={busy}>Sign in</button>
        </form>
      )}
      {(session.user || needsSignout) && <button id="logout" disabled={busy} onClick={logout}>Sign out and clear identity</button>}
      <button id="visit" disabled={busy || needsSignout} onClick={() => run(async () => setMessage(await trackDemoVisit(Boolean(session.user))))}>Record a visit</button>
      <p role="status">{busy ? 'Working...' : message}</p>
      <aside>
        <p>Analytics: <strong id="analytics-status">{analytics.status}</strong></p>
        <p>User ID: <code id="user-id">{identity.userId ?? 'anonymous'}</code></p>
        <p>Device ID: <code id="device-id">{identity.deviceId ?? 'not initialized'}</code></p>
      </aside>
    </main>
  );
}
```

src/style.css

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

On logout, `reset` clears the SDK user ID and creates a new device ID. It doesn't delete server-side profiles or start a new analytics session. The next visit has the new identity; a reload during a valid sign-in restores the server account before another visit is recorded.

The auth request completes independently of telemetry. The logout handler doesn't wait for an analytics upload before clearing SDK identity. A failed session request leaves the current UI state and analytics identity unchanged.

## 5. Mount and test the app

I'll start the app once outside the React component tree and retain Strict Mode. The tests exercise the operation or session behavior separately from the UI.

src/main.jsx

```jsx
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.jsx';
import { sessionRequest } from './session.js';
import { initializeAnalytics } from './analytics.js';
import './style.css';

async function start() {
  const session = await sessionRequest('session');
  const analytics = await initializeAnalytics(session);
  createRoot(document.getElementById('root')).render(<StrictMode><App session={session} analytics={analytics} /></StrictMode>);
}
start().catch((error) => {
  document.getElementById('root').textContent = `Could not load the session: ${error.message}. Reload to retry.`;
});
```

tests/session.test.mjs

```javascript
import test from 'node:test';
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { createDemoServer } from '../server/server.mjs';

test('real local session lifecycle rejects bad credentials and cross-origin writes', async (t) => {
  const server = createDemoServer(); server.listen(0, '127.0.0.1'); await once(server, 'listening');
  t.after(() => new Promise((resolve) => server.close(resolve)));
  const origin = `http://127.0.0.1:${server.address().port}`;
  const post = (route, body, cookie, requestOrigin = origin) => fetch(`${origin}/api/${route}`, {
    method: 'POST', headers: { Origin: requestOrigin, 'Content-Type': 'application/json', ...(cookie ? { Cookie: cookie } : {}) }, body: JSON.stringify(body),
  });
  assert.equal((await (await fetch(`${origin}/api/session`)).json()).state, 'anonymous');
  assert.equal((await post('login', { username: 'alex', password: 'wrong' })).status, 401);
  assert.equal((await post('login', { username: 'alex', password: 'local-demo-password' }, null, 'https://other.example')).status, 403);
  const login = await post('login', { username: 'alex', password: 'local-demo-password' });
  assert.equal(login.status, 200);
  const setCookie = login.headers.get('set-cookie'); assert.match(setCookie, /HttpOnly; SameSite=Strict/);
  const cookie = setCookie.split(';')[0];
  const current = await (await fetch(`${origin}/api/session`, { headers: { Cookie: cookie } })).json();
  assert.equal(current.user.id, 'build-login-alex-v1');
  assert.equal((await post('logout', {}, cookie)).status, 200);
  assert.equal((await (await fetch(`${origin}/api/session`, { headers: { Cookie: cookie } })).json()).state, 'expired');
  const sam = await post('login', { username: 'sam', password: 'local-demo-password' });
  assert.equal((await sam.json()).user.id, 'build-login-sam-v1');
});
```

Terminal

```sh
pnpm test
pnpm build
pnpm start
```

Open `http://127.0.0.1:5190`.

## Verify it worked

Follow the sequence in one browser and compare actual event identities, rather than only the labels on the page.

1. **Local session:** With a blank analytics key, sign in as Alex, reload, and sign out. Confirm the real local session works while analytics stays disabled. Add the test key and rebuild. If the page asks you to clear an earlier sign-in, use the explicit sign-out button before the sequence.
2. **Before login:** Record a visit and note the device ID. Try an incorrect password and confirm no session is created. Then sign in as Alex and record another visit. The user ID becomes `build-login-alex-v1` and the device ID remains the same.
3. **Reload and logout:** Reload while signed in, then record a visit. Confirm the account and device ID are unchanged. Sign out, confirm the SDK user ID is anonymous and the device ID changes, then record another visit. Sign in as Sam and record again.
4. **Transport and processed events:** Confirm uploads return HTTP 200. Inspect individual event bodies with Instrumentation Explorer; SDK request compression can make the Network payload view unreadable. In User Lookup, find Alex and Sam by their stable IDs and inspect Activity. Events normally populate in ten seconds to one minute. Match event times and device IDs, including the anonymous event preceding each sign-in.
5. **Identity boundary:** In raw event data, the first visit has no `user_id`; the Alex visits have `build-login-alex-v1` and the original device ID. The post-logout visit has no `user_id` and the new device ID, which is also used for the following Sam visit. Earlier anonymous activity can appear in a known user's profile after identification; inspect raw fields to distinguish capture-time identity from the merged profile.

## Troubleshooting

### Every anonymous reload gets a new device ID

Remove `reset` from render, effects, and null-user branches. Keep it at a confirmed sign-out boundary. A loading or failed session lookup doesn't establish that the person signed out.

### Signed-in visits have the wrong user

Use the stable ID returned by the authenticated server session. Set it before the next tracked action, and wait for session restoration before rendering the controls. Don't use a display name or client-selected account ID as proof of authentication.

### A previous user is still displayed after server restart

The demo's in-memory sessions are gone, while analytics can retain a cached identity. Use Sign out and clear identity. The demo blocks visit recording until that explicit boundary rather than silently treating missing state as logout.

### Login or logout fails

Use the printed loopback URL and keep the local server running. The API accepts same-origin JSON POST requests. An incorrect demo password leaves the current identity unchanged; a server/network error should be retried deliberately.

### There are no events after a successful login

Login sets identity; it doesn't send a visit automatically. Click Record a visit. Check the ingestion key and data center, rebuild after changing Vite environment variables, and inspect upload status separately from the local session.

## Full code reference

The [complete runnable example](https://github.com/amplitude/ampli-examples/tree/6094858f8db8396891e488649ead49482dc8e1db/browser/javascript/v2/react-login-identity) includes the lockfile. These are the complete application and test files, combined for copying. Keep environment values local.

Full code reference

```text
===== package.json =====
{
  "name": "amplitude-react-login-identity",
  "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",
    "start": "node server/server.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>Login identity 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

===== server/server.mjs =====
import http from 'node:http';
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const demoPassword = scryptSync('local-demo-password', 'local-build-demo', 32);
const users = {
  alex: { id: 'build-login-alex-v1', name: 'Alex' },
  sam: { id: 'build-login-sam-v1', name: 'Sam' },
};
const defaultRoot = fileURLToPath(new URL('../dist/', import.meta.url));

export function createDemoServer({ staticRoot = defaultRoot } = {}) {
  const sessions = new Map();
  return http.createServer(async (req, res) => {
    if (!/^127\.0\.0\.1:\d+$/.test(req.headers.host ?? '')) {
      res.writeHead(400); return res.end('Use the printed loopback URL.');
    }
    const origin = `http://${req.headers.host}`;
    const url = new URL(req.url, origin);
    const token = req.headers.cookie?.split(';').map((v) => v.trim())
      .find((v) => v.startsWith('build_demo_session='))?.split('=')[1];
    const session = token && sessions.get(token);
    const user = session && session.expiresAt > Date.now() ? users[session.username] : null;
    function json(status, body, cookie) {
      res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store',
        ...(cookie ? { 'Set-Cookie': cookie } : {}) });
      res.end(JSON.stringify(body));
    }
    try {
      if (url.pathname.startsWith('/api/')) {
        if (req.method === 'GET' && url.pathname === '/api/session') {
          return json(200, { user, state: user ? 'signed_in' : token ? 'expired' : 'anonymous' });
        }
        if (req.method !== 'POST' || req.headers.origin !== origin
          || !req.headers['content-type']?.startsWith('application/json')) {
          return json(403, { error: 'Use a same-origin JSON POST.' });
        }
        let body = '';
        for await (const chunk of req) {
          body += chunk;
          if (body.length > 2048) return json(413, { error: 'Request too large.' });
        }
        const input = JSON.parse(body || '{}');
        if (url.pathname === '/api/login') {
          const candidate = scryptSync(String(input.password ?? '').slice(0, 128), 'local-build-demo', 32);
          if (!Object.hasOwn(users, input.username) || !timingSafeEqual(candidate, demoPassword)) {
            return json(401, { error: 'The demo credentials did not match.' });
          }
          if (token) sessions.delete(token);
          const nextToken = randomBytes(32).toString('hex');
          sessions.set(nextToken, { username: input.username, expiresAt: Date.now() + 3600000 });
          return json(200, { user: users[input.username], state: 'signed_in' },
            `build_demo_session=${nextToken}; HttpOnly; SameSite=Strict; Path=/; Max-Age=3600`);
        }
        if (url.pathname === '/api/logout') {
          if (token) sessions.delete(token);
          return json(200, { user: null, state: 'anonymous' },
            'build_demo_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0');
        }
        return json(404, { error: 'Unknown demo endpoint.' });
      }
      if (req.method !== 'GET') { res.writeHead(405); return res.end(); }
      let filename = path.resolve(staticRoot, '.' + decodeURIComponent(url.pathname));
      if (url.pathname === '/') filename = path.join(staticRoot, 'index.html');
      if (!filename.startsWith(path.resolve(staticRoot) + path.sep)) {
        res.writeHead(403); return res.end();
      }
      const data = await readFile(filename);
      const mime = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css' };
      res.writeHead(200, { 'Content-Type': mime[path.extname(filename)] ?? 'application/octet-stream', 'Cache-Control': 'no-store' });
      res.end(data);
    } catch (error) {
      json(error.code === 'ENOENT' ? 404 : 400, { error: 'The demo request could not be completed.' });
    }
  });
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  createDemoServer().listen(5190, '127.0.0.1', () => console.log('Local demo: http://127.0.0.1:5190'));
}

===== src/session.js =====
export async function sessionRequest(path, body) {
  const response = await fetch(`/api/${path}`, body === undefined ? {
    credentials: 'same-origin', cache: 'no-store',
  } : {
    method: 'POST', credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
  });
  const result = await response.json();
  if (!response.ok) throw new Error(result.error ?? 'Session request failed.');
  return result;
}

===== src/analytics.js =====
import * as amplitude from '@amplitude/unified';

let ready;
let enabled = false;
export function initializeAnalytics(session) {
  const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
  if (!apiKey) return Promise.resolve({ status: 'disabled', needsSignout: false });
  if (!ready) {
    ready = amplitude.initAll(apiKey, {
      instanceName: 'build-login-identity',
      serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
      analytics: { autocapture: false, remoteConfig: { fetchRemoteConfig: false } },
      sessionReplay: { sampleRate: 0 }, engagement: { skip: true },
    }).then(() => {
      enabled = true;
      if (session.user) amplitude.setUserId(session.user.id);
      // Don't reset for null/loading state. An explicit sign-out clears stale identity.
      return { status: 'ready', needsSignout: !session.user && Boolean(amplitude.getUserId()) };
    }).catch((error) => {
      console.error('Analytics initialization failed', error);
      return { status: 'error', needsSignout: false };
    });
  }
  return ready;
}

export function analyticsIdentity() {
  return enabled ? { userId: amplitude.getUserId() ?? null, deviceId: amplitude.getDeviceId() } : { userId: null, deviceId: null };
}
export function identifySignedInUser(user) {
  if (enabled) amplitude.setUserId(user.id);
}
export function resetAfterSignout() {
  if (enabled) amplitude.reset();
}
export async function trackDemoVisit(signedIn) {
  if (!enabled) return 'Analytics disabled; the local session still works.';
  const result = await amplitude.track('Identity Demo Viewed', {
    auth_state: signedIn ? 'signed_in' : 'anonymous',
  }).promise;
  if (result.code !== 200) throw new Error(`Visit upload: ${result.message}`);
  return 'Visit event accepted. Check the identity in Amplitude.';
}

===== src/App.jsx =====
import React, { useRef, useState } from 'react';
import { sessionRequest } from './session.js';
import { analyticsIdentity, identifySignedInUser, resetAfterSignout, trackDemoVisit } from './analytics.js';

export function App({ session: initialSession, analytics }) {
  const [session, setSession] = useState(initialSession);
  const [identity, setIdentity] = useState(analyticsIdentity);
  const [needsSignout, setNeedsSignout] = useState(analytics.needsSignout || initialSession.state === 'expired');
  const [username, setUsername] = useState('alex');
  const [password, setPassword] = useState('local-demo-password');
  const [busy, setBusy] = useState(false);
  const pending = useRef(false);
  const [message, setMessage] = useState('Ready. Record a visit, then sign in.');
  async function run(action) {
    if (pending.current) return;
    pending.current = true; setBusy(true);
    try { await action(); setIdentity(analyticsIdentity()); }
    catch (error) { setMessage(error.message); }
    finally { pending.current = false; setBusy(false); }
  }
  async function login(event) {
    event.preventDefault();
    await run(async () => {
      const result = await sessionRequest('login', { username, password });
      identifySignedInUser(result.user);
      setSession(result); setMessage(`Signed in as ${result.user.name}. Record a visit.`);
    });
  }
  async function logout() {
    await run(async () => {
      const result = await sessionRequest('logout', {});
      resetAfterSignout();
      setSession(result); setNeedsSignout(false);
      setMessage('Signed out. The next visit uses a new device ID.');
    });
  }
  return (
    <main>
      <p className="eyebrow">LOCAL SESSION DEMO</p><h1>Login and analytics identity</h1>
      <p>This local-only example has two seeded demo users, Alex and Sam. Use local-demo-password for either. Sessions are kept in server memory and expire after one hour; restarting the server invalidates them. Use your existing auth system in a real app.</p>
      <p id="session-state">Session: {session.user?.name ?? session.state}</p>
      {needsSignout ? <p>Clear the previous sign-in before recording another visit.</p> : !session.user && (
        <form onSubmit={login}>
          <label htmlFor="username">Demo user</label>
          <select id="username" value={username} disabled={busy} onChange={(e) => setUsername(e.target.value)}>
            <option value="alex">Alex</option><option value="sam">Sam</option>
          </select>
          <label htmlFor="password">Demo password</label>
          <input id="password" type="password" value={password} disabled={busy} onChange={(e) => setPassword(e.target.value)} />
          <button id="login" disabled={busy}>Sign in</button>
        </form>
      )}
      {(session.user || needsSignout) && <button id="logout" disabled={busy} onClick={logout}>Sign out and clear identity</button>}
      <button id="visit" disabled={busy || needsSignout} onClick={() => run(async () => setMessage(await trackDemoVisit(Boolean(session.user))))}>Record a visit</button>
      <p role="status">{busy ? 'Working...' : message}</p>
      <aside>
        <p>Analytics: <strong id="analytics-status">{analytics.status}</strong></p>
        <p>User ID: <code id="user-id">{identity.userId ?? 'anonymous'}</code></p>
        <p>Device ID: <code id="device-id">{identity.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 { App } from './App.jsx';
import { sessionRequest } from './session.js';
import { initializeAnalytics } from './analytics.js';
import './style.css';

async function start() {
  const session = await sessionRequest('session');
  const analytics = await initializeAnalytics(session);
  createRoot(document.getElementById('root')).render(<StrictMode><App session={session} analytics={analytics} /></StrictMode>);
}
start().catch((error) => {
  document.getElementById('root').textContent = `Could not load the session: ${error.message}. Reload to retry.`;
});

===== tests/session.test.mjs =====
import test from 'node:test';
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { createDemoServer } from '../server/server.mjs';

test('real local session lifecycle rejects bad credentials and cross-origin writes', async (t) => {
  const server = createDemoServer(); server.listen(0, '127.0.0.1'); await once(server, 'listening');
  t.after(() => new Promise((resolve) => server.close(resolve)));
  const origin = `http://127.0.0.1:${server.address().port}`;
  const post = (route, body, cookie, requestOrigin = origin) => fetch(`${origin}/api/${route}`, {
    method: 'POST', headers: { Origin: requestOrigin, 'Content-Type': 'application/json', ...(cookie ? { Cookie: cookie } : {}) }, body: JSON.stringify(body),
  });
  assert.equal((await (await fetch(`${origin}/api/session`)).json()).state, 'anonymous');
  assert.equal((await post('login', { username: 'alex', password: 'wrong' })).status, 401);
  assert.equal((await post('login', { username: 'alex', password: 'local-demo-password' }, null, 'https://other.example')).status, 403);
  const login = await post('login', { username: 'alex', password: 'local-demo-password' });
  assert.equal(login.status, 200);
  const setCookie = login.headers.get('set-cookie'); assert.match(setCookie, /HttpOnly; SameSite=Strict/);
  const cookie = setCookie.split(';')[0];
  const current = await (await fetch(`${origin}/api/session`, { headers: { Cookie: cookie } })).json();
  assert.equal(current.user.id, 'build-login-alex-v1');
  assert.equal((await post('logout', {}, cookie)).status, 200);
  assert.equal((await (await fetch(`${origin}/api/session`, { headers: { Cookie: cookie } })).json()).state, 'expired');
  const sam = await post('login', { username: 'sam', password: 'local-demo-password' });
  assert.equal((await sam.json()).user.id, 'build-login-sam-v1');
});
```

## Hand it to your agent

Use this prompt to adapt the example to an existing application.

Implementation prompt

```text
Use https://amplitude.com/build/react-login-identity and its linked source.
Inspect the current SDK entry point and application flow first. Merge into existing
files; preserve auth, consent, routes, and other instrumentation. Fetch current
Amplitude docs for the installed SDK. Keep the ingestion key in the existing
environment mechanism and never add server secrets to browser code.

Use the authenticated session's stable account ID with setUserId before the next
event. Resolve session loading before rendering analytics-triggering controls.
Never reset in a render/effect just because user is null. Call reset after
confirmed logout and verify that the next anonymous visit uses a new device ID.
Handle a cached analytics identity that disagrees with the confirmed auth state
through the explicit sign-out lifecycle. Keep failed auth requests from changing
identity. Preserve current consent and product settings. The seeded loopback
server is only a runnable local fixture, not production auth.

Test blank-key startup and failure paths as well as success. Confirm real SDK
uploads and processed data separately from local tests. Report changed files and
remaining coverage limits.
```

## What this unlocks

[Product analytics](https://amplitude.com/amplitude-analytics) can connect `Identity Demo Viewed` to a stable account while retaining the event's capture-time identity.

[Session replay](https://amplitude.com/session-replay) can add context to authenticated journeys when enabled and configured separately.

[Feature flags](https://amplitude.com/feature-management) can use consistent application identity in a later configured implementation.

[Guides and surveys](https://amplitude.com/guides-and-surveys) can support an authenticated experience when enabled separately with its targeting configured.

## Frequently asked questions

### Does reset erase the user's history?

No. It clears the SDK user ID and generates a new device ID for later activity in this browser. It doesn't remove the user's stored Amplitude profile or events.

### Does reset start a new session?

No. Identity and analytics session boundaries are separate. This example verifies user and device IDs; it doesn't claim logout creates a new analytics session.

### Can I use an auth provider instead of this server?

Use the confirmed login, session-restoration, and logout lifecycle from your existing auth system. Keep the identity calls at those boundaries and test its loading/error behavior. The local fixture doesn't verify a named provider integration.

## Next steps

[Web frameworksReact product analyticsInstall analytics and track deliberate business events.](https://amplitude.com/build/react-product-analytics)[Use caseCustom events alongside autocaptureSeparate interaction capture from confirmed outcomes.](https://amplitude.com/build/react-custom-events)[Use caseStitch client and server eventsUse a consistent identity across browser and backend events.](https://amplitude.com/build/stitch-client-server-events)

Reference docs

[Install the Browser Unified SDK →](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/get-started)[Identity reference →](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/reference#identity)[Manage user identity →](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/instrument-and-configure#manage-identity)[Track unique users →](https://amplitude.com/docs/data/sources/instrument-track-unique-users)[Debug analytics →](https://amplitude.com/docs/analytics/debug-analytics)[Docs MCP server →](https://amplitude.com/docs/amplitude-ai/docs-mcp-server)

Amplitude is the leading [all-in-one analytics platform](https://amplitude.com/) for building better products. Product and engineering teams use Amplitude to connect [product analytics](https://amplitude.com/amplitude-analytics) and [web analytics](https://amplitude.com/web-analytics) with [session replay](https://amplitude.com/session-replay), [heatmaps](https://amplitude.com/heatmaps), [experimentation](https://amplitude.com/amplitude-experiment), [feature flags](https://amplitude.com/feature-management), and [guides and surveys](https://amplitude.com/guides-and-surveys) in one unified workflow, with [AI agents](https://amplitude.com/ai-agents) working across all of it. Learn how Amplitude is building [self-improving products](https://amplitude.com/self-improving-products) with [Wave](https://amplitude.com/wave), helping teams turn product data into PRs.

For agents

[View raw .md](/build/react-login-identity.md)[llms.txt](/llms.txt)

## Connect the next event

Make the identity and properties explicit, then verify them in your test project.

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