Google Tag Manager
Google Tag Manager is a platform to manage all your website's tags without code.
Set up the integration
Amplitude plugin setup
To forward events to Google Tag Manager, use a variant of an Amplitude Destination Plugin. The template below is a Destination Plugin tailored for Google Tag Manager. The plugin creates an instance of the Google Tag Manager browser snippet and forwards tracked events from Amplitude's SDK. Customize this template for any need.
ts
import { DestinationPlugin, Event, PluginType, Result } from '@amplitude/analytics-types';
export class GTMPlugin implements DestinationPlugin {
name = 'google-tag-manager';
type = PluginType.DESTINATION as const;
containerId: string;
constructor(containerId: string) {
this.containerId = containerId;
}
async setup(): Promise<void> {
if (!window.dataLayer) {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });
const head = document.getElementsByTagName('head')[0],
script = document.createElement('script'),
dataLayer = 'datalayer' != 'dataLayer' ? '&l=' + 'datalayer' : '';
script.async = true;
script.src = 'https://www.googletagmanager.com/gtm.js?id=' + this.containerId + dataLayer;
head.insertBefore(script, head.firstChild);
}
}
async execute(event: Event): Promise<Result> {
window.dataLayer.push(event);
return {
code: 200,
event: event,
message: 'Event pushed onto GTM Data Layer',
};
}
}
Amplitude plugin usage
In the app's code, import the plugin and add it to the Amplitude SDK instance.
ts
import * as amplitude from '@amplitude/analytics-browser';
import { GTMPlugin } from './GTMPlugin';
amplitude.init(AMPLITUDE_API_KEY);
amplitude.add(new GTMPlugin(GOOGLE_TAG_MANAGER_CONTAINER_ID));
amplitude.logEvent('open app');
Was this helpful?