Next.js integration guide
Next.js cookie consent, connected to real analytics.
Three files connect the Polimeo banner to one Google Analytics 4 property. Google loads only after the Analytics category is allowed. Returning visitors keep their choice, and a Cookie settings button lets them change it.
See our own published policy and integration →1. Prepare your service and analytics property
Create a service in Polimeo. In Banner settings, save your enabled categories and published policies, then confirm their review. Enable Analytics, the decline button and preferences. Copy the service ID from Integration and your G-… measurement ID from Google Analytics. Keep your existing site layout and styles when adding the files below.
This example owns the Google tag for one GA4 property. Remove other installations of the same tag, including unconditional GoogleAnalytics components and GTM tags. In GA4, turn off Enhanced Measurement for this stream: this example sends page_view explicitly and does not implement automatic scroll, outbound-link or form measurement.
The three-file example below uses explicit script blocking with Google's analytics disable flag. It does not implement Google Consent Mode or Google Ads. The shared widget also offers a separate built-in Consent Mode v2 integration via data-google-analytics and data-google-ads attributes; use one approach only. Polimeo itself does not install Google Analytics. The example is code for your own site, and needs verification with your property and browser settings.
- Next.js App Router with TypeScript; no additional package required
- One shared root layout, one Polimeo widget, one GA4 property
- Analytics category enabled and optional; decline and settings available
- No other code may initialize the same Google tag independently
2. Add the analytics consent adapter
Save this as app/analytics.ts. The adapter subscribes before reading the current choice, so it handles both saved consent and later decisions. Without analytics consent it does not insert the Google script or queue page views.
On withdrawal it sets Google's ga-disable flag immediately. That also applies if the script is still downloading. The flag stops future collection for this property; it does not erase previously collected data or delete existing analytics cookies. Check any additional cookie cleanup requirements for your site.
The explicit page_view events use the pathname without query strings, fragments or document titles. Review any automatic data collection in your GA4 setup too, and do not put personal information in paths. Repeated consent notifications do not install a second script or send another view of the same path.
// A single GA4 property, with no Google tag installed elsewhere on the page.
export type Consent = Record<string, boolean> | null;
export type ConsentAPI = {
getConsent(): Consent;
onConsentChange(callback: (choice: Consent) => void): (() => void) | void;
showBanner(): void;
};
type AnalyticsWindow = Window & {
dataLayer?: IArguments[];
[key: `ga-disable-${string}`]: boolean;
};
let activeId: string | null = null;
let allowed = false;
let lastPath: string | null = null;
const configured = new Set<string>();
function gtag(...args: unknown[]) {
void args; // The function signature stays typed; Google consumes Arguments below.
const browser = window as unknown as AnalyticsWindow;
browser.dataLayer ??= [];
// gtag's queue uses Arguments objects, not arrays.
// eslint-disable-next-line prefer-rest-params -- gtag consumes Arguments objects.
browser.dataLayer.push(arguments);
}
export function trackPageView(path: string) {
if (!allowed || !activeId || path === lastPath) return;
lastPath = path;
gtag("event", "page_view", {
send_to: activeId,
page_location: window.location.origin + path,
// Do not forward query strings, fragments or document titles.
page_title: path,
});
}
export function connectAnalytics(api: ConsentAPI, measurementId: string) {
if (!/^G-[A-Z0-9]+$/.test(measurementId)) {
throw new Error("Use your GA4 measurement ID (G-...).");
}
const browser = window as unknown as AnalyticsWindow;
activeId = measurementId;
let disposed = false;
const apply = (choice: Consent) => {
if (disposed) return;
allowed = choice?.analytics === true;
// This check also stops an already-loaded Google tag after withdrawal.
browser[`ga-disable-${measurementId}`] = !allowed;
if (!allowed) {
lastPath = null;
return;
}
if (!configured.has(measurementId)) {
configured.add(measurementId);
gtag("js", new Date());
gtag("config", measurementId, {
send_page_view: false,
allow_google_signals: false,
allow_ad_personalization_signals: false,
});
const script = document.createElement("script");
script.async = true;
script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
document.head.appendChild(script);
}
trackPageView(window.location.pathname);
};
// Listen first, then read: handle saved choices and future changes.
const unsubscribe = api.onConsentChange(apply);
apply(api.getConsent());
return () => {
disposed = true;
unsubscribe?.();
allowed = false;
browser[`ga-disable-${measurementId}`] = true;
};
}
3. Add the Client Component and settings button
Save this beside it as app/PolimeoConsent.tsx. Replace YOUR_SERVICE_ID and G-YOURMEASUREMENTID. The component connects when the widget script is ready, reads route changes with usePathname and removes its subscription on unmount.
Keep this component in the shared root, not inside each page. The persistent Cookie settings button reopens the banner, including on a later visit with saved consent. A denied or missing choice leaves analytics off; if the script cannot load, the visitor can reload to retry.
"use client";
import Script from "next/script";
import { usePathname } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { connectAnalytics, trackPageView, type ConsentAPI } from "./analytics";
// Replace both values. Enable the Analytics category in Polimeo first.
const SERVICE_ID = "YOUR_SERVICE_ID";
const GA_ID = "G-YOURMEASUREMENTID";
const getAPI = () =>
(window as Window & { PremexConsent?: ConsentAPI }).PremexConsent;
export default function PolimeoConsent() {
const pathname = usePathname();
const cleanup = useRef<(() => void) | undefined>(undefined);
const [ready, setReady] = useState(false);
const [failed, setFailed] = useState(false);
const connect = useCallback(() => {
const api = getAPI();
if (!api || cleanup.current) return;
cleanup.current = connectAnalytics(api, GA_ID);
}, []);
useEffect(() => {
// Also reconnect after a development Strict Mode remount.
connect();
return () => {
cleanup.current?.();
cleanup.current = undefined;
};
}, [connect]);
useEffect(() => {
if (pathname) trackPageView(pathname);
}, [pathname]);
return (
<>
<Script
id="polimeo-consent"
src={`https://polimeo.com/widget/${SERVICE_ID}`}
strategy="afterInteractive"
onReady={() => {
connect();
setReady(Boolean(getAPI()));
setFailed(false);
}}
onError={() => setFailed(true)}
/>
<button type="button" disabled={!ready} onClick={() => getAPI()?.showBanner()}>
Cookie settings
</button>
{failed && <p role="status">Cookie settings could not load. Reload to retry.</p>}
</>
);
}
4. Include it once in your root layout
Add PolimeoConsent to your existing app/layout.tsx, for example in the footer. Preserve your own fonts, metadata and other providers. Do not add a second widget Script alongside the component.
The afterInteractive strategy determines when the consent widget loads. The adapter separately controls when Google may load. Neither a loading strategy nor merely displaying a banner grants consent.
import PolimeoConsent from "./PolimeoConsent";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<footer><PolimeoConsent /></footer>
</body>
</html>
);
}
5. Verify fresh visits, navigation and withdrawal
Use a fresh browser profile and the Network panel. Filter for googletagmanager.com and google-analytics.com. Start without a saved choice, then repeat after a full reload with both accepted and declined consent. Use a test GA4 property and confirm the received page views there.
Our automated tests exercise no choice, rejection, saved acceptance, repeated notifications, route changes, withdrawal while loading and component cleanup. They check the integration's script insertion, event queue and disable flag. They do not replace checking Google's live tag on your own site.
- Fresh visit / decline: no Google script inserted and no page_view queued
- Accept Analytics: one Google script and one page_view for the current path
- Navigate: one view per new pathname, with no second script
- Reload: a saved acceptance enables analytics; a saved rejection does not
- Cookie settings → decline: future collection is disabled, including after a returning visit
- Accept again: analytics can resume without loading a duplicate tag
- Slow or failed widget load: analytics stays off until a valid choice is available
Alternative: the shared Consent Mode v2 integration
If you need GA4 and Google Ads together, the widget has a built-in basic Consent Mode v2 adapter. Use this instead of the three-file analytics example above and remove other Google tag installations. Replace the IDs below, load one widget and keep a Cookie settings button.
Denied defaults precede measurement. Analytics controls analytics_storage; Marketing controls ad_storage, ad_user_data and ad_personalization. Google loads only after a relevant choice. Save and review your categories against the published policies in Banner settings first.
For SPA navigation, await window.PremexConsent.refreshConsent(), then call window.PremexConsent.trackPageView(window.location.pathname). Disable GA4 Enhanced Measurement for this explicit page-view integration. On withdrawal the adapter sends denied consent and disables application GA4 collection; a previously loaded Google library may still issue consent-related requests. Existing cookies and historical data are not erased.
Verify new and returning visits, separate Analytics/Marketing choices, navigation and withdrawal with browser Network tools and Google Tag Assistant before publishing. This does not configure a GTM container or your Google account settings.
<script src="https://polimeo.com/widget/YOUR_SERVICE_ID"
data-google-analytics="G-YOURMEASUREMENTID"
data-google-ads="AW-YOURADSACCOUNT" defer></script>
<button type="button" onclick="window.PremexConsent?.showBanner()">Cookie settings</button>Common questions
Can I use this with a different analytics provider?
Keep the widget connection and replace analytics.ts with that provider's initialization and opt-out APIs. Removing a script element alone does not stop an SDK that is already running. Test the provider's withdrawal behaviour separately.
Does this implement Google Consent Mode?
The three-file example uses explicit script blocking. For Consent Mode v2 and Google Ads, use the separate built-in widget integration described in the final section. Choose one integration; neither configures your Google account or a Tag Manager container.
Why is the API called PremexConsent?
Polimeo was previously Premex Terms. The JavaScript API retains its name so existing website integrations keep working.
Does the guide add analytics to my site automatically?
No. Downloading or reading the example does not change your site. Add the files to your own app, substitute your IDs and review and test the integration before publishing.
Further reading
Continue building
Make the first draft. Then make it yours.
Free, with no fixed expiry date. No credit card required.
See pricing and future-change terms