
This guide covers how Amplitude Browser SDK 2 works with cookies, local storage, opt-in and opt-out options, and consent management, including CNIL regulations for France.

{% callout type="info" heading="Browser SDK 2 compatibility" %}
This guide covers Browser SDK 2 (TypeScript SDK). For the legacy JavaScript SDK, refer to the [legacy cookies and consent management guide](/docs/sdks/analytics/browser/cookies-and-consent-management-javascript-sdk).
{% /callout %}

## Amplitude cookies

A cookie is a piece of data from a website that browsers store on users' devices. Websites retrieve cookies later to access stored data for functional or technical purposes. After initialization, Amplitude Browser SDK 2 creates cookies that begin with specific prefixes and include the first 10 digits of your project API key.

For example, if you initialize the SDK with:

```ts
import * as amplitude from "@amplitude/analytics-browser";
amplitude.init("a2dbce0e18dfe5f8e...");
```

Amplitude Browser SDK 2 creates cookies with the following format:

- **User session cookies**: `AMP_` with the first 10 characters of your project's API key appended (for example, `AMP_a2dbce0e18`).
- **Marketing campaign cookies**: `AMP_MKTG_` with the first 10 characters of your project's API key appended (for example, `AMP_MKTG_a2dbce0e18`).

### Test cookies

During initialization, the SDK may create temporary test cookies to verify cookie functionality:

- `AMP_TEST_` followed by a timestamp: tests whether cookies work.
- `AMP_TLDTEST_` followed by a timestamp: finds the appropriate subdomain for cookie storage.

The SDK removes these test cookies after testing completes. If they persist, you can safely delete them manually.

### Cookie data

The SDK stores different types of information in cookies:

#### User session cookies (`AMP_*`)

The user session cookie contains metadata the SDK needs to function correctly:

- `deviceId`: a randomly generated string that persists across sessions.
- `userId`: when users log 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.
- `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.
- `lastEventId`: an incrementing sequence of identifiers used to distinguish events.

#### Marketing campaign cookies (`AMP_MKTG_*`)

The marketing campaign cookie stores attribution data:

- UTM parameters (`utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`).
- Referrer information (`referrer`, `referring_domain`).
- Click IDs (`gclid`, `fbclid`, `dclid`, `gbraid`, `wbraid`, `ko_click_id`, `msclkid`, `ttclid`, `twclid`, `li_fat_id`, `rdt_cid`).

### Cookie size

Cookie size varies from approximately 60 bytes to 120 bytes per cookie. With both user session and marketing campaign cookies, expect around 240 bytes total for Amplitude cookies per project API key.

### Expiration time

By default, Amplitude cookies expire after 365 days (1 year). You can customize this with the `cookieOptions.expiration` configuration parameter:

```ts
amplitude.init("API_KEY", {
  cookieOptions: {
    expiration: 30, // Set cookies to expire after 30 days
  },
});
```

### Remove Amplitude cookies

To remove Amplitude cookies programmatically, run the following snippet.

```ts
const API_KEY = "1234567890abcdefghijklmnopqrstuv"; // Replace it with your API KEY
const cookieName = `AMP_${API_KEY.substring(0, 10)}`;
const cookieNameMktg = `AMP_MKTG_${API_KEY.substring(0, 10)}`;
const cookies = document.cookie.split(";");

