On this page

Google Tag Manager (client)

This is the client-side Google Tag Manager Template for Amplitude Analytics. The tag uses the Amplitude Browser SDK 2.0 for data collection.

Breaking Changes Checklist from the version 240a7, Aug, 2023

Starting from version 240a7, August, 2023, this template uses Amplitude Browser SDK 2.0 instead of Marketing Analytics SDK(Deprecated), offering better support, enhanced functionality, and additional features.

While this updated template offers additional features and improvements, it may result in different behavior that could affect your existing analytics charts. You can enable or disable these changes to keep consistency. To retain the legacy behavior, review the following list of breaking changes and adjust your configuration.

Refer to the breaking changes checklist at Breaking changes checklist.

Update your Amplitude GTM template to the latest version consistently for an enhanced feature set, crucial bug fixes, and an improved user experience.

Create a container

If you're working on a new implementation, configure your container first.

  1. Name the container using your site's URL.
  2. Select the Web target platform.
  3. Click Create.

Add the template

From the Workspace tab, click Templates. In the Tag Templates section, click Search Gallery. Search for Amplitude and select Amplitude Analytics Browser SDK. Click Add to workspace, and confirm to add the community template.

Create tags

Navigate to the Tags tab. Click New, and select the Amplitude Analytics Browser SDK template.

Configure the tag

Instance name

If you plan to run more than one Amplitude instance, each with distinct API keys or initialization options, assign an Instance Name to each one. Amplitude links tags with the same Instance Name and uses the API key of the Initialization tag for that Instance Name.

This approach can also prevent missing events if different versions of the Amplitude SDK coexist in your system.

You can access amplitude instance in a Custom HTML tag.

js
// For amplitude-js-gtm@3.1.4 and above
amplitudeGTM.getDeviceId();

// Others
amplitude.getDeviceId();

With customized instance name

js
// For amplitude-js-gtm@3.1.4 and above
amplitudeGTM._iq["yourInstanceName"].getDeviceId();

// Others
amplitude._iq["yourInstanceName"].getDeviceId();

Select a tag type

A tag type allows you to specify the type of action or event to track in your application. The following tag types are supported in Amplitude GTM template.

Initialize

init operates as a separate tag type you need to create. Although Amplitude provides deferred initialization, Amplitude doesn't receive events until the init fires.

Amplitude generates cookies at the initialization stage. For more information on managing cookies, refer to the cookie management details. Amplitude recommends that you initialize after obtaining cookie consent. Amplitude supports deferred initialization, and captures any events that take place before the init command.

API Key

Copy your Amplitude project API Key in the API Key field. For EU residency, your project API Key is under analytics.eu.amplitude.com. Each project has a different API Key, so make sure you copy the API Key from the right project. Go to Settings > Projects > click the right project name from the list to find your project API Key. For more information, review API Authentication.

Autocapture options

Enable Autocapture events to enable autocapture for the following event types:

  • Track Marketing Attribution.
  • Track Page Views.
  • Track Sessions.
  • Track Form Interactions.
  • Track File Downloads.
  • Track Element Interactions.

For more information, refer to Browser SDK 2 - Autocapture.

NameDescriptionDefault Value
Initial Empty Valuestring. Customize the initial empty value for attribution related user properties to any string value.EMPTY
Exclude Referrersstring or string1, string2. The referring_domain you want to exclude the attribution tracking. If you exclude a referring_domain, it doesn't track web attribution, and maps to (none) in chart analysis. By default, it also excludes a referral section to track attribution of all subdomains of the input domain. Refer to Subdomain attribution tracking for more information.[]
Reset session on new campaignboolean. Configures Amplitude to start a new session if any campaign parameter changes.false
Page view tracking

Check this box to enable page view tracking. The following configurations are available page view tracking options. For more information, refer to Browser SDK 2.

Session tracking

Check this box to enable sessions tracking. For more information, refer to Browser SDK 2.

Form interaction tracking

Check this box to enable form interactions tracking. For more information, refer to Browser SDK 2.

File downloads tracking

Check this box to enable file downloads tracking. For more information, refer to Browser SDK 2.

Network tracking

Check this box to enable network tracking. Network tracking captures network request events invoked by XHR and Fetch. For more information, refer to Browser SDK 2 - Track network requests.

EU data residency

