On this page

Cookies and Consent Management (JavaScript SDK)

Legacy JavaScript SDK

This guide covers the legacy JavaScript SDK. For new implementations, use the Browser SDK 2 cookies and consent management guide, which covers the current TypeScript SDK.

New customers must use the new TypeScript SDK (Browser SDK 2). Existing customers should consider migrating to Browser SDK 2 for the latest features and improvements.

This guide covers how Amplitude works with cookies, local storage, opt-in/opt-out options, and consent management (including CNIL regulations for France) when you use the legacy JavaScript SDK.

Recommended migration

For the most up-to-date cookies and consent management features, migrate to Browser SDK 2 and use the Browser SDK 2 cookies and consent management guide.

Amplitude cookies

A "cookie" is a piece of data from a website that the browser stores on a user's device. Websites retrieve cookies later to access data stored for functional or technical purposes. After initialization, the Amplitude SDK creates a cookie that begins with the prefix AMP_ and ends with the first 10 digits of your project API key. You can customize this prefix with the constant COOKIE_PREFIX in the SDK's constants.js file. The SDK defines the cookie's value in amplitude-client.js.

For example, if you use the default value for the prefix with the following:

js
amplitude.getInstance().init("a2dbce0e18dfe5f8e...");

The Amplitude Browser 2.0 SDK creates a cookie with the format AMP_ followed by the first 10 characters of your project's API key.

In previous SDK versions, you could customize the key for this cookie at initialization with the cookieName option. This no longer works, but if you use older SDK versions, the cookie name may differ from the standard name.

If another cookie appears with the key amplitude_cookie_test followed by a random base64 suffix, the SDK uses the cookie to test whether the user has cookies enabled. The SDK removes this cookie when the test completes. For more information, refer to the SDK's base-cookie.js file.

Sometimes, the SDK doesn't remove the amplitude_test_cookie cookie. In this case, the cookie remains in the cookie list but isn't used. You can customize the key of this cookie with the COOKIE_TEST_PREFEX constant in the SDK's constants.js file.

The SDK uses the cookie to track the following metadata:

  • deviceId: A randomly generated string.
  • userId: When a user logs in, if your app sends this value to Amplitude, the SDK stores it in the cookie. Set this value to uniquely identify users. Amplitude encodes this value as Base64 before storing it.
  • optOut: A flag that opts this device out of Amplitude tracking. When this flag is set, Amplitude stores no extra information about the user.
  • sessionId: A randomly generated string for each session.
  • lastEventTime: Time of the last event, used to decide when to expire and create a new session ID.
  • eventId: An incrementing sequence of identifiers that distinguishes events.
  • identifyId: An incrementing sequence of identifiers that distinguishes identify calls.
  • sequenceNumber: A sequence number that orders events and identify calls.

When the Amplitude JavaScript SDK loads, it checks the cookie for an Amplitude device_id (which exists if the user is returning and generated a device_id in a previous visit). If found, the SDK uses that value. Otherwise (for a new user or one who recently cleared cookies), the SDK randomly generates a device_id and saves it to the cookie.

Cookie size can vary from a minimum of 60 bytes to about 120 bytes. Because Amplitude can store two cookies (amp_* and amp_*.organization.domain), assume 120 bytes as a safe average size for Amplitude cookies per project API key.

Expiration time

The Amplitude SDK has a cookieExpiration option that lets you set the number of days until a cookie expires. Before SDK version 7.0, the default value was 10 years. After SDK version 7.0, cookieExpiration defaults to one year. Most browsers limit the lifetime of cookies set through document.cookie to between one and seven days.

Remove Amplitude cookies

To programmatically remove the Amplitude cookie, use the JavaScript SDK's clearStorage() method. This method clears all cookies and deletes any metadata stored on them.

Deprecated cookies

The following cookie keys are deprecated in the latest SDK versions:

  • amplitude_id_<API_KEY>.your_org_domain: In previous versions of the Amplitude JavaScript SDK, the default cookie key was amplitude_id. This may appear in projects that use an SDK version earlier than 6.0.0. In that case, the cookie key is amplitude_id_<PROJECT_API_KEY>.organization.domain.

  • amplitude_test.your_org_domain: The Amplitude SDK uses this cookie to test more thoroughly if cookies are available. By default, the key is amplitude_cookie_test, and the SDK removes this cookie after the test.

Disable cookies using LocalStorage (opt-out cookies)

The cookie contains data necessary for Amplitude to function correctly. It saves deviceId, sessionId, and the last event's timestamp. To store this information in a user's local storage instead, set disableCookies to true in the SDK's options.js file.

Data stored in local storage

Besides the information managed in the cookie, Amplitude uses local storage for:

  • Online events: The saveEvents option in the SDK's options.js controls this storage (defaults to true). Amplitude stores every event it receives and removes it after successful upload. When set to false, events may be lost if the user navigates to another page before upload completes.
  • Offline events: The savedMaxCount option in the SDK's options.js sets the number of offline events (defaults to 1000). If Amplitude logs more than 1000 events offline, the SDK removes the oldest events from storage.
  • Failed events: The SDK stores any failed event here for retry.

