The Amp Devcenter Test Developer Hub

Welcome to the Amp Devcenter Test developer hub. You'll find comprehensive guides and documentation to help you start working with Amp Devcenter Test as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    

Advanced Topics

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

On initialization, the SDK will create 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

Amplitude cookies 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 users across subdomains of your product (eg: www.amplitude.com vs analytics.amplitude.com), this will no longer work. Access to localStorage is restricted by subdomain.

SameSite

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 our cookies. 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, Amplitude's cookies 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.

RequireJS

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 -->
<script>
 require(['https://cdn.amplitude.com/libs/amplitude-6.2.0-min.umd.gz.js'], 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');
 });
 </script>

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

<script src='scripts/require.js'></script> <!-- loading RequireJS -->
<script>
 requirejs.config({
  paths: {
   'amplitude': 'https://cdn.amplitude.com/libs/amplitude-6.2.0-min.umd.gz.js'
  }
 });

 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');
 });
</script>
<script>
 require(['amplitude'], function(amplitude) {
  amplitude.getInstance().logEvent('Page loaded');
 });
</script>

Cross Domain Tracking (JavaScript)

You can track anonymous behavior across two different domains. For example, let's say you have the following two domains:

If you want to track an anonymous user who starts on Site 1 and navigates to Site 2, then you will need to pass the Device ID from Site 1 as a parameter to Site 2. After that, you will need to reinitialize the SDK with the passed Device ID. It would look something like:

  • From Site 1, grab the Device ID from amplitude.options.deviceId.
  • Pass the Device ID to Site 2 via a URL parameter or third party cookie.
  • Initialize the Amplitude SDK on Site 2 with amplitude.init('API_KEY', null, {deviceId: '$DEVICE_ID'}).

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
    }
    window.location.replace('URL_OF_OTHER_SITE');
};

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() {
        window.location='LINK_A_URL';
    });
};

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

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
});

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:

amplitude.getInstance().setDeviceId('DEVICE_ID');

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.

Updated 10 days ago


Advanced Topics


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.