For EU data residency, create your project inside Amplitude EU and use the API key from Amplitude EU. You can configure the server zone by checking the checkbox EU Data Residency under Tag Configuration > Initialization of the init tag. The initialization section only shows up when tag type is set to init. For more information, refer to Browser SDK 2.

User ID

If the user ID is already available you can:

  • Initialize the instance with it by entering it in the "User ID" input box of the init tag.
  • Use the setUserId tag type to set the user ID later. For more information, refer to Browser SDK 2.

Configuration

Choose from the following options:

  • Use default values. The initialization uses each configuration option's default value.
  • Set configuration manually. Set by selecting the corresponding option. The following configurations are the available ones with the value type in GTM template.
  • Select a **GTM variable** from the list. You need to return an object containing the key-value pairs you want to use for instance configuration. Ensure that the keys are part of the available configurations.

Setting logLevel in GTM

In GTM, you can't import the LogLevel enum like you would in a TypeScript or JavaScript project. Use numeric values to set the log level:

  • 0 - None (suppresses all logs).
  • 1 - Error (error messages only).
  • 2 - Warn (error and warning messages, default).
  • 3 - Verbose (informative messages).
  • 4 - Debug (all messages including function context).

For example, to suppress all Amplitude SDK console logs, set logLevel to 0 in the Configuration section. Don't use string values like "LogLevel.None" or "LogLevel.Warn", as these don't work in GTM.

Track event

Events represent how users interact with your application. For example, "Button Clicked" may be an action you want to note.

The track tag type tracks an event under a specific trigger.

Event type

NameDescription
Event Typestring. The name of the event.

Individual event properties

NameDescription
Property Namestring. The name of the event property.
Property Valuestring. The value of the event property.

Event properties object

Select a GTM variable that returns a valid event properties object. This overwrites the Individual Event Properties event properties if there are any duplicate keys. Amplitude ignores any inputs not in the object format and any value under the user_properties key.

javascript
    {
        'eventPropKey' : 'eventPropValue',
        'otherEventPropKey': 'otherEventPropValue',
    }

To establish a scalable approach for defining properties, you can use the Google Tag: Event Settings variable in GTM. The GTM Google Tag: Event Settings variable lets you reuse the event settings in multiple tags. For more information, refer to Browser SDK 2. You can use this variable to create properties and reuse them across several tags.

The format of Google Tag: Event Settings variable:

javascript
    {
        'eventPropKey' : 'eventPropValue',
        'otherEventPropKey': 'otherEventPropValue',
        'user_properties': {
            'user_property_key': 'user_property_value'
        }
    }

Note that if you choose the Google Tag: Event Settings variable as an input in Event Properties Object, Amplitude ignores the value under user_properties.

Custom timestamp

NameDescriptionDefault Value
Custom Timestamp number or null. timestamp in UNIX time (milliseconds). Leave empty to use current time.Current timestamp.
Track with groups

Set event level groups. With event-level groups, the group designation applies only to the specific logged event, and doesn't persist on the user unless set explicitly with setGroup. For more information, refer to Browser SDK 2 - User Groups.

NameDescription
Group Typestring. The type of group for which you're setting the name. For example, Customer Name.
Group Namestring or string1,string2.... The name of the group. The value can be a single group name (for example, 15) or a comma-separated list (for example, 2,12,24) of group names.

Set user properties

Identify calls don't appear in user look up. The identify call sets the user properties, and those updated user properties appear only after the next event fired by the user.

Add individual user property operations each as its own row in the table. You can add as many as you like, but you can only include a specific User Property in a single operation. The operations execute in order. For more information, refer to Browser SDK 2.

NameDescription
Method CallAdd, Append, Prepend, Set, Set Once, Remove, Preinsert, Postinsert, Clear All. The operation for the identify call.
User Propertystring. The key of user properties.
Valuestring or others. The value of specific user property. To pass other types, use a GTM variable (Data Layer Variable).

Set group

Amplitude supports assigning users to groups and performing queries, such as Count by Distinct, on those groups. If at least one member of the group has performed the specific event, then the count includes the group. For more information, refer to Browser SDK 2.

NameDescriptionDefault Value
Group Typestring. The group type.
Group Name(s)string or string,string.... The group names under the group type. You can add a single group name or a comma-separated list ( 2,12,24) of group names.

Set group properties

Use the Group Identify API to set or update the properties of particular groups. These updates only affect events going forward. For more information, refer to Browser SDK 2.

