Advanced Topics

COPPA Control

COPPA control in Amplitude's other SDKs disables tracking for IDFA, IDFV, city, location data (location_lat and location_lng), and IP address.
There's no interface for COPPA control in the JavaScript SDK because it doesn't track location_lat, location_lng, IDFA or IDFV. Instead, you can disable tracking for city and ip_address with trackingOptions.

var trackingOptions = {
        city: false,
        ip_address: false,

Getting the Device ID

You can get a user's current Device ID with the following code:

var deviceId = amplitude.getInstance().options.deviceId; // existing device id

Setting Configuration Options

You can configure Amplitude by passing an object as the third argument to the init:

amplitude.getInstance().init("API_KEY", null, {
    // optional configuration options
    saveEvents: true,
    includeUtm: true,
    includeReferrer: true

Cookie Management

Cookies Created by the SDK

If you choose to use Amplitude's SDK to submit data to the Amplitude platform, the upon initialization the SDK creates a cookie that begins with the prefix amp_ and ends with this first six digits of your API key. For example amplitude.getInstance().init("a2dbce0e18dfe5f8e74493843ff5c053") would create a cookie with the key amp_a2dbce.

The cookie is used to keep track of a few bits of metadata for the SDK:

  • A randomly generated device id
  • The current session id
  • The current user id if a user id is set
  • The last event time
  • A few sequence ids in order to sequence events and identifies correctly

Disabling Cookies

Cookies created by the SDK can be disabled altogether using the disableCookies option. When you disable cookies, the JavaScript SDK will fallback to using localStorage to store its data. LocalStorage is a great alternative, but there is one small potential downside. If you track anonymous users across subdomains of your product (eg: vs, this will no longer work. Access to localStorage is restricted by subdomain.


The JS SDK defaults to setting the SameSite option on its cookies to None. This can be overridden with the sameSiteCookie option. We set the option to Lax option on our own sites at amplitude. Lax is recommended unless there are instances where you have third party sites that POST forms to your site. The default may change to Lax in the future.

HttpOnly Cookies

We often receive requests to have an HttpOnly option on cookies created by the SDK. This isn't possible for the SDK cookie. The cookie is set on the client side and is used as a client side data store. The SDK cookie would not be able to set the HttpOnly flag, and if it were somehow able to set such a flag, it would not be able to read the cookie.

Upgrading Legacy Cookies

Historically, cookies created by the Amplitude SDK have been on the large side. Newly created cookies tend to be significantly smaller. For users that already have older cookies saved, the SDK will only remove old cookies and start using the newer more compact cookie format if the cookieForceUpgrade option is set to true. Note that if you use the SDK in multiple products, and track anonymous users across those products, you will want to be sure to set this option on all of those products. We would only recommend doing this if you are running into problems with over sized cookies.


If you are using RequireJS to load your JavaScript files, then you can also use it to load the Amplitude JavaScript SDK script directly instead of using our loading snippet. If you take this approach you will lose one of the key advantages of the snippet that allows your app to start and use the amplitude sdk without having to wait for amplitude to fully download.

<script src='scripts/require.js'></script> <!-- loading RequireJS -->
 require([''], function(amplitude) {
 amplitude.getInstance().init('API_KEY'); // replace API_KEY with your Amplitude API key.
 window.amplitude = amplitude; // You can bind the amplitude object to window if you want to use it directly.
 amplitude.getInstance().logEvent('Clicked Link A');

You can also define the path in your RequireJS configuration like this:

<script src='scripts/require.js'></script> <!-- loading RequireJS -->
  paths: {
   'amplitude': ''

 require(['amplitude'], function(amplitude) {
  amplitude.getInstance().init('API_KEY'); // replace API_KEY with your Amplitude API key.
  window.amplitude = amplitude; // You can bind the amplitude object to window if you want to use it directly.
  amplitude.getInstance().logEvent('Clicked Link A');
 require(['amplitude'], function(amplitude) {
  amplitude.getInstance().logEvent('Page loaded');

Cross Domain Tracking (JavaScript)

You can track anonymous behavior across two different domains. Anonymous users are identified by their Device IDs which will need to be passed between the domains. For example:

  • Site 1:
  • Site 2:

Users who start on Site 1 and then navigate to Site 2 will need to have the Device ID generated from Site 1 passed as a parameter to Site 2. Site 2 then needs to initialize the SDK with that Device ID. The SDK can parse the URL parameter automatically if deviceIdFromUrlParam is enabled.

  • From Site 1, grab the Device ID from amplitude.getInstance().options.deviceId.
  • Pass the Device ID to Site 2 via a URL parameter when the user navigates. (e.g.
  • Initialize the Amplitude SDK on Site 2 with amplitude.init('API_KEY', null, {deviceIdFromUrlParam: true}).

Tracking UTM Parameters, Referrer, and gclid (JavaScript)

Amplitude supports automatically tracking:

  • Standard UTM parameters from the user's cookie or URL parameters when the configuration option includeUtm is set to true during initialization.
  • The referring URL when the configuration option includeReferrer is set to true during initialization.
  • gclid (Google Click ID) from URL parameters when the configuration option includeGclid is set to true during initialization.

If tracking is enabled, then the SDK will set the values as user properties (e.g. referrer or utm_source) once per session (this is last touch attribution). The SDK will also save the initial values using a setOnce operation (e.g. initial_referrer or initial_utm_source), and once set that value will never change (this is first touch attribution).

Note: By default, the SDK will only save the values at the start of the session. For example, if a user lands on your site with an initial set of UTM parameters and triggers some flow that causes them to land on your site again with a different set of UTM parameters within the same Amplitude session, then that second set will not be saved. You can set the configuration option saveParamsReferrerOncePerSession to false to remove that restriction so that the SDK will always capture any new values from the user.

Note: By default, the SDK will carry over existing UTM Parameters and Referrer values at the start of a new session. For example, if a users session expires, the SDK will map the user's Referrer and UTM Parameters to existing values. To reset those values to null upon instantiating a new session, set unsetParamsReferrerOnNewSession to true.

Callbacks for logEvent, Identify, and Redirect

You can pass a callback function to logEvent and identify, which will get called after receiving a response from the server. This is useful if timing may cause an event to not be captured before the browser navigates away from a webpage. Putting the navigation in a callback to the logEvent method will guarantee the event is captured before the navigation occurs. Here is a logEvent example:

amplitude.getInstance().logEvent("EVENT_TYPE", null, callback_function);

Here is an identify example:

var identify = new amplitude.Identify().set('key', 'value');
amplitude.getInstance().identify(identify, callback_function);

The status and response body from the server are passed to the callback function, which you might find useful. Here is an example of a callback function which redirects the browser to another site after a response:

var callback_function = function(status, response) {
    if (status === 200 && response === 'success') {
        // do something here

You can also use this to track outbound links to your website. For example, you would have a link like this:

<a href="javascript:trackClickLinkA();">Link A</a>

Then, you would define a function that is called when the link is clicked like this:

var trackClickLinkA = function() {
    amplitude.getInstance().logEvent('Clicked Link A', null, function() {

In the case that optOut is true, then no event will be logged but the callback will be called. In the case that batchEvents is true, if the batch requirements eventUploadThreshold and eventUploadPeriodMillis are not met when logEvent is called, then no request is sent but the callback is still called. In these cases, the callback will be called with an input status of 0 and a response of 'No request sent'.

Error Callbacks

You can pass a second callback to logEvent and identify that will be called if the network request for the event fails. This is useful to detect if a user is using an ad blocker, or if there's an error from the Amplitude server due to an issue with the event format. You can use the error callback together with the success callback like this:

var successCallback = function() {
    console.log('the event was logged successfully');

var errorCallback = function() {
    console.log('there was an error logging the event')

amplitude.getInstance().logEvent('event', null, successCallback, errorCallback);

init Callbacks

You can also pass a callback function to init, which will get called after the SDK finishes its asynchronous loading. Note: The instance is passed as an argument to the callback:

amplitude.getInstance().init('API_KEY', 'USER_ID', null, function(instance) {
  console.log(instance.options.deviceId);  // access Amplitude's deviceId after initialization

Using sendBeacon

In SDK version 8.5.0 and above, the SDK can send events using the browser's built-in navigator.sendBeacon API. Unlike standard network requests, events sent by sendBeacon are sent in the background, and will be completed even if the user quickly closes the browser or leaves the page. However, because these events are sent in the background, it is not known if the event successfully uploads to the Amplitude server, and cannot be saved for a later retry.

To send an event using sendBeacon, set the transport SDK option to 'beacon' in one of two ways

// set transport to 'beacon' when initializing an event
amplitude.getInstance().init('API_KEY', 'USER_ID', {transport: 'beacon'});

// set transport to 'beacon' after initialization

// this event will be sent using navigator.sendBeacon
amplitude.getInstance().logEvent('send event with beacon');

// set transport back to the default 'http' value

// this event will be sent using the standard xhr mechanism
amplitude.getInstance().logEvent('send event with http');

Using sendBeacon only when exiting page

Configuring sendBeacon to send data only when the user exits a page can be complicated, so the JS SDK provides a convenient callback function that is called only when the user exits the page, and automatically switches the transport to 'beacon' for any logs sent in the callback. This callback is called 'onExitPage' and is passed into the SDK on initialization, like so:

var exitCallback = function {
  amplitude.getInstance().logEvent('Logging a final event as user exits via sendBeacon');

amplitude.getInstance().init('API_KEY', 'USER_ID', { onExitPage: exitCallback });

Custom Device IDs

By default, device IDs are randomly generated UUIDs, although you can define a custom Device ID by setting it as a configuration option or by calling:


You can retrieve the Device ID that Amplitude uses with Amplitude.getInstance().getDeviceId(). This method can return null if a Device ID has not been generated yet.

Note: This is not recommended unless you know what you are doing (like if you have your own system for tracking user devices). Make sure the deviceId you set is sufficiently unique in order to prevent conflicts with other devices in our system. We recommend something like a UUID.

See here for an example of how to generate on JavaScript.

Did this page help you?