cookies.forEach((cookie) => {
  const [name] = cookie.trim().split("=");

  if (name === cookieName || name === cookieNameMktg) {
    document.cookie = `${name}=; Max-Age=0; path=/; SameSite=Lax`;
  }
});
```

To anonymize users after they log out, call `reset`.

```ts
amplitude.reset();
```

`reset` does the following:

1. Sets `userId` to `undefined`.
2. Sets `deviceId` to a new UUID value.

With an undefined `userId` and a new `deviceId`, the user appears to Amplitude as a new user.

## Disable cookies using localStorage

Set the `identityStorage` option to configure the SDK to use localStorage rather than cookies.

```ts
amplitude.init("API_KEY", {
  identityStorage: "localStorage",
});
```

### Data stored in local storage

When using localStorage, the SDK stores the same user session information that cookies normally hold, plus:

- **Unsent events**: events that didn't upload successfully to Amplitude.
- **Failed events**: events that failed to send and that the SDK queues for retry.

The SDK stores data in localStorage with keys that include your project API key:

- `AMP_unsent_[API_KEY]`: stores unsent events.

{% callout type="warning" heading="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. For more information, refer to [Cross-domain tracking](/docs/sdks/analytics/browser/browser-sdk-2#cross-domain-tracking).
{% /callout %}

## Disable cookies and local storage (opt-out storage)

You can disable all persistent storage by setting `identityStorage` to `none`:

```ts
amplitude.init("API_KEY", {
  identityStorage: "none",
});
```

When you disable all storage, Amplitude creates a new `device_id` for that user every time they visit your site 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.

## Managing cookie consent

Certain jurisdictions require users to consent to non-essential cookies before you can collect any data. You are ultimately responsible for getting any necessary consents and making any 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.

{% callout type="note" heading="" %}
Amplitude may create cookies as soon as the SDK initializes, regardless of the user's opt-out status. If you require that no cookies exist before consent, defer SDK initialization until after the user provides consent.
{% /callout %}

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. SDK initialization enables or disables Amplitude functions, such as cookie storage, local storage, and event tracking.

### Deferred initialization approach

For consent management, you can track events before cookie consent and initialize the SDK later:

```ts
// Track events
amplitude.track("Button Clicked");

// Later, when user provides consent,
// initialize the SDK
amplitude.init("API_KEY");
```

### Configuration options related to storage

Each storage-related option in Browser SDK 2:

| Option                     | Default value  | Definition                                                                                                                                                                                                      |
| -------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cookieOptions.expiration` | 365            | The number of days after which the Amplitude cookie expires. The default of 12 months supports GDPR compliance.                                                                                                 |
| `cookieOptions.domain`     | `undefined`    | Sets a custom domain for the Amplitude cookie. To include subdomains, add a preceding period, for example: `.amplitude.com`.                                                                                    |
| `cookieOptions.secure`     | `false`        | If `true`, Amplitude sets the cookie with the Secure flag. The Secure flag tells the browser to send this cookie only on encrypted HTTPS transmissions.                                                         |
| `cookieOptions.sameSite`   | `Lax`          | Sets the SameSite flag on the Amplitude cookie. Determines cookie privacy policy.                                                                                                                               |
| `identityStorage`          | `cookie`       | Sets the storage API for user identity. Options include `cookie` for `document.cookie`, `localStorage` for `localStorage`, `sessionStorage` for `sessionStorage`, or `none` to opt out of persisting user identity. |
| `storageProvider`          | `LocalStorage` | Sets a custom implementation of `Storage<Event[]>` to persist unsent events.                                                                                                                                    |

## Abstraction layer for storage

The abstraction layer for storage, the available options, and the stored metadata are available in Amplitude's GitHub repository for the TypeScript SDK:

- [Browser SDK 2 source code](https://github.com/amplitude/Amplitude-TypeScript/tree/main/packages/analytics-browser)
- [Configuration types](https://github.com/amplitude/Amplitude-TypeScript/blob/main/packages/analytics-types/src/config/browser.ts)
- [Cookie storage implementation](https://github.com/amplitude/Amplitude-TypeScript/tree/main/packages/analytics-browser/src/storage)

## Frequently asked questions

{% accordion title="Are Amplitude's cookies first-party or third-party cookies?" %}
Amplitude uses first-party cookies. From a technical standpoint, there's no difference between first-party and third-party cookies. The distinction relates to:

1. The context of a particular visit.
2. Who creates the cookie.

Every cookie has an owner, which is the domain defined in the cookie:

- First-party cookies are issued by a website that a user views directly. If a user lands on a website, for example, fit.amplitude.com, this site creates a cookie that is then saved on the user's computer.
  This is how Amplitude works. When a customer adds Amplitude Browser SDK 2 to their website, the customer (through their website) directly creates the cookie stored in the visitor's computer.

- Third-party cookies are not created by the website being visited, but by someone else. Imagine you're visiting fit.amplitude.com, and the site uses YouTube videos for virtual non-live classes. In this case, YouTube sets the cookie that is saved on the user's computer.

In this case, the website owner embeds pieces of code, provided by YouTube, so that the videos play directly in fit.amplitude.com. When that YouTube code executes in the browser, or the video loads, YouTube can track the player and put data in its cookies. The cookie qualifies as a third-party cookie because a different domain than fit.amplitude.com or amplitude.com creates it.
{% /accordion %}

{% accordion title="Will Google Chrome's plan to remove third party cookies affect Amplitude?" %}
No. Amplitude is not a third-party cookie. Amplitude customers add Amplitude to their website or bundle themselves, and Amplitude sets the cookie in their bundled code through document.cookie, so Amplitude has the privileges of a first-party cookie.
{% /accordion %}

{% accordion title="Why aren't Amplitude cookies marked as `HttpOnly`?" %}
Amplitude's cookies aren't HttpOnly because the purpose of that option is to prevent document.cookie from reading those cookies (since the browser uses them only in client-server communication). The purpose of Amplitude's cookies is the opposite: Amplitude needs to persist data in the browser and store it in document.cookies. Amplitude can't read from the server because Amplitude is client-side code.

If you're concerned that this renders the Amplitude cookie vulnerable to authentication information theft, you shouldn't be. Amplitude stores no authentication information in that cookie, so there's no danger of an XSS attack. The worst thing an attacker could do is steal Amplitude's cookie and take that user's device ID and user ID, which shouldn't be PII to begin with.

If this is a serious concern for you, disable Amplitude's cookies.
{% /accordion %}

{% accordion title="Why aren't Amplitude's cookies marked as secure?" %}
The Secure flag tells the browser to send the cookie only on encrypted HTTPS transmissions. The Secure flag ensures that your cookie isn't visible to an attacker, for example in a man-in-the-middle attack. Amplitude has no authentication information in that cookie or any type of sensitive information, so Amplitude isn't in danger of an XSS attack. The worst thing an attacker could do is steal Amplitude's cookie and take that user's device ID and user ID.

For these reasons, Amplitude doesn't consider this a security vulnerability. However, you can enable the Secure flag if needed:

```ts
amplitude.init("API_KEY", {
  cookieOptions: {
    secure: true,
  },
});
```

{% /accordion %}

{% accordion title="Will cookies cause unsent events to send to a project with a different API key?" %}
No. Browser SDK 2 scopes all stored events with the API key. If a product changes the project (or its API key) it sends events to, those old events don't reach the new project. The SDK stores events in localStorage with keys that include the API key, which ensures proper isolation between different projects.
{% /accordion %}

{% accordion title="How do you integrate with third-party Consent Management Platforms?" %}
Websites and applications can use a consent management platform (CMP) to manage legal consent from users around collecting and processing their personal data through any cookies and other trackers operating on the domain, as applicable privacy laws may require, such as GDPR, CCPA, and ePrivacy. Examples of these tools include OneTrust, Axeptio, and Responsum.

Amplitude doesn't currently have a default integration with any of these tools. Configure your CMP to pass the outcome of the consent to the Amplitude SDK, so that any end user who hasn't provided consent or who has revoked consent (depending on the end user's jurisdiction) opts out of tracking by the Amplitude SDK.

Here's an example integration pattern:

```ts
// Track events
amplitude.track("Button Clicked");

// Initialize when CMP provides consent status
amplitude.init("API_KEY");
```

{% /accordion %}

{% accordion title="Can I use OneTrust with Amplitude to stay GDPR compliant?" %}
Yes, you can use Amplitude with a CMP, like OneTrust, in a GDPR-compliant manner. Amplitude can't direct you on how to classify the Amplitude SDK or cookies. Instead, your privacy and legal teams should make this assessment based on the data you're collecting. Most customers, including in the EU, classify Amplitude cookies as Performance/Analytics cookies.

Customers may also choose to implement through a server-side integration, which bypasses Amplitude's SDK cookies. Customers who integrate through a server-side integration are still responsible for getting any necessary consents and making any necessary disclosures for the personal data they collect and send to Amplitude.
{% /accordion %}

## CNIL France - Frequently asked questions

{% callout type="warning" heading="CNIL France FAQs" %}
FAQs related to CNIL aren't intended as legal or regulatory advice and don't constitute any warranty or contractual commitment on the part of Amplitude. Amplitude encourages customers to seek independent legal advice on your legal and regulatory obligations with issues related to this subject matter.
{% /callout %}

{% accordion title="CNIL France - What is the CNIL cookie exemption?" %}
The CNIL (Commission Nationale Informatique & Libertés) is the French Data Protection Agency. As a general rule, the CNIL requires user consent before a website, mobile application, or other connected device can use cookies. The CNIL allows a limited exemption from this requirement for cookies that collect only anonymous, aggregated statistical data used for measuring website traffic or performance. Data collected from these cookies can't combine with other data or identify users.
{% /accordion %}

{% accordion title="CNIL France - What does the CNIL cookie exemption really mean?" %}
The CNIL maintains a list of services that can operate under the exemption. Any use of an analytics service under the CNIL exemption is subject to the following limitations:

1. Analytics cookies can ONLY operate without user consent if they only collect anonymous statistical data for audience measurement (total traffic, page views).
2. This doesn't mean a customer can collect ALL data about a user for analysis.
3. Under the exemption, customers can't use or create "user" analyses.
{% /accordion %}

{% accordion title="CNIL France - What does the CNIL exemption mean for Amplitude and our cookies?" %}
The CNIL allows a limited exemption for the requirement that companies obtain user consent for any non-essential cookies. This exemption applies to analytics cookies for the limited purpose of audience measurement of an app or a site, and it's limited to the use of anonymous tracers.

A customer's use of an analytics service under the exemption is therefore limited. Without the CNIL cookie exemption, customers might only collect and measure part of their traffic. The limited data set in Amplitude (for example, the data set with only users who opted in or consented) is more valuable than the limited data that the exemption permits, because:

- Audience measurement (page views, total sessions) doesn't help customers make better decisions. Behavioral analytics guide actions and learning.
- Amplitude doesn't need 100% of traffic to derive meaningful insights.
- Most exempted tools don't have the powerful analytics capabilities of Amplitude.

In addition to using the SDKs, customers can send data to Amplitude server-side. Server-side integration doesn't require customers to obtain consent for a separate Amplitude SDK cookie. Customers who integrate through a server-side integration are responsible for obtaining any necessary consents and making any necessary disclosures for the personal data they collect and send to Amplitude.
{% /accordion %}

{% accordion title="CNIL France - 13-month cookie limit" %}
Amplitude Browser SDK 2 has a `cookieOptions.expiration` option that lets customers set the number of days a cookie lives. The default is 1 year (365 days) as of the current version. Most browsers limit the lifetime of cookies set using document.cookie from 1 to 7 days.

```ts
amplitude.init("API_KEY", {
  cookieOptions: {
    expiration: 395, // 13 months in days
  },
});
```

{% /accordion %}

{% accordion title="CNIL France - 25-month data retention max" %}
Use [Amplitude's Time to Live](/docs/data/time-to-live) functionality to set a retention schedule for event data.
{% /accordion %}

{% accordion title="CNIL France - Purpose strictly limited to the sole measurement of the site's or application's audience" %}
The requirement limits the purpose to the sole measurement of the site's or application's audience: performance measurement, detection of browsing problems, optimization of technical performance or ergonomics, estimation of the power of the servers required, and analysis of contents consulted, for the exclusive account of the publisher. Amplitude customers are in full control of the data that they choose to send to the Amplitude platform, and can choose to send only Amplitude events related to audience measurement and page views.

Configure the SDK to track only page views and basic session information:

```ts
amplitude.init("API_KEY", {
  autocapture: {
    attribution: false,
    pageViews: true,
    sessions: true,
    formInteractions: false,
    fileDownloads: false,
    elementInteractions: false,
  },
});
```

{% /accordion %}

{% accordion title="CNIL France - Only serve to produce anonymous statistical data" %}
Before you start using Amplitude to produce anonymous statistical data:

- [Contact Amplitude](https://amplitude.zendesk.com/hc/en-us/requests/new) to:
  - Request that Amplitude drop the IP address for projects that contain end users who haven't provided consent.
  - Discuss disabling Amplitude's User Look-Up and the ability to view user streams for projects that contain data for end users who haven't provided consent.
  - Discuss the most effective configuration options for your use case.

- Ensure you don't send `deviceID` to Amplitude for end users who haven't provided consent.
- For end users who haven't provided consent, set a `userID` that's randomly generated or hashed.
- Consider disabling the capacity to filter end users at the individual level by hiding user properties, such as `userID`, `deviceID`, and `Amplitude ID`. Refer to [Transformations](/docs/data/transformations) for more information.
- Consider disabling user downloads. Refer to [Managing Projects](/docs/admin/account-management/manage-orgs-projects) for more information.

{% /accordion %}

{% accordion title="CNIL France - Compliant with GDPR" %}
Amplitude's privacy program is based on privacy-by-design principles. Amplitude's privacy program ensures that it complies with all relevant domestic and international privacy regulations and laws regarding the processing of personal data, including GDPR.

Amplitude also offers customers the choice of hosting their data in the US-West based AWS environment or the EU based AWS environment. To ensure that Amplitude's customers can appropriately respond to and comply with end-user data deletion requests as required by global privacy laws such as GDPR, Amplitude built an API endpoint that lets customers submit requests programmatically to delete all data for a set of known Amplitude IDs or User IDs. For more details, refer to the developer documentation: [User Privacy API](/docs/apis/analytics/user-privacy).

Customers can complete Data Subject Access Requests (DSARs) using the [DSAR API](/docs/apis/analytics/ccpa-dsar), which makes it easy to retrieve all data about a single user.

For more information on Amplitude's stance on privacy and security, refer to [Amplitude Trust](https://amplitude.com/trust).
{% /accordion %}

{% accordion title="CNIL France - Cookies must not lead to a cross-checking of the data with other processing or that data be passed on to third parties." %}
Amplitude doesn't export data unless the customer chooses to export data to third-party products. Customers shouldn't use Amplitude to export data related to end users who haven't provided consent to third-party products.

Upon request, Amplitude can disable its cohort syncing and data streaming capabilities for orgs that contain only data for end users who haven't provided consent.
{% /accordion %}

{% accordion title="CNIL France - Cookies must not allow the global follow-up" %}
The CNIL exemption states that cookies must not allow the global follow-up of the navigation of the person using different applications or browsing on different websites. Any solution that uses the same identifier across multiple sites (for example, through cookies placed on a third-party domain loaded by multiple sites) to cross-reference, duplicate, or measure a unified reach for content is excluded.

To comply with this requirement, customers shouldn't use Amplitude's [cross domain tracking](/docs/sdks/analytics/browser/browser-sdk-2#cross-domain-tracking), and should use a [separate platform instrumentation](/docs/get-started/cross-platform-vs-separate-platform) for any projects with data from end users who haven't provided consent. By default, Amplitude doesn't employ cross-domain tracking for customers.
{% /accordion %}

{% accordion title="CNIL France - The data is collected, processed and stored independently for each publisher" %}
Amplitude logically separates customer data and stores it in encrypted form in Amplitude's AWS environment.
{% /accordion %}

{% accordion title="CNIL France - The trackers are completely independent of each other and of any other tracker" %}
The cookie used by Amplitude Browser SDK 2 is a [first party cookie](#frequently-asked-questions). The customer collects any data the cookie collects as the controller of the data. Amplitude processes the customer's data only as a processor or service provider, and doesn't use customer data for its own purposes.
{% /accordion %}
