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 SDK Topics

This section has information unique to each platform

Getting the Device ID (JavaScript)

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 (JavaScript)

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 (JavaScript)

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 (JavaScript)

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>

Google Tag Manager (JavaScript)

Amplitude's JavaScript SDK supports integration with Google Tag Manager. Take a look at our demo application for instructions on how to set it up.

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.

Setting Version Name (JavaScript)

By default, no version name is set. You can specify a version name to distinguish between different versions of your site by calling setVersionName:

amplitude.getInstance().setVersionName('VERSION_NAME');

Callbacks for logEvent, Identify, and Redirect (JavaScript)

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 (JavaScript)

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

iOS Extensions

The SDK allows for tracking in iOS extensions. Please note that this does not include watchOS. We recommend tracking watch interactions using the partner iPhone app code or sending the data server-side via our HTTP API. To set up tracking in iOS extensions, you should follow the same setup instructions until step six. In step six, instead of initializing the SDK in application:didFinishLaunchingWithOptions:, you should initialize the SDK in your extension's viewDidLoad method.

Here are a couple of things to note:

  • The viewDidLoad method will get called every time your extension is opened. This means that our SDK's initializeApiKey method will get called every single time. However, this is okay since it will safely ignore subsequent calls after the first one. If you wish to, you can protect the initialization with something like a dispatch_once block.
  • Our definition of sessions was intended for an app use case. Depending on your expected extension use case, you might not want to enable trackingSessionEvents, or you may want to extend the minTimeBetweenSessionsMillis to be longer than five minutes. You should experiment with these two settings to get your desired session definition.
  • In addition, you may want to decrease eventUploadPeriodSeconds to something shorter than 30 seconds to upload events at shorter intervals if you do not expect users to keep your extension open that long. You can also manually call [[Amplitude instance] uploadEvents]; to manually force an upload.
    Here is a simple demo application showing how to instrument the iOS SDK in an extension.

Here is a simple demo application showing how to instrument the iOS SDK in an extension.

Debug Logging (iOS and Android)

By default, only critical errors are logged to console. To enable debug logging in iOS, change AMPLITUDE_DEBUG from 0 to 1 at the top of the Objective-C file you wish to examine. Error messages are printed by default. To disable error logging, change AMPLITUDE_LOG_ERRORS from 1 to 0 in Amplitude.m.

You can disable all logging done in the Android SDK by calling Amplitude.getInstance().enableLogging(false). By default, the logging level is Log.INFO, meaning info messages, errors, and asserts are logged but verbose and debug messages are not. You can change the logging level. For example, to enable debug messages you can do:

Amplitude.getInstance().setLogLevel(log.DEBUG)

Push Notification Events (iOS and Android)

Push notification events should not be sent client-side via the iOS SDK because a user must open the app to initialize the Amplitude SDK in order for the SDK to send the event. Therefore, if push notification events are tracked client-side then there can be data delays as the push notification event will not be sent to Amplitude's servers until the next time the user opens the app.

Push notification events should not be sent client-side via the Android SDK because a user must open the app to initialize the Amplitude SDK in order for the SDK to send the event. Therefore, if push notification events are tracked client-side then there can be data delays as the push notification event will not be sent to Amplitude's servers until the next time the user opens the app.

You can use our mobile marketing automation partners or our HTTP API V2 to send push notification events to Amplitude.

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');
[[Amplitude instance] setDeviceId:@"DEVICE_ID"]
Amplitude.getInstance().setDeviceId("DEVICE_ID")
Amplitude.getInstance().setDeviceId("DEVICE_ID")

If you would like to use Google's Advertising ID as the Device ID, you can specify this by calling Amplitude.getInstance().useAdvertisingIdForDeviceId() prior to initializing. 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.

We use UUID.randomUUID().toString() on iOS

As of iOS 10, if the user enables Limit Ad Tracking, then Apple will replace the IDFA with all zeros. If the iOS SDK detects an all 0 Device ID, then it will generate a random UUID and use that instead.

Log Level

The log level allows you to set the level of logs printed to be printed in the developer console. The different levels are as follows:

  • 'INFO': This option will show error messages, warnings, and informative messages that may be useful for debugging.
  • 'WARN': This option will show error messages and warnings. This level will log issues that might be a problem and cause some oddities in the data. For example, this level would display a warning for properties with null values.
  • 'ERROR': This option will show error messages only.
  • 'DISABLE': This will suppress all log messages.

You can set the log level by calling the following on Android:

Amplitude.getInstance().setLogLevel(log.DEBUG)

Updated about a month ago


Advanced SDK Topics


Suggested Edits are limited on API Reference Pages

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