For a Next.js App Router Google Tag Manager setup, load the container once in the root layout with the GoogleTagManager component from @next/third-parties/google, set consent defaults in a beforeInteractive script before it, and let GA4 count route changes through enhanced measurement's browser history setting. Pick one page view method only. For forms handled by server actions, return a success result to a client component and push the conversion to the dataLayer from there, never on submit.
This is for developers and agency teams putting GTM on a client's Next.js site, or fixing one where GA4 numbers look wrong. It covers the component versus next/script, how page views work on client-side navigation, where duplicates come from, pushing events from client components, conversions from server actions (including redirects and spam), consent mode, Meta Pixel on route changes, and how to test all of it in Tag Assistant.
Why Next.js App Router breaks normal GTM setups
A classic website loads a new HTML document on every click. GTM loads, fires its Page View trigger, and your tags run. A Next.js App Router site loads one document and then swaps content on the client when people click a Link. The URL changes through the History API, but the page does not reload.
That one fact explains most broken setups:
- Page View triggers fire once. GTM's Page View, DOM Ready and Window Loaded triggers only fire on a real document load. After that, every route change is invisible to them.
- Thank-you pages stop working. A "Page Path equals /thank-you" trigger never fires if the visitor reaches that page by client-side navigation.
- Everything can double. GA4, GTM and Meta Pixel each have their own way of reacting to history changes. Add a manual page view on top and you count twice.
- Forms never submit in the old sense. Server actions post in the background. There is no page load after submit, and the browser's submit event fires even when the server rejects the data.
Should you use @next/third-parties GoogleTagManager or next/script?
Use the GoogleTagManager component unless you have a reason not to. It is a thin wrapper around next/script, so the two are close. The Next.js third-party libraries guide still labels @next/third-parties as experimental, but the GTM part is small and easy to read in the source.
What the component does, based on its current source:
- Two scripts. An inline script with the id
_next-gtm-init that creates the dataLayer and pushes the gtm.js start event, then the gtm.js file itself with the id _next-gtm.
- Default loading. Neither script sets a strategy, so both use
afterInteractive, the next/script default. GTM loads after hydration starts, not in the initial HTML.
- Props.
gtmId, gtmScriptUrl (for a server-side tagging domain), dataLayer, dataLayerName, auth and preview (for GTM environments). The source also accepts a nonce for a strict Content Security Policy.
- The dataLayer prop runs late. The object you pass in
dataLayer is pushed after the gtm.js event. That makes it fine for page metadata, and wrong for consent defaults.
| Option | Good for | Watch out for |
GoogleTagManager component | Most sites. Handles environments, custom dataLayer names, server-side script URL, and gives you sendGTMEvent | Marked experimental. Consent defaults must be set separately, before it |
next/script with the GTM snippet | When you need to control the strategy or copy Google's snippet exactly | Inline scripts need an id. You write your own push helper |
Raw <script> tag in the layout | Rarely needed | Easy to end up with a second copy next to the component |
GoogleAnalytics component plus GTM | Nothing, if GTM already sends GA4 | Two Google tags for the same property means double page views |
If you are still deciding between a hardcoded Google tag and a GTM container for the client, the trade-offs are in Google tag vs Google Tag Manager.
The root layout setup, with consent defaults first
Consent mode only works when the default command runs before any tag sends data. Google's consent docs say the order is what matters, and that defaults called out of order will not work. In Next.js, the cleanest way to guarantee that order is a beforeInteractive script. The next/script reference says these are injected into the initial HTML, always placed in the head, must live in a root layout, and run once per document load. GTM then loads later with afterInteractive.
// app/layout.tsx
import Script from 'next/script'
import { GoogleTagManager } from '@next/third-parties/google'
const CONSENT_DEFAULT =
"window.dataLayer = window.dataLayer || [];" +
"function gtag(){dataLayer.push(arguments);}" +
"gtag('consent', 'default', {" +
" ad_storage: 'denied'," +
" ad_user_data: 'denied'," +
" ad_personalization: 'denied'," +
" analytics_storage: 'denied'," +
" wait_for_update: 500" +
"});"
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<GoogleTagManager gtmId={process.env.NEXT_PUBLIC_GTM_ID as string} />
<body>
{children}
<Script
id="consent-default"
strategy="beforeInteractive"
dangerouslySetInnerHTML={{ __html: CONSENT_DEFAULT }}
/>
</body>
</html>
)
}
A few notes on this:
- Use gtag for consent, not sendGTMEvent. Consent commands have to reach the
dataLayer as an arguments object, which is what the gtag() function pushes. Pushing a plain object like { event: 'consent_update' } does not change consent state.
- Updating consent. When the banner is accepted, call
gtag('consent', 'update', ...) from your banner component. Since gtag is declared in a classic inline script, it is available on window. In TypeScript, declare it on the window type so the call compiles.
- CMP in GTM instead. If the client uses a consent platform with a GTM template, you can skip the inline defaults and let the template set them on the Consent Initialization trigger. Do one or the other. Two sources of defaults make debugging painful.
- Defaults per region. If you only need denied defaults in the EEA and UK, add the
region parameter. The full set of options is in our consent mode v2 implementation guide.
Does @next/third-parties track page views on route change?
No. The component only loads GTM. Page views on client-side navigation come from GA4 itself. The Next.js docs say this directly for their GoogleAnalytics component: GA4 tracks page views when the browser history state changes, as long as enhanced measurement is on and "Page changes based on browser history events" is checked. The same applies when GA4 runs through a Google tag inside GTM, because enhanced measurement settings live on the GA4 data stream, not in the page code.
Google's help page for enhanced measurement says the page_view event fires when the page loads or when the active site changes the browser history state, and that it listens for pushState, popState and replaceState. Next.js uses pushState for normal Link clicks and router.push, so that is covered. Back and forward buttons are covered through popState.
So for most marketing sites, the right setup is:
- In GA4. Admin, Data streams, your web stream, enhanced measurement on, and under page views, the browser history setting checked.
- In GTM. One Google tag with the GA4 measurement ID, firing on Initialization or All Pages. No extra page_view event tags. No History Change trigger on anything GA4 related.
- In code. Nothing. Do not push page view events from a route listener.
Why are GA4 page views doubled in Next.js?
Almost always because two methods are running at once. Common combinations:
| What is set up | Result | Fix |
| Enhanced measurement history setting on, plus a GA4 page_view tag on a GTM History Change trigger | Two page_views per route change | Delete the History Change tag |
Enhanced measurement history setting on, plus a usePathname effect that pushes a page view event | Two page_views per route change, sometimes three on first load | Pick one. See the manual option below |
send_page_view set to false in the Google tag, but the history setting left on | Route changes still send page_view | Turn off the history setting too |
GTM Google tag plus the GoogleAnalytics component, same measurement ID | Every page_view twice, including the first | Remove one. Keep GTM |
| GTM loaded in the root layout and again in a nested layout or page | Container appears twice in Tag Assistant | Keep it in the root layout only |
The third row catches experienced people. Google's developer docs on page views state that enhanced measurement will send history-based page_view events even when send_page_view is false. To fully take over page views, you have to turn off both.
When to send manual virtual page views instead
Enhanced measurement is fine until you need control. Reasons to switch to manual page views:
- Query string noise. Filters or search update the URL with
router.replace on every keystroke and you get page_views you do not want.
- Wrong page titles. Check the
page_title parameter in DebugView on a few navigations. If it shows the previous page's title, the history event is firing before the new title is in the document.
- Extra parameters. You want content group, logged-in state or page type on every page view.
If you switch, do all three steps: set send_page_view to false as a configuration parameter on the GTM Google tag, uncheck the browser history setting in the GA4 stream, then send page views yourself.
// app/route-tracker.tsx
'use client'
import { useEffect, useRef } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
import { sendGTMEvent } from '@next/third-parties/google'
export function RouteTracker() {
const pathname = usePathname()
const searchParams = useSearchParams()
const lastUrl = useRef('')
useEffect(() => {
const qs = searchParams.toString()
const url = pathname + (qs ? '?' + qs : '')
if (url === lastUrl.current) return
lastUrl.current = url
sendGTMEvent({
event: 'virtual_page_view',
page_location: window.location.href,
page_title: document.title,
})
}, [pathname, searchParams])
return null
}
Render it in the root layout inside a Suspense boundary, since useSearchParams on a statically rendered route needs one. In GTM, create a Custom Event trigger for virtual_page_view and a GA4 event tag named page_view that reads page_location and page_title from Data Layer Variables. Google notes that a custom page_location must be the full URL with the protocol, which window.location.href gives you.
Two things to know about this component. The effect runs on the first render too, so it handles the landing page as well. And the first push can land in the dataLayer before GTM has finished loading. That is fine, because the queue is processed in order once it loads, but it is the push most worth checking in Tag Assistant. If you only care about the path and not filters, drop useSearchParams from the dependency list so query string changes do not count.
Pushing dataLayer events from client components
sendGTMEvent is a small helper. In the current source, it creates the dataLayer array if it does not exist yet and pushes your object onto it. That means events pushed before GTM loads are queued, not lost. The docs say it only works when the GoogleTagManager component is rendered in a parent layout or the same file, because the helper uses the data layer name the component set.
'use client'
import { sendGTMEvent } from '@next/third-parties/google'
export function PricingCta({ plan }: { plan: string }) {
return (
<button
onClick={() =>
sendGTMEvent({ event: 'pricing_cta_click', plan_name: plan })
}
>
Start trial
</button>
)
}
Rules that save time later:
- Only from client components. Server components run on the server, where there is no
window. Anything that needs to reach GTM has to happen in a file marked 'use client'.
- Push in handlers or effects, not during render. Render can run more than once. In development, React Strict Mode also runs effects twice, so guard effects with a ref when a duplicate would matter.
- Name events on purpose. Use GA4 recommended names like
generate_lead where they fit, and keep custom names consistent across clients. Our GA4 key events and naming plan has a template.
- Reset nested objects. GTM merges pushed objects into its data model. If you push
ecommerce objects, push { ecommerce: null } first so old items do not carry over.
How do you track a server action form submission in GTM?
Do not track the click or the submit event. A server action form fires the browser's submit event as soon as the visitor clicks, before the server has validated anything. If your conversion fires there, every failed attempt, every validation error and every bot counts as a lead. GA4's enhanced measurement form interactions can have the same problem, which is why many teams turn that option off and send their own lead event. The general pattern is covered in our GTM form tracking guide. Here is the Next.js version.
The idea: the server action returns a result, the client component sees the result, and only a real success triggers the push.
// app/contact/actions.ts
'use server'
import { randomUUID } from 'crypto'
export type LeadState = { ok: boolean; error?: string; leadId?: string }
export async function submitLead(
prev: LeadState,
formData: FormData
): Promise<LeadState> {
// Honeypot: look successful to the bot, but return no leadId
if (formData.get('website_url')) return { ok: true }
const email = String(formData.get('email') || '').trim()
if (!email.includes('@')) {
return { ok: false, error: 'Enter a valid email address.' }
}
try {
const leadId = randomUUID()
await saveLeadToCrm({ leadId, email }) // your own function
return { ok: true, leadId }
} catch {
return { ok: false, error: 'Something went wrong. Please try again.' }
}
}
// app/contact/lead-form.tsx
'use client'
import { useActionState, useEffect, useRef } from 'react'
import { sendGTMEvent } from '@next/third-parties/google'
import { submitLead, type LeadState } from './actions'
const initialState: LeadState = { ok: false }
export function LeadForm() {
const [state, formAction, pending] = useActionState(submitLead, initialState)
const trackedId = useRef<string | null>(null)
useEffect(() => {
if (!state.ok || !state.leadId) return
if (trackedId.current === state.leadId) return
trackedId.current = state.leadId
sendGTMEvent({
event: 'generate_lead',
form_name: 'contact',
lead_id: state.leadId,
})
}, [state])
if (state.ok) return <p>Thanks. We will be in touch.</p>
return (
<form action={formAction}>
<input type="email" name="email" required />
<input type="text" name="website_url" tabIndex={-1} autoComplete="off" hidden />
{state.error ? <p aria-live="polite">{state.error}</p> : null}
<button disabled={pending}>Send</button>
</form>
)
}
What this handles:
- Validation failures. The action returns
ok: false, nothing is pushed, and the visitor sees the error.
- Server or CRM errors. Caught and returned as an error. No conversion for a lead you did not save.
- Spam. The honeypot path returns success without a
leadId, so the bot sees a thank-you and your ad platforms see nothing.
- Double fires. The ref keyed to
leadId stops the same lead from being pushed twice if the component re-renders or Strict Mode runs the effect again.
- Double clicks. The
pending flag disables the button while the action runs.
In GTM, a Custom Event trigger on generate_lead fires your GA4 event tag, the Google Ads conversion tag and the Meta Lead tag. Use lead_id as the Google Ads transaction ID so Google can drop duplicates. If you also send enhanced conversions, push the hashed or raw user data in the same event, following the enhanced conversions setup guide.
Multi-step forms
For a multi-step form, push a step event (for example form_step with a step_number) when each step is accepted, and keep generate_lead for the final server success only. Do not mark the step events as key events in GA4, or a three-step form counts as three conversions.
What if the server action redirects to a thank-you page?
Many sites call redirect('/thank-you') at the end of the action. The redirect reference says that in a server action, redirect does a client-side navigation when JavaScript is available, uses push by default, and serves a 303 HTTP redirect for progressive enhancement submissions where JavaScript has not loaded. It also throws, so it has to be called outside any try block.
For tracking, that means:
- GTM Page View triggers will not fire on
/thank-you in the normal case, because there was no document load. A Page Path condition on a Page View trigger looks broken but is working as designed.
- A History Change trigger with a Page Path condition will fire, but so will a refresh, a bookmark or someone sharing the link. Thank-you URLs reached directly inflate conversions.
The better pattern is to redirect with the ID in the URL, then push from a client component on the thank-you page and remember that you did:
// in the action, after saving, outside try/catch
redirect('/thank-you?lead=' + encodeURIComponent(leadId))
// app/thank-you/lead-pixel.tsx
'use client'
import { useEffect } from 'react'
import { useSearchParams } from 'next/navigation'
import { sendGTMEvent } from '@next/third-parties/google'
export function LeadPixel() {
const leadId = useSearchParams().get('lead')
useEffect(() => {
if (!leadId) return
const key = 'lead_tracked_' + leadId
try {
if (sessionStorage.getItem(key)) return
sessionStorage.setItem(key, '1')
} catch {}
sendGTMEvent({ event: 'generate_lead', form_name: 'contact', lead_id: leadId })
}, [leadId])
return null
}
Visits without a lead parameter push nothing, and a refresh in the same tab is skipped. The lead_id as transaction ID protects Google Ads from anything that slips through. If the client's site has to work without JavaScript, the 303 path is a full page load, and this component still runs once the page hydrates.
Sending the same lead from the server for Meta
Because the server action already has the lead, it is a natural place to send a Conversions API Lead event. If you do that and also fire the Pixel Lead in the browser, both must share the same event ID or Meta counts two leads. Use the leadId for both: send it as event_id in the server call, return it to the client, and pass it to the Pixel tag in GTM as the eventID option. The details and common mistakes are in our Meta CAPI deduplication guide.
How do you fire Meta Pixel PageView on Next.js route changes?
Check before you add anything. Meta's single page application guide describes a disablePushState setting that stops the Pixel from sending PageView events on history state changes. In other words, the Pixel already sends PageView on pushState navigations by default. If you also add a History Change trigger that fires fbq('track', 'PageView'), each route change counts twice.
So there are two valid setups. Pick one:
| Setup | Base Pixel tag | Route changes |
| Let the Pixel handle it (simplest) | Fires once on Initialization or All Pages with init and PageView | Handled by the Pixel. No extra tags |
| Control it yourself | Same, with disablePushState set to true | A PageView tag on a History Change trigger, or on your virtual_page_view event |
Meta says turning off push state handling is not recommended, so use the second setup only when you have a reason, such as query string changes producing extra PageViews. In the second setup, the base code in a GTM Custom HTML tag looks like this:
<script>
// standard Meta base code loader goes here
fbq('init', 'YOUR_PIXEL_ID');
fbq.disablePushState = true;
fbq('track', 'PageView');
</script>
Whichever you choose, make sure the base tag cannot fire twice. A base Pixel tag on a History Change trigger reruns init on every navigation, which is a common source of the problems in Meta duplicate events.
Avoiding duplicate GTM containers in layouts
Put GoogleTagManager in the root layout and nowhere else. Things that cause a second copy:
- A leftover snippet. Someone pasted Google's snippet into the layout years ago, then a later developer added the component. Search the codebase for
googletagmanager.com and your container ID.
- Per-page loading. The docs show loading GTM in a single page file. That is fine for a one-off landing page, but combined with a root layout copy you get two.
- Multiple root layouts. If the app uses route groups like
(marketing) and (app), each with its own root layout, each needs its own GTM component and consent script. The Next.js route groups docs note that moving between different root layouts causes a full page load, so GTM reloads there anyway.
- The client's own container. Agency container plus client container both sending to the same GA4 property is a duplicate even though the IDs differ.
- A pages directory. Sites partway through migration may have a
_app or _document with GTM too. Navigation between the two routers is a full load, and both copies can run.
If you run server-side tagging, keep the same one-copy rule and pass your tagging server URL through gtmScriptUrl. The server container side is covered in our server-side GTM setup guide.
Testing with Tag Assistant on client-side navigation
Testing an App Router site means testing navigation, not just page loads. Typing a URL into the address bar causes a full load and hides the bugs you are looking for.
- Start preview. Open Tag Assistant from GTM Preview and connect to the site. Accept or reject the consent banner and check the consent state on the first events.
- Click through with links. Navigate three or four pages using the site's own menu. Each click should add a history event in the Tag Assistant timeline, not a new page load.
- Count page views. In GA4 DebugView, each navigation should produce exactly one
page_view. Check page_location and page_title on each one.
- Back and forward. Use the browser buttons. You should still see one page_view per step.
- Query strings. If the site has filters, change one and see whether you want that counted as a page view.
- Form failure. Submit the form with a bad email. No
generate_lead should appear.
- Form success. Submit a real test. Exactly one
generate_lead with a lead_id. Then refresh the thank-you page and confirm nothing new fires.
- Meta. Use Test Events in Events Manager and confirm one PageView per navigation and one Lead, with the server and browser Lead marked as deduplicated if you send both.
If the form tests fail, the checklist in GA4 form submissions not tracked walks through the usual causes.
Getting it fixed for a client
Next.js sites tend to look fine in a quick check and then over count or miss leads once real traffic arrives. If a client's GA4, Google Ads or Meta numbers do not match their CRM, start with a free tracking check. We go through the container, the page view method and the form flow, and tell you exactly what is counting wrong.