NameDescription
Group Typestring. The group type.
Group Name(s)string. The group names under the group type.
Method CallAdd, Append, Prepend, Set, Set Once, Remove, Preinsert, Postinsert, Clear All. The operation for the identify call.
User Propertystring. The key of user properties.
Valuestring or others. The value of specific user property. To pass other types, use a GTM variable (Data Layer Variable).

Track revenue

Tracks the revenue event for a user. Revenue instances store each revenue transaction and let you define several special revenue properties (such as revenueType and productIdentifier) that Amplitude's Event Segmentation and Revenue LTV charts use.

NameDescriptionDefault Value
product_idRequired. string. An identifier for the product. Amplitude recommend something like the Google Play Store product ID.``
quantityRequired. number. The quantity of products purchased. For version after marketing-analytics-browser-gtm 0.5.4, the SDK auto assigns revenue = quantity * price.1
priceRequired. number. The price of the products purchased, and this can be negative. Note: revenue = quantity* price.null
revenue_typeOptional, but required for revenue verification. string. The revenue type (for example, tax, refund, income).null
event propertiesOptional. { [key: string]: any }. An object of event properties to include in the revenue event.null

Flush events

The flush method prompts the client to send buffered events. You don't need to call the flush tag type manually, it triggers based on either flushIntervalMillis or flushQueueSize, whichever comes first. To avoid event loss due to browser closure, consider setting transport in the configuration options to beacon, or call amplitude.setTransport('beacon') at the event pagehide. For more information, refer to Browser SDK 2.

Reduce the flushQueueSize and flushIntervalMillis according to your event traffic load, ensuring events don't get stuck on the client.

Set user ID

To reset the userId and deviceId after logout, check the reset tag type instead.

NameDescriptionDefault Value
User IDundefined or string. Set the userId. Leave empty to set the userId to undefined.undefined

Set device ID

To reset the userId and deviceId after logout, check the reset tag type instead.

NameDescriptionDefault Value
Device IDstring. Set the deviceId for the current user. Amplitude assigns a unique identifier for the deviceId by default. For the cross domain use case, Amplitude captures the deviceId from URL parameter and assigns the value to deviceId. For more information, refer to Browser SDK 2.UUID

Set session ID

Amplitude handles session logic automatically. You might need to set the sessionId to -1 to opt out of session control. Make sure the value is in milliseconds since epoch (Unix Timestamp) or -1. For more information, refer to Browser SDK 2.

Reset

Use reset when a user logs out. It includes 2 operations: setUserId(undefined) and setDeviceId(UUID()). For more information, refer to Browser SDK 2.

Set opt-out

Check the Opt current user out of tracking checkbox to opt user out of tracking. For more information, refer to Browser SDK 2.

Define your trigger

All tags fire based on events. When Google Tag Manager registers an event, it evaluates event triggers and fires tags. Refer to Trigger types for the available triggers in GTM.

In most cases, the init tag is the first thing you need to fire on the page. It's common to fire the init tag using the All Pages or Initialization - All Pages triggers. You can defer the init tag until you receive a signal and fire it with customized triggers, such as a consent grant. All other tags wait for the init tag to fire before they can send to Amplitude.

Add a custom plugin

Plugins let you modify events. To learn more, refer to the Browser SDK plugins documentation. You can add custom plugins by using a custom HTML tag.

For example, the HTML to add an event property to default page view events:

HTML
<script>
  window.amplitudeGTM.add({
    name: "page-view-enrichment-plugin",
    execute: function(event) {
      if(event.event_type === "[Amplitude] Page Viewed"){
        event.event_properties["custom_key"] = "custom_value";
      }
      return event;
    }
  });
</script>

To add a plugin to a named instance, use window.amplitudeGTM.createInstance('instanceName').add().

GTM loads templates only when a tag based on that template fires. As a result, configure the sequencing of tags to ensure the plugin loads at the beginning, and applies to all following events. To do this, create a custom HTML tag that adds the plugin as the setup tag for the init tag. Then, configure a flush tag as the setup tag for the custom HTML tag. Sequence the tags in this order:

  • Flush.
  • Custom HTML.
  • init.

Troubleshooting

These are common issues encountered with the GTM template. For further troubleshooting of your GTM instance, refer to the GTM Help Center.

Does Amplitude GTM template support React Native (Android or iOS) apps?

