Leí ¿Cómo cargar Google Tag Manager con el componente next/script (Next.js 11)? y también leí esta página de documentos .
Pero ninguno de ellos resolvió mi problema.
Quiero incluir Google Tag en muchos de mis sitios desarrollados con nextjs. Por lo tanto, he creado un componente reutilizable simple:
import Script from 'next/script' const GoogleTag = ({ identifier }) => { if (!identifier || !identifier.startsWith('G-')) { throw new Error('Google tag id is not correct;'); } return <> <Script src={`https://www.googletagmanager.com/gtag/js?id=${identifier}`} strategy="afterInteractive" /> <Script id="google-analytics" strategy="afterInteractive"> {` window.dataLayer = window.dataLayer || []; function gtag(){window.dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${identifier}'); `} </Script> </> } export default GoogleTag; Y lo uso en cada uno de mis sitios, en el archivo _app.js , de esta manera:
import Head from 'next/head'; import GoogleTag from '../Base/GoogleTag'; export default function MyApp({ Component, pageProps }) { return ( <> <Head> <GoogleTag identifier='G-9XLT855ZE0' /> </Head> <div> application code comes here </div> </> ) }Pero no veo que se cargue la secuencia de comandos de Google Tag en las Herramientas de desarrollo de Chrom, en la pestaña Redes internas.
Para usar correctamente la google tag en su aplicación next.js , debe agregar el script GTM a _document.js en la sección Head .
código de ejemplo _documents.js , fuente.
import Document, { Html, Head, Main, NextScript } from 'next/document' import { GA_TRACKING_ID } from '../lib/gtag' export default class MyDocument extends Document { render() { return ( <Html> <Head> {/* Global Site Tag (gtag.js) - Google Analytics */} <script async src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`} /> <script dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${GA_TRACKING_ID}', { page_path: window.location.pathname, }); `, }} /> </Head> <body> <Main /> <NextScript /> </body> </Html> ) } }Para configurar la vista de página de Google Analytics para aplicaciones de una sola página y otros métodos de uso de GT en next.js. Puedes visitar esta fuente1 , fuente2 .