Manage identity and sessions in Browser SDK 2
Browser SDK 2 attaches three identifiers to every event: a device ID, an optional user ID, and a session ID. Amplitude uses them to merge events into users and sessions. The SDK stores all three, plus the opt-out flag, in a first-party cookie named AMP_ followed by the first 10 characters of your API key, so they persist across page loads and subdomains.
How the SDK chooses identifiers on load
During init(), the SDK takes each identifier from the first source that has a value.
Device ID
- The
deviceIdoption. - The
ampDeviceIdURL parameter, then the legacydeviceIdURL parameter. - The
AMP_cookie. - A cookie from the maintenance JavaScript SDK (
amp_prefix). - A new UUID.
User ID
- The
userIdargument or option. - The
AMP_cookie. - A cookie from the maintenance JavaScript SDK.
Session ID
- The
sessionIdoption. - The
ampSessionIdURL parameter. - A session deferred by opt-out.
- The
AMP_cookie, if the last event was withinsessionTimeout. Date.now().
The SDK ignores the URL parameters when an ampTimestamp parameter is present and earlier than the current time. Go to Track users across domains.
Set the user ID
Call setUserId() when a user signs in. Use a stable, unique identifier from your system, such as a database ID. Avoid email addresses if they can change.
amplitude.setUserId("user-12345");
The new user ID applies to every later event and persists in the cookie. User IDs and device IDs must be at least five characters, or Amplitude rejects the event. To allow shorter IDs, set minIdLength in init().
If you know the user ID at page load, pass it to init() instead, so the first autocaptured events carry it:
amplitude.init("AMPLITUDE_API_KEY", "user-12345");
Reset identity when a user signs out
Call reset() when a user signs out. It sets the user ID to undefined and generates a new device ID, so later activity on this browser doesn't merge into the signed-out user.
amplitude.reset();
reset() doesn't start a new session, clear user properties on Amplitude's servers, or change opt-out. Plugins can react to it through their onReset() hook.
Set the device ID
The SDK generates a random UUID as the device ID. Set your own only when you already have a stable anonymous identifier, for example one shared with your server or a mobile app.
amplitude.setDeviceId("2f9d6a1e-4b7c-4f0e-9a51-0c3e8b7d5a12");
Use a value that's unique per device and at least five characters long. Two browsers with the same device ID merge into one user in Amplitude.
Read and update identity together
getIdentity() returns the current device ID, user ID, and the user properties the SDK tracked in this page load. Requires Browser SDK 2.18.0 or later.
const { deviceId, userId, userProperties } = amplitude.getIdentity();
setIdentity() updates any combination of the three. When you include userProperties, the SDK sends an $identify event that sets each key with $set. setIdentity() requires Browser SDK 2.35.0 or later.
amplitude.setIdentity({
userId: "user-12345",
userProperties: { plan: "pro" },
});
setIdentity() doesn't unset properties you leave out of userProperties. To remove a user property, send new amplitude.Identify().unset("key").
userProperties reflects only the $set, $unset, and $clearAll operations sent from this page load. It doesn't read user properties from Amplitude's servers.
How sessions work
A session groups the events a user triggers in one visit. Its ID is the Unix timestamp, in milliseconds, of the session's first event.
- The SDK starts a new session when an event arrives more than
sessionTimeoutafter the previous event. The default timeout is 30 minutes. - Sessions continue across page loads and tabs on the same domain, because the last event time lives in the cookie.
- With session autocapture on (the default), the SDK sends
session_startat the start of each session andsession_endat the end of the previous one. Amplitude shows them as[Amplitude] Start Sessionand[Amplitude] End Session. The SDK sendssession_endwhen the next session starts, not when the user leaves. - With
autocapture.attribution.resetSessionOnNewCampaignset totrue, a new campaign also starts a new session.
To change the timeout, set sessionTimeout in milliseconds:
amplitude.init("AMPLITUDE_API_KEY", {
sessionTimeout: 60 * 60 * 1000, // 1 hour
});
For how Amplitude counts session length and session metrics, go to Track sessions.
Keep a session alive without an event
extendSession() updates the last activity time without sending an event. Use it for activity the SDK can't observe, such as a user watching a long video.
amplitude.extendSession();
Start a session with a specific ID
setSessionId() ends the current session and starts one with the ID you pass. Pass a Unix timestamp in milliseconds.
amplitude.setSessionId(Date.now());
With session autocapture on, the SDK treats the ID as the session's last activity time. If you pass an ID that isn't a recent timestamp, the next event looks more than sessionTimeout late, and the SDK replaces your ID with a new session. setSessionId() does nothing if the ID equals the current session ID.
Track users across domains
The AMP_ cookie covers one registrable domain and its subdomains, such as www.example.com and app.example.com. To keep one anonymous user and session across two different domains, such as example.com and example-shop.com, pass the identifiers in the link URL. The ampDeviceId and ampSessionId parameters require Browser SDK 2.8.0 or later.
On the source domain, read the current IDs and add them to the link:
tsconst url = new URL("https://www.example-shop.com/cart"); url.searchParams.set("ampDeviceId", amplitude.getDeviceId() ?? ""); url.searchParams.set("ampSessionId", String(amplitude.getSessionId())); url.searchParams.set("ampTimestamp", String(Date.now() + 60_000)); window.location.assign(url.toString());On the destination domain, initialize the SDK without
deviceIdorsessionIdoptions. The SDK reads the parameters automatically.tsamplitude.init("AMPLITUDE_API_KEY");
ampTimestamp limits how long the link works. The SDK uses ampDeviceId and ampSessionId only while ampTimestamp is later than the current time. Without ampTimestamp, the parameters never expire, so a shared or bookmarked link can merge unrelated visitors into one device. ampTimestamp requires Browser SDK 2.21.1 or later.
Opt users out of tracking
setOptOut(true) stops the SDK from tracking or uploading events for this browser. The setting persists in the AMP_ cookie.
amplitude.setOptOut(true);
// Later, after the user consents:
amplitude.setOptOut(false);
While opt-out is on:
- Every tracking call resolves immediately with code
0andEvent skipped due to optOut config. - The SDK doesn't start sessions. If
init()runs while opted out, the SDK defers the session and starts it when you callsetOptOut(false). - Page view and attribution tracking start when opt-out turns off.
To start opted out until a user consents, pass optOut: true to init(). For consent banners, deferred initialization, and cookie-free storage, go to Cookies and consent management.
Choose where the SDK stores identity
identityStorage controls where the SDK keeps the device ID, user ID, session ID, and opt-out flag.
| Value | Storage | Shared across subdomains | Persists after the tab closes |
|---|---|---|---|
"cookie" (default) | First-party cookie | Yes | Yes, until cookieOptions.expiration (365 days) |
"localStorage" | localStorage | No | Yes |
"sessionStorage" | sessionStorage | No | No |
"none" | Memory only | No | No, and a reload creates a new device and session |
amplitude.init("AMPLITUDE_API_KEY", {
identityStorage: "localStorage",
});
By default, the SDK writes the cookie on the highest domain it can, such as .example.com, so subdomains share identity. It finds that domain by writing and deleting an AMP_TLDTEST cookie at each level. To pin the domain or change other cookie attributes, set cookieOptions. Go to Cookie options.
Was this helpful?
For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.