No. The Amplitude Analytics Browser SDK only supports the web container, designed for desktop and mobile browsers. Amplitude doesn't provide support for GTM templates for mobile apps. To request this feature, submit a feature request through the Amplitude Help Center.

Can you add logic to Amplitude template?

Yes, but it's not recommended. Modified Community Gallery Templates don't receive updates from the developer, but you can restore the template to start receiving notifications again.

Missing events

  • Check if you have multiple versions of Amplitude browser SDK installed. There may be collision between different versions of SDKs. Try giving a different instance name for your GTM instance.
  • If your website blocks the script the template tries to inject, check your browser's Console or Network tab to view if it blocks any scripts or if you're getting any errors.
  • Init web attribution event is missing. If you installed cookies consent, check if the value of document.referrer updates to your current domain. The campaign from the current domain isn't tracked.
  • Ensure you select the appropriate Tag firing options. Choosing Once per event causes your tag to fire each time a user performs a Trigger event. Selecting Once per Page fires your Tag a single time. This discrepancy could lead to events not sending as expected.

Overall user counts to increase

Verify whether cookies are altered or removed inadvertently. Cookies store critical user session data and marketing campaign information. If these cookies are deleted, Amplitude resets user identifiers (such as user ID and device ID), which leads to a surge in the user count. Also, the erasure of last-viewed campaign parameters can result in an increase in organic and direct traffic, among other effects.

Cross domain tracking

To retain user identification across domains, create a custom HTML tag to attach the user's deviceId to the domain link you want to track. When you append ampDeviceId=YourDeviceId to the URL, the Amplitude Browser SDK uses the URL parameter value rather than generate a new deviceId. For more information, refer to an example script on GitHub.

Starting from template version 15cce (library version amplitude-ts-gtm/3.17.1), the template supports getting the session ID from the URL parameter ampSessionId to keep the same session. You can also include an ampTimestamp parameter to create an evaluation window that ensures the tracking parameters are only used when they haven't expired. For more information, review Cross-domain tracking with Browser SDK 2.0.

How to pass other types for identify or groupIdentify value

Hard coding the value in your tag forces the input into a string type. To use other types like number or boolean, create a GTM variable, specifically a Data Layer Variable.

Why is my data layer correct but events are wrong?

This issue occurs when a tag reads a value from a variable in the data layer, and two values are pushed to the data layer within a short time. The expected behavior is that Amplitude tracks two events with different values. However, what actually happens is that both events have the second (most recently pushed) value.

This happens because when the first value is pushed to the data layer, the data layer updates the value but doesn’t trigger the event. When the second value is pushed, the data layer updates the value again and triggers two events, both reading the second value.

This is a known limitation of GTM. Follow Google's documentation to resolve it by adding an event name.

If you added an event name to a message and this issue still happens, check whether the track tag has a setup tag. A setup tag can delay the track tag, causing it to read the data layer variable after it's been overwritten with the latest value. Removing the setup tag should resolve this issue.

Breaking changes checklist

Page View event's name and properties

The new template changes the default page view events to include [Amplitude] prefixes. To continue using the older page view events, check the Use legacy page view properties checkbox. Refer to the full details in the table.

  • - Event Name: Page View; - Properties: page_location, page_path, page_title. page_url
    • Current:
      • Event Name: [Amplitude] Page Viewed.
      • Properties: [Amplitude] Page Domain, [Amplitude] Page Location, [Amplitude] Page Path, [Amplitude] Page Title, [Amplitude] Page URL.

Subdomain attribution tracking

Traffic from one subdomain to another (like analytics.amplitude.com to experiment.amplitude.com) isn't tracked by default. To exclude the attribution tracking on location.hostname, but not other subdomains, add the string value of location.hostname in the Exclude Referrers input under the Track marketing attribution section. Refer to the full details in the table.

BeforeCurrent
Track attribution of all subdomains.Excludes all subdomains of the same root domain as referrer.

User agent parser

The new template changes the way it parses the device related info, which might affect the value of OS, Device Type, Device Family (event.os_name, event.os_version, event.device_model, event.device_manufacturer), and related properties. To continue using the older way to parse user agent, check the (Legacy) Enable client side user agent enrichment checkbox. Refer to the full details in the table.

BeforeCurrent
Client-side user agent parsing.Server-side user agent parsing by Amplitude ingestion endpoints.

Was this helpful?