Google Tag Manager is a platform to manage all your website's tags without code.
A variant of an Amplitude Destination Plugin is required to forward events to Google Tag Manager. Below is a template of a Destination Plugin tailored for Google Tag Manager. It creates an instance of the
Google Tag Manager browser snippet and forwards tracked events from Amplitude's SDK. This template is customizable for any needs.
1 2import { DestinationPlugin, Event, PluginType, Result } from '@amplitude/analytics-types'; 3 4export class GTMPlugin implements DestinationPlugin { 5 name = 'google-tag-manager'; 6 type = PluginType.DESTINATION as const; 7 containerId: string; 8 9 constructor(containerId: string) {10 this.containerId = containerId;11 }12 13 async setup(): Promise<void> {14 if (!window.dataLayer) {15 window.dataLayer = window.dataLayer || [];16 window.dataLayer.push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' });17 const head = document.getElementsByTagName('head')[0],18 script = document.createElement('script'),19 dataLayer = 'datalayer' != 'dataLayer' ? '&l=' + 'datalayer' : '';20 script.async = true;21 script.src = 'https://www.googletagmanager.com/gtm.js?id=' + this.containerId + dataLayer;22 head.insertBefore(script, head.firstChild);23 }24 }25 26 async execute(event: Event): Promise<Result> {27 window.dataLayer.push(event);28 29 return {30 code: 200,31 event: event,32 message: 'Event pushed onto GTM Data Layer',33 };34 }35}
Inside the app's code, the plugin may then be imported and added to the Amplitude SDK instance.
1import * as amplitude from '@amplitude/analytics-browser';2import { GTMPlugin } from './GTMPlugin';3 4amplitude.init(AMPLITUDE_API_KEY);5amplitude.add(new GTMPlugin(GOOGLE_TAG_MANAGER_CONTAINER_ID));6 7amplitude.logEvent('open app');
Thanks for your feedback!
April 19th, 2024
Need help? Contact Support
Visit Amplitude.com
Have a look at the Amplitude Blog
Learn more at Amplitude Academy
© 2024 Amplitude, Inc. All rights reserved. Amplitude is a registered trademark of Amplitude, Inc.