tanstack-router-ga4
v1.6.0
Published
Google Analytics (GA4) integration for TanStack Router and TanStack Start.
Maintainers
Readme
tanstack-router-ga4
Google Analytics (GA4) integration for TanStack Router and TanStack Start, built for modern React apps that need reliable analytics with minimal setup.
Live demo: tanstack-router-ga4.ben3d.ca
Features
- Automatically records
page_viewevents on route changes - Full TypeScript support for common GA4 events (
sign_up,generate_lead, etc.) and custom events - Supports all Google Analytics configuration options (for example
debug_modeanduser_id) - Supports advanced features like user-session association, consents and queries (
get) - Deferred GA script injection by default — waits for the browser to be idle via
requestIdleCallbackbefore loading, improving initial page load performance. Passdeferred={false}to load immediately - Designed for TanStack Router and TanStack Start with correct behavior across client-side navigation and SSR
- Full test suite with unit/integration coverage and browser-based E2E tests
- Ultra small bundles (minified/gzipped) to less than 1KB.
Install
pnpm add tanstack-router-ga4Peer dependencies: react (>=18), @tanstack/react-router (>=1).
Usage
Mount the component in your app shell (for example a RootDocument or root layout) so every route gets automatic page views, and use the hook as a typed wrapper over the core gtag commands.
import { HeadContent, Scripts } from '@tanstack/react-router';
import type { ReactNode } from 'react';
import { GoogleAnalytics, useGoogleAnalytics } from 'tanstack-router-ga4';
// In your root document — automatic page_view on each route change
function RootDocument({ children }: { children: ReactNode }) {
return (
<html lang="en">
<head>
<HeadContent />
</head>
<body>
<GoogleAnalytics measurementId="G-XXXXXXXXXX" />
{children}
<Scripts />
</body>
</html>
);
}
// In any component — track custom events
function SignupForm() {
const ga = useGoogleAnalytics();
const handleSubmit = () => {
const user = await registerUser({ email: '[email protected]', password: 'secure-password' });
// associate user id with session
ga.set({
user_id: user.id,
user_properties: {
email: user.email,
username: user.username,
},
});
// send standard GA event for signups
ga.event('sign_up', { method: 'email' });
};
return <button onClick={handleSubmit}>Sign up</button>;
}Deferred loading
By default, GoogleAnalytics delays GA script injection until the browser is idle using requestIdleCallback. This moves analytics work out of the critical rendering path, improving Time to Interactive and other Core Web Vitals. On browsers that don't support requestIdleCallback (such as Safari) the script loads immediately so no data is lost.
To load GA immediately instead, pass deferred={false}:
<GoogleAnalytics measurementId="G-XXXXXXXXXX" deferred={false} />Hook API
useGoogleAnalytics() exposes typed wrappers around the core gtag commands:
set(config)for global configconfig(measurementId, config?)for per-stream configevent(name, params?)for recommended and custom eventsget(measurementId, fieldName, callback?)for callback-based reads likeclient_idconsent('default' | 'update', params)for consent mode updates
Development
This repo contains the library and a TanStack Start demo:
- Library:
packages/tanstack-router-ga4 - Demo:
packages/example-website
pnpm install
pnpm dev
pnpm tsc # typescript-native
pnpm build
pnpm lint # oxlint
pnpm lint:fix
pnpm format # oxfmt
pnpm test # vitestPublishing runs from the repo root and uses the root README as the package README. Run pnpm make-release to publish. For E2E tests, run pnpm exec playwright install chromium then pnpm test.
License
MIT
Author
Created by Ben Houston and sponsored by Land of Assets.
