Version 11 of Next.js recently introduced a new approach with the Script
component offering various strategies.
To avoid duplicate tags, it is advised to implement Google TagManager using the afterInteractive
strategy.
In my experimentation:
// _app.js
import Script from 'next/script';
class MyApp extends App {
public render() {
const { Component, pageProps } = this.props;
return (
<>
<Script strategy="afterInteractive">
{`(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-XXXXXXX');`}
</Script>
<Component {...pageProps} />
</>
);
}
}
export default MyApp;
The current implementation successfully loads Google Tag Manager, however, it inserts the same script on each page navigation leading to duplicate tags being generated.
Is there a more effective way to utilize the new Script
component?