How to install the Meta pixel and Google tag on a Next.js site

On Next.js (App Router), load Madder’s pixel snippet with next/script in app/layout.tsx, then call fbq(‘track’, ‘Lead’) in the client once the form succeeds, just before the router moves to the thank-you page.

For Next.js. Takes about 20 minutes

On this page

Step 2 of Madder’s pixel window prints the base code with your ID. Put the ID in NEXT_PUBLIC_META_PIXEL_ID instead of hard-coding it.

Before you start#

  • Next.js 13.4 or later with the app/ directory (Pages Router: the same Script component works in pages/_app.tsx).
  • A deploy you can push to, and the site’s production domain.

1Load the base code in the root layout#

Paths as of September 2026. In app/layout.tsx add an inline Script with the default afterInteractive strategy (it loads after hydration, which Next.js recommends for tag managers and analytics). Inline scripts must carry an id:

import Script from 'next/script'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
      <Script id="meta-pixel" strategy="afterInteractive">
        {`/* paste the body of Madder's snippet here (the !function... block,
           fbq('init', '${process.env.NEXT_PUBLIC_META_PIXEL_ID}') and
           fbq('track', 'PageView')), without the <script> tags */`}
      </Script>
    </html>
  )
}

Drop the snippet’s <noscript> image tag; it is optional. Next.js runs the script once per full page load, and later page changes happen without a reload. Madder’s brief for developers asks for a PageView on every page change too, so also call fbq('track', 'PageView') when the route changes, for example in a client component that watches usePathname().

2Fire Lead after the form succeeds#

Fire in the client component that owns the form, only after your server action or API call resolves, then navigate:

'use client'
import { useRouter } from 'next/navigation'

declare global { interface Window { fbq?: (...args: unknown[]) => void } }

export function LeadForm() {
  const router = useRouter()
  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const res = await fetch('/api/lead', { method: 'POST', body: new FormData(e.currentTarget) })
    if (!res.ok) return
    window.fbq?.('track', 'Lead')
    router.push('/thank-you')
  }
  return <form onSubmit={onSubmit}>{/* fields */}</form>
}

Fire before router.push: a useEffect on /thank-you runs on every visit, reloads and bookmarks included, and double-counts. If you must fire on the page instead, gate it with a one-time flag in sessionStorage.

3The Google tag#

Use @next/third-parties/google (npm install @next/third-parties@latest): render <GoogleTagManager gtmId="GTM-…" /> in the root layout and send the conversion with sendGTMEvent({ event: 'lead' }) next to the fbq call, or, with no container, render <GoogleAnalytics gaId="GT-…" /> with your Google tag ID (GT-… or AW-…). Which IDs and which conversion action: Install the Google tag on your website.

4Verify#

  1. Deploy to production with the ID set in your host’s environment settings.
  2. Open the live site with the Meta Pixel Helper Chrome extension; it should show one pixel, “Active”, with your ID, and Lead once after the form.
  3. In Meta Events Manager: Data sources › your pixel › Test events, enter your URL, submit the form, and check that PageView and Lead appear.
  4. In Madder, open the pixel window again with Set up tracking. Madder checks as it opens. “The pixel is live.” means you are done. Otherwise press Check again after a minute, and if Madder still can’t see it, press Mark as installed.

If it doesn’t work#

fbq is not defined
The form fired before afterInteractive finished loading; use window.fbq?.(...) and, for very fast submits, move the Script to beforeInteractive.
Pixel missing in production only
NEXT_PUBLIC_META_PIXEL_ID is unset on the host; rebuild after setting it (public env vars are inlined at build time).
Lead fires twice
React Strict Mode runs effects twice in development only; in production, check you did not fire both in the handler and in a useEffect on the thank-you page.
CSP blocks the script
Allow https://connect.facebook.net in script-src and pass your nonce to Script.