Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
¿Cómo usar Google Analytics con la aplicación next.js?

Estoy usando componentes con estilo con next.js, por lo que mis estilos deben representarse en el lado del servidor, por lo tanto, ¿cómo puedo agregar Google Analytics a mi sitio web?

Revisé el ejemplo de Google Analytics de next.js , pero como dije, mi archivo _document es diferente debido al uso de componentes con estilo.

 // _document.js import React from 'react' import Document from 'next/document' import { ServerStyleSheet } from 'styled-components' class MyDocument extends Document { static async getInitialProps(ctx) { const sheet = new ServerStyleSheet() const originalRenderPage = ctx.renderPage try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />), }) const initialProps = await Document.getInitialProps(ctx) return { ...initialProps, styles: ( <> {initialProps.styles} {sheet.getStyleElement()} </> ), } } finally { sheet.seal() } } } export default MyDocument
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Para inicializar gtag correctamente, haga lo siguiente en _document.js o donde haya definido Head :

 import { Head } from 'next/document'; export default class MyDocument extends Document { render() { return ( // ... <Head> <script async src="https://www.googletagmanager.com/gtag/js?id=[Tracking ID]" /> <script dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '[Tracking ID]', { page_path: window.location.pathname }); `, }} /> </Head> ); } }

Lo anterior hará un seguimiento de las visitas a la página en la carga de la página. Para realizar un seguimiento de la navegación, agregue lo siguiente a _app.js :

 import { useRouter } from 'next/router'; import { useEffect } from "react"; export default const App = () => { const router = useRouter(); const handleRouteChange = (url) => { window.gtag('config', '[Tracking ID]', { page_path: url, }); }; useEffect(() => { router.events.on('routeChangeComplete', handleRouteChange); return () => { router.events.off('routeChangeComplete', handleRouteChange); }; }, [router.events]); return ( // ... ); };

Ver también:

  • https://github.com/vercel/next.js/tree/canary/examples/with-google-analytics
  • https://github.com/vercel/next.js/issues/160
over 4 years ago · Santiago Trujillo Report

0

En su _document.js , anula el método getInitialProps . También puede anular el método de render . Simplemente agregue

 render() { return ( <Html lang={this.props.lang || "en"}> <Head> <script dangerouslySetInnerHTML={{ __html: `[google analytics tracking code here]` }} /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); }

Asegúrese de importar los componentes necesarios:

import Document, { Html, Head, Main, NextScript } from "next/document"

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!