Capítulo 331 de 456

Third Party Libraries

Core Idea

@next/third-parties provides optimized components/utilities for loading popular third-party scripts (Google Tag Manager, Google Analytics, Google Maps Embed, YouTube Embed) with minimal performance impact, using deferred/lazy loading strategies.

Key Concepts

  • @next/third-parties/google: entry point for all Google integrations, imported as named exports.
  • GoogleTagManager: component that instantiates a GTM container; fetches inline script after hydration.
  • sendGTMEvent: pushes events into the GTM dataLayer; requires <GoogleTagManager /> present in a parent layout/page/component.
  • GoogleAnalytics: component that loads GA4 via gtag.js after hydration; use only if GTM is not already handling analytics.
  • sendGAEvent: pushes GA4 events into the dataLayer.
  • GoogleMapsEmbed: lazy-loaded (via loading attribute) iframe wrapper for Google Maps Embed API.
  • YouTubeEmbed: fast-loading YouTube embed built on lite-youtube-embed.

Code Examples

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

export default function MyApp({ Component, pageProps }) {
  return (
    <>
      <Component {...pageProps} />
      <GoogleTagManager gtmId="GTM-XYZ" />
    </>
  )
}
  • O que demonstra: registrar o GTM globalmente via _app para todas as rotas.
import { sendGTMEvent } from '@next/third-parties/google'

export function EventButton() {
  return (
    <button onClick={() => sendGTMEvent({ event: 'buttonClicked', value: 'xyz' })}>
      Send Event
    </button>
  )
}
  • O que demonstra: disparo manual de evento customizado para o dataLayer.
import { GoogleMapsEmbed } from '@next/third-parties/google'

export default function Page() {
  return (
    <GoogleMapsEmbed apiKey="XYZ" height={200} width="100%" mode="place" q="Brooklyn+Bridge,New+York,NY" />
  )
}
  • O que demonstra: embed de mapa lazy-loaded sem JS manual de iframe.

Reference Tables

ComponentRequired propsNotes
GoogleTagManagergtmId (ou gtmScriptUrl)dataLayer, dataLayerName, auth, preview opcionais
GoogleAnalyticsgaIddataLayerName, debugMode, nonce opcionais
GoogleMapsEmbedapiKey, modeheight/width default auto; loading default lazy
YouTubeEmbedvideoidwidth/height default auto; params é query string (controls=0&start=10)

Anti-patterns

  • Incluir GoogleAnalytics junto com GoogleTagManager: duplica coleta de dados; configure Analytics dentro do próprio GTM em vez de usar os dois componentes.
  • Enviar sendGAEvent/sendGTMEvent sem o componente correspondente montado: a função não tem efeito se <GoogleAnalytics />/<GoogleTagManager /> não estiver em um componente pai.

Key Takeaways

  1. Todos os componentes carregam scripts após hidratação, priorizando performance de carregamento inicial.
  2. GoogleTagManager deve ser preferido a GoogleAnalytics quando GTM já está em uso, para evitar dados duplicados.
  3. Pageviews do GA4 são rastreados automaticamente em navegação client-side, desde que "Enhanced Measurement" esteja habilitado no painel admin.
  4. Biblioteca é experimental; recomenda-se instalar com latest ou canary.

Connects To

  • next/script: mecanismo genérico de carregamento de scripts que @next/third-parties usa internamente para otimizar terceiros específicos.