Amplitude stores this data in the following keys:

  • amplitude_unsent_<PROJECT_API_KEY>: Stores unsent events. You can customize its name with the unsentIdentifyKey option in the SDK's options.js.
  • amplitude_unsent_identify_<PROJECT_API_KEY>: Stores unsent identify calls. You can customize its name with the unsentKey option in the SDK's options.js.

Local storage limitations

Local Storage restricts access by subdomain. For example, if you track non-identified users across subdomains like www.amplitude.com and analytics.amplitude.com, the device_id value for each subdomain isn't available while browsing the other.

The Amplitude SDK supports cross-site tracking with the deviceIdFromURLParam option in the SDK's options.js. When set to true, the SDK captures the amp_device_id parameter from the URL. For more information, refer to JavaScript SDK Cross-domain tracking.

Other auto-captured properties aren't affected by using LocalStorage instead of a cookie. For full detail, refer to User property definitions.

This action disables cookie storage, but Amplitude stores the same data in the user's browser Local Storage. It isn't a valid option for a user that wants to fully opt out.

Disable cookies and local storage / session storage (opt-out storage)

When you disable cookies and the user disables local storage and session storage, Amplitude creates a new device_id for that user on every visit because the SDK can't find an existing ID. If the user logs in or provides other identifying information, Amplitude's identity resolution system ties the various device_id values together with that user ID. The user must log in on each visit so Amplitude can merge identifiers.

Disabling tracking (opt out tracking)

