If you already have your Next.js app set up, you might want to add Google Tag Manager (GTM) to it.
<Script>
component of Next.js.First, you need a script that's required for GTM to work. Here's a screenshot of where you can find this Google Tag Manager installation script:
Screenshot of where to find GTM container installation script
Screenshot of a popup window with GTM container installation script
/app
folder of your Next.js app, you will find app/layout.js
or app/layout.tsx
file. This is the main layout file of your app you can add the script to.<head>
of your layour, you need to:- import
<Script>
component fromnext/script
- add
<Script>
component to the<body>
of the page - pass this script as a
{children}
prop to<Script>
component - add
strategy="beforeInteractive"
prop to ensure that this script will be placed in the<head>
of the page
<Script>
component added:import Script from 'next/script';
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<Script id="gtm" strategy="beforeInteractive">
{`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-124RPQXB');`}
</Script>
</body>
</html>
);
}
To check if the script works, you paste URL to your page in this field and click "Test".
If it works, you will see a green checkbox.
Screenshot of a popup window with option to test GTM container installation script on a given URL
Congratulations! You have successfully added Google Tag Manager to your Next.js app.