DEV Community

Cover image for Como implementar o Google Tag Manager e Analytics no Next.js 13+ com eventos de clique
Rogerio Orioli
Rogerio Orioli

Posted on

1 1 1 1 1

Como implementar o Google Tag Manager e Analytics no Next.js 13+ com eventos de clique

Como implementar o Google Tag Manager no Next.js 13+ com eventos de clique

O que você vai aprender:

  • Instalar e configurar o GTM com o pacote oficial do Next.js
  • Rastrear eventos de clique em links e botões
  • Criar um helper reutilizável para o dataLayer
  • Dica bônus: usar data-attributes para rastrear sem JavaScript
  • (Opcional) Adicionar o Google Analytics 4 junto com o GTM

1. Instale o pacote oficial

O Next.js 13+ traz suporte nativo para scripts de terceiros com o pacote:

npm install @next/third-parties
Enter fullscreen mode Exit fullscreen mode

Ou com yarn:

yarn add @next/third-parties
Enter fullscreen mode Exit fullscreen mode

2. Ative o GTM no layout

No arquivo app/layout.tsx ou app/layout.js, importe e adicione o componente:

import { GoogleTagManager } from '@next/third-parties/google'

export default function RootLayout({ children }) {
  return (
    <html lang="pt">
      <body>
        {children}
        <GoogleTagManager gtmId="GTM-XXXXXXX" />
      </body>
    </html>
  )
}
Enter fullscreen mode Exit fullscreen mode

3. (Opcional) Adicione também o Google Analytics 4

Você pode aproveitar o mesmo pacote para incluir o GA4 de forma oficial:

import { GoogleAnalytics } from '@next/third-parties/google'

export default function RootLayout({ children }) {
  return (
    <html lang="pt">
      <body>
        {children}
        <GoogleAnalytics gaId="G-XXXXXXXXXX" />
        <GoogleTagManager gtmId="GTM-XXXXXXX" />
      </body>
    </html>
  )
}
Enter fullscreen mode Exit fullscreen mode

Substitua "G-XXXXXXXXXX" pelo ID da sua propriedade GA4. Isso é útil caso você queira usar os dois ao mesmo tempo.
Substitua "GTM-XXXXXXX" pelo ID do seu container do GTM.


4. Crie um helper para eventos GTM

No diretório lib/ ou utils/, crie o arquivo gtm.js:

export const sendGTMEvent = ({ event, category, action, label }) => {
  if (typeof window !== 'undefined') {
    window.dataLayer = window.dataLayer || []
    window.dataLayer.push({
      event,
      category,
      action,
      label,
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

5. Envie eventos ao clicar em links

Agora, em qualquer componente, você pode disparar eventos:

import { sendGTMEvent } from '@/lib/gtm'

const handleClick = () => {
  sendGTMEvent({
    event: 'click',
    category: 'CTA',
    action: 'clique_home',
    label: 'Botão Saiba Mais',
  })
}

export default function BotaoCTA() {
  return (
    <a href="/produto" onClick={handleClick}>
      Saiba mais
    </a>
  )
}
Enter fullscreen mode Exit fullscreen mode

6. (Bônus) Usando data-attributes no HTML

Quer rastrear sem escrever JavaScript? Use data-attributes e configure os gatilhos diretamente no GTM:

<a href="/produto" data-gtm-event="click" data-gtm-label="saiba-mais-home">
  Saiba mais
</a>
Enter fullscreen mode Exit fullscreen mode

No GTM, crie um acionador do tipo "Clique em Elemento" e defina a condição com base no atributo data-gtm-event.


7. Testando

Use:

  • Modo Preview do GTM
  • Tag Assistant (extensão Chrome)
  • GA4 DebugView

Verifique se os eventos estão sendo enviados corretamente.


Conclusão

  • Essa abordagem é recomendada pela própria Vercel
  • Você ganha performance, organização e controle
  • Pronto para escalar com eventos personalizados e automações de marketing

Quer usar um componente pronto?

Você pode até criar um <GTMLink> reutilizável para simplificar isso:

import Link from 'next/link'
import { sendGTMEvent } from '@/lib/gtm'

export default function GTMLink({ href, children, eventData, ...props }) {
  const handleClick = () => {
    sendGTMEvent(eventData)
  }

  return (
    <Link href={href} {...props} onClick={handleClick}>
      {children}
    </Link>
  )
}
Enter fullscreen mode Exit fullscreen mode

Uso:

<GTMLink
  href="/produto"
  eventData={{
    event: 'click',
    category: 'CTA',
    action: 'clique_produto',
    label: 'Botão Produto',
  }}
>
  Ver Produto
</GTMLink>
Enter fullscreen mode Exit fullscreen mode

Obrigado pela leitura!

Sou Carlos Rogério Orioli, desenvolvedor e entusiasta de tecnologia, performance e marketing digital.
Meu GitHub é @rogeriorioli — estou à disposição para trocar ideias, contribuir ou colaborar em projetos.

Top comments (1)

Collapse
 
john_wilson profile image
John Wilson

Good job!

MongoDB Atlas runs apps anywhere. Try it now.

MongoDB Atlas runs apps anywhere. Try it now.

MongoDB Atlas lets you build and run modern apps anywhere—across AWS, Azure, and Google Cloud. With availability in 115+ regions, deploy near users, meet compliance, and scale confidently worldwide.

Start Free

👋 Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creators—let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay