π£ Phase 3 β OptionalΒ Β·Β Only needed if your site is a SPA. Otherwise GTM handles it automatically.
page_view (SPA only)
When to pushβ
- Multi-page site (full reload): nothing to do. GTM derives
page_viewfrom thegtm.jsevent. - SPA (React/Vue/Next.js client-side routing): push on every client-side navigation.
SPA patternβ
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'page_view',
page: {
path: window.location.pathname + window.location.search,
title: document.title,
location: window.location.href
}
});
React Routerβ
import { useLocation } from 'react-router-dom';
import { useEffect } from 'react';
function usePageViewTracking() {
const location = useLocation();
useEffect(() => {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'page_view',
page: {
path: location.pathname + location.search,
title: document.title,
location: window.location.href
}
});
}, [location.pathname, location.search]);
}
Next.js App Routerβ
'use client';
import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
export function PageViewTracker() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
event: 'page_view',
page: {
path: pathname + (searchParams.toString() ? '?' + searchParams.toString() : ''),
title: document.title,
location: window.location.href
}
});
}, [pathname, searchParams]);
return null;
}
Parametersβ
| Parameter | Required |
|---|---|
event | required β 'page_view' |
page.path | recommended |
page.title | recommended |
page.location | optional |
Platformsβ
| Platform | Native event |
|---|---|
| GA4 | page_view |
| Meta | PageView |
| Google Ads | included in remarketing tag |
Pitfallsβ
- β Pushing
page_viewon the initial SPA load βgtm.jsalready covers it. - β Multiple pushes from a re-running effect β fix the deps.