Users may want to opt out of cookies (which prevents Amplitude from storing any data in the cookie) and also opt out of tracking completely (which means Amplitude doesn't store events or records of their browsing history). The Amplitude SDK provides optOut to fulfill this request. To programmatically opt out of tracking, call amplitude.setOptOut(true).

"Do not track" setting on browsers (DNT flag)

Some browsers have a "Do not track" setting intended to block all tracking. Amplitude doesn't adhere to this setting. The DNT standard isn't widely supported, and the scope of what it disables isn't clear. To honor that setting, write your own code to test for the DNT flag and then set the optOut option in the SDK.

Some jurisdictions require users to consent to non-essential cookies before data collection. You're ultimately responsible for getting necessary consents and making necessary disclosures for the personal data you collect and send to Amplitude. You're also responsible for determining how you classify the Amplitude cookies in your cookie policy based on your specific use case and the jurisdictions in which you use them.

If you use the Amplitude SDK in one of these jurisdictions, don't initialize the SDK until the user consents to your use of cookies. The Amplitude functions (for example, cookie storage, local storage, and tracking events) are enabled or disabled at SDK initialization.

To support this, the JavaScript SDK offers a deferInitialization option (defaults to null). When set to true, this option disables the core SDK functions, including saving a cookie (or anything to local storage) and all tracking, until you explicitly enable them. The SDK instance loads without storage and tracking until you call amplitude.getInstance().enableTracking().

When you call amplitude.getInstance().enableTracking(), the SDK sets deferInitialization to false and Amplitude creates the cookie with the options values you configured, as shown in client.js:

js
/**
 * Enable tracking via logging events and dropping a cookie
 * Intended to be used with the deferInitialization configuration flag
 * This will drop a cookie and reset initialization deferred
 * @public
 */
AmplitudeClient.prototype.enableTracking = function enableTracking() {
  // This will call init (which drops the cookie) and will run any pending tasks
  this._initializationDeferred = false;
  f(this);
  this.runQueuedFunctions();
};

/**
 * Saves deviceId, userId, event meta data to amplitude cookie
 * @private
 */
var _saveCookieData = function _saveCookieData(scope) {
  const cookieData = {
    deviceId: scope.options.deviceId,
    userId: scope.options.userId,
    optOut: scope.options.optOut,
    sessionId: scope._sessionId,
    lastEventTime: scope._lastEventTime,
    eventId: scope._eventId,
    identifyId: scope._identifyId,
    sequenceNumber: scope._sequenceNumber,
  };
  if (scope._useOldCookie) {
    scope.cookieStorage.set(
      scope.options.cookieName + scope._storageSuffix,
      cookieData,
    );
  } else {
    scope._metadataStorage.save(cookieData);
  }
};

This doesn't affect users who already have an Amplitude cookie, as shown in amplitude-client.js. At some point, the user provided consent, which is all Amplitude needs to create the cookie legitimately. To opt that user out of tracking, you must remove any Amplitude cookies that already exist for that user.

The presence of an Amplitude Analytics cookie determines whether Amplitude tracks a user's events. For users who have one, consider the following:

  1. If you manually set cookieExpiration to a short lifespan, you may need to run amplitude.getInstance().enableTracking() when the Amplitude Analytics cookie expires or when the user logs in.

  2. If the user removes all cookies, they see the consent banner again the next time they visit your app. Because no Amplitude Analytics cookie exists yet, the flow proceeds as described in the Managing cookie consent section, and the initialization of storage and tracking options waits when you use deferInitialization = true.

  3. If the user consented to the Amplitude Analytics cookie in the past and that consent has expired for any reason (website cookie deletion, consent tracking expired), Amplitude prompts the user for consent again. If the user declines, you must explicitly remove the Amplitude Analytics cookie. Otherwise, the SDK continues to collect the user's information against their will.

Getting the SDK initialization options per project

From any site that uses the Amplitude JavaScript SDK, you can find which initialization options are set. Run the following command from the JavaScript console in the browser you use to access the site:

js
amplitude.getInstance().options;

The console displays each option alongside its value. For example, on amplitude.com you may see the following.

API options in Amplitude Event Explorer Chrome extension

If you use the Amplitude Event Explorer Chrome extension, you can access the initialization options values in the "API Options" tab after selecting the project you're interested in.

If the Amplitude object instance isn't stored in the window object, this information isn't available from the console or the Chrome extension. This usually happens when you use Node.js instead of the JavaScript SDK.

The error in the console appears like this.

Storage options explained

This table gives a brief overview of each storage-related option.

OptionDefault ValueDefinition
cookieExpiration365The number of days after which the Amplitude cookie expires. The default 12 months supports GDPR compliance.
cookieForceUpgradeFalseForces SDK pre-v6.0.0 instances to adopt SDK post-v6.0.0 compatible cookie formats.
deferInitializationNullWhen true, disables the core functions of the SDK, including saving a cookie and all logging, until you explicitly enable them by calling amplitude.getInstance().enableTracking().
deviceIdFromUrlParamFalseWhen true, the SDK parses device ID values from the URL parameter amp_device_id if available. This option supports cross-domain tracking. Device IDs defined in the configuration options during init take priority over device IDs from URL parameters.
disableCookieFalseDisables Amplitude cookies altogether.
domainThe top domain of the current page's URLSets a custom domain for the Amplitude cookie. To include subdomains, add a preceding period, for example, .amplitude.com.
optOutFalseDisables tracking for the current user.
sameSiteCookieNoneSets the SameSite flag on the Amplitude cookie. Decides cookie privacy policy.
saveEventsTrueWhen true, the SDK saves events to local storage and removes them after successful upload. Without saving events, the SDK may lose them if the user navigates to another page before upload completes.
savedMaxCount1000Maximum number of events to save in Local Storage. If the SDK logs more events while offline, it removes the oldest events.
secureCookieFalseWhen true, the SDK sets the Amplitude cookie with the Secure flag. The Secure flag lets the browser send this cookie only on encrypted HTTPS transmissions. This ensures that your cookie isn't visible to an attacker in a man-in-the-middle attack.
unsentIdentifyKeyamplitude_unsent_identifylocalStorage key that stores unsent identify calls.
unsetKeyamplitude_unsentlocalStorage key that stores unsent events.

Abstraction layer for storage

You can find the storage abstraction layer, available options, and stored metadata in Amplitude's GitHub:

The SDK sets the options at initialization. For cookie and metadata storage, this happens in the Init method for the Amplitude client:

js
this.options.apiKey = apiKey;
this._storageSuffix =
  "_" +
  apiKey +
  (this._instanceName === Constants.DEFAULT_INSTANCE
    ? ""
    : "_" + this._instanceName);
this._storageSuffixV5 = apiKey.slice(0, 6);

this._oldCookieName = this.options.cookieName + this._storageSuffix;
this._unsentKey = this.options.unsentKey + this._storageSuffix;
this._unsentIdentifyKey = this.options.unsentIdentifyKey + this._storageSuffix;

this._cookieName = Constants.COOKIE_PREFIX + "_" + this._storageSuffixV5;

this.cookieStorage.options({
  expirationDays: this.options.cookieExpiration,
  domain: this.options.domain,
  secure: this.options.secureCookie,
  sameSite: this.options.sameSiteCookie,
});

this._metadataStorage = new MetadataStorage({
  storageKey: this._cookieName,
  disableCookies: this.options.disableCookies,
  expirationDays: this.options.cookieExpiration,
  domain: this.options.domain,
  secure: this.options.secureCookie,
  sameSite: this.options.sameSiteCookie,
  storage: this.options.storage,
});

const hasOldCookie = !!this.cookieStorage.get(this._oldCookieName);
const hasNewCookie = !!this._metadataStorage.load();
this._useOldCookie =
  !hasNewCookie && hasOldCookie && !this.options.cookieForceUpgrade;
const hasCookie = hasNewCookie || hasOldCookie;

Frequently asked questions

CNIL France - Frequently asked questions

CNIL France FAQs

CNIL FAQs aren't intended as legal or regulatory advice and don't constitute any warranty or contractual commitment from Amplitude. Amplitude encourages customers to seek independent legal advice on legal and regulatory obligations related to this subject matter.

Was this helpful?