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

  1. The deviceId option.
  2. The ampDeviceId URL parameter, then the legacy deviceId URL parameter.
  3. The AMP_ cookie.
  4. A cookie from the maintenance JavaScript SDK (amp_ prefix).
  5. A new UUID.

User ID

  1. The userId argument or option.
  2. The AMP_ cookie.
  3. A cookie from the maintenance JavaScript SDK.

Session ID

  1. The sessionId option.
  2. The ampSessionId URL parameter.
  3. A session deferred by opt-out.
  4. The AMP_ cookie, if the last event was within sessionTimeout.
  5. 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.

ts
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:

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

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

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

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

ts
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 sessionTimeout after 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_start at the start of each session and session_end at the end of the previous one. Amplitude shows them as [Amplitude] Start Session and [Amplitude] End Session. The SDK sends session_end when the next session starts, not when the user leaves.
  • With autocapture.attribution.resetSessionOnNewCampaign set to true, a new campaign also starts a new session.

To change the timeout, set sessionTimeout in milliseconds:

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

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

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

  1. On the source domain, read the current IDs and add them to the link:

    ts
    const 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());
    
  2. On the destination domain, initialize the SDK without deviceId or sessionId options. The SDK reads the parameters automatically.

    ts
    amplitude.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.

ts
amplitude.setOptOut(true);

// Later, after the user consents:
amplitude.setOptOut(false);

While opt-out is on:

  • Every tracking call resolves immediately with code 0 and Event 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 call setOptOut(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.

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

これは役に立ちましたか?

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.

このページでは