Add the TermsFeed Privacy Consent cookie banner to Next.js as a plain <script> element in the root layout with the App Router, or in the custom document with the Pages Router. Both files render the <head> of every page, so the script loads once per visit, whichever route the visitor lands on. The code uses TypeScript and applies to Next.js 15 and 16, and setup takes about 15 minutes.

Privacy Consent needs no npm package and no initialization call. The tracking tools you move into vendors live in the TermsFeed app, so the application code carries none of them. Create the consent banner and copy its token with Create Your First TermsFeed Privacy Consent Banner.

Why the script stays out of pages and route components

The script stays out of pages and route components, because a <script> element there loads only where that component renders. A visitor who lands on another route does not get a consent banner, and no vendor runs for that visitor. Keep one copy in the root layout or the custom document. A second copy in one page load prints [ee][205bde55] or [ee][1040992c] in the Console tab and stops.

Use a plain <script> element and leave next/script out of it. The plain element lands in the server-rendered HTML as written, while the afterInteractive and lazyOnload strategies insert the script from client-side JavaScript, which delays the consent banner.

App Router: add the script to app/layout.tsx

Paste the script into the <head> of the root layout, the only layout that renders <html> and <head>. Replace YOUR_TOKEN with the token in the snippet from the Install page of your consent banner.

// app/layout.tsx
import type { ReactNode } from 'react';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <head>
        {/* Privacy Consent by TermsFeed (https://www.termsfeed.com) */}
        <script
          type="text/javascript"
          src="https://cdn.termsfeedtag.com/plugins/pc/v1/YOUR_TOKEN/plugin.js"
          async
        />
        {/* End Privacy Consent by TermsFeed (https://www.termsfeed.com) */}
      </head>
      <body>{children}</body>
    </html>
  );
}

Keep the lang attribute on <html>, which Privacy Consent reads first to choose the language of the consent banner. Privacy Consent adds its elements at the end of <body>.

Pages Router: add the script to pages/_document.tsx

Paste the script into the <Head> of the custom document, which Next.js renders on the server for every page. Create the file if the project has none.

// pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {
  return (
    <Html lang="en">
      <Head>
        {/* Privacy Consent by TermsFeed (https://www.termsfeed.com) */}
        <script
          type="text/javascript"
          src="https://cdn.termsfeedtag.com/plugins/pc/v1/YOUR_TOKEN/plugin.js"
          async
        />
        {/* End Privacy Consent by TermsFeed (https://www.termsfeed.com) */}
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

Use the <Head> of next/document here. The <Head> of next/head belongs to pages, and a script placed through it follows each page.

Google tags added from their templates in the TermsFeed app need no code in the layout, because Privacy Consent sends the Google Consent Mode v2 defaults for them. Keep your layout free of Consent Mode code in that case, and never paste this block on a site that uses a Google template.

Basic Consent Mode, a Google tag in a custom vendor, needs your own code before the script. The block sets the defaults, restores a saved answer on page load, and sends the update from the callbacks. Any Google tag that stays in the layout goes between the block and the script.

// app/layout.tsx
import type { ReactNode } from 'react';

const consentModeBlock = `
  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',
    'functionality_storage': 'denied',
    'personalization_storage': 'denied',
    'security_storage': 'granted',
    'wait_for_update': 500
  });

  function tfConsentModeSignals(categories) {
    var has = function (id) { return categories.indexOf(id) !== -1; };
    var ads = has('advertising') ? 'granted' : 'denied';
    return {
      'ad_storage': ads,
      'ad_user_data': ads,
      'ad_personalization': ads,
      'analytics_storage': has('analytics') ? 'granted' : 'denied',
      'functionality_storage': has('functionality') ? 'granted' : 'denied',
      'personalization_storage': has('marketing') ? 'granted' : 'denied'
    };
  }

  (function () {
    try {
      var saved = JSON.parse(localStorage.getItem('termsfeed_privacy_consent_state') || '{}');
      var state = saved.consentState;
      if (!state || !state.consentedDate) { return; }
      if (Date.now() / 1000 - state.consentedDate > 365 * 24 * 60 * 60) { return; }
      var accepted = state.categories.filter(function (c) {
        return c.vendors && c.vendors.length
          ? c.vendors.every(function (v) { return v.enabled; })
          : c.enabled === true;
      }).map(function (c) { return c.id; });
      gtag('consent', 'update', tfConsentModeSignals(accepted));
    } catch (e) {}
  })();

  var tfCallbacks = {
    acceptedAll: function (categories) {
      gtag('consent', 'update', tfConsentModeSignals(categories));
    },
    acceptedSome: function (categories) {
      gtag('consent', 'update', tfConsentModeSignals(categories));
    },
    rejectedAll: function () {
      gtag('consent', 'update', tfConsentModeSignals([]));
    }
  };

  if (window.termsfeed_privacy_consent !== undefined)
    window.termsfeed_privacy_consent.v1.callbacks(tfCallbacks);
  else
    window.termsfeed_privacy_consent_callbacks = tfCallbacks;
`;

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <head>
        <script dangerouslySetInnerHTML={{ __html: consentModeBlock }} />
        <script
          type="text/javascript"
          src="https://cdn.termsfeedtag.com/plugins/pc/v1/YOUR_TOKEN/plugin.js"
          async
        />
      </head>
      <body>{children}</body>
    </html>
  );
}

The same 2 elements go into the <Head> of pages/_document.tsx with the Pages Router, in the same order. No answer callback runs on page load for a returning visitor, which is why the block reads the saved answer itself. A vendor category with some vendors off counts as declined. Check the setup against Set Up Google Consent Mode v2.

Open the Preferences Center from a Next.js component

Call window.termsfeed_privacy_consent.v1.openPrivacyPreferences() from a client component to reopen the choices. The method does nothing before the script is ready, and it then prints [ee][478058ef] in the Console tab. Start by declaring the global once, in a file tsconfig.json includes.

// types/termsfeed-privacy-consent.d.ts
export {};

declare global {
  interface Window {
    termsfeed_privacy_consent?: {
      openPrivacyPreferences: () => void;
    };
  }
}

Next, add a client component that calls the method on click, and render it in the footer of the root layout. The optional chaining keeps a very early click from throwing an error.

// app/components/PrivacyPreferencesButton.tsx
'use client';

export function PrivacyPreferencesButton() {
  return (
    <button
      type="button"
      onClick={() => window.termsfeed_privacy_consent?.v1?.openPrivacyPreferences()}
    >
      Privacy Preferences
    </button>
  );
}

A plain element with the class termsfeed-pc1-open-privacy-preferences opens the Preferences Center too, with no JavaScript of your own. It works on elements a route renders later. Compare the options in Let Visitors Reopen Preferences.

Route changes in Next.js do not reload the document

A click on a Next.js <Link> swaps the page content without loading a new document, so Privacy Consent does not start again. The consent banner stays on screen until the visitor answers, and the vendor tags that ran on the first page keep running.

This changes 2 things you handle yourself. An analytics tool counts a page view on a full page load, so a route change needs its own page view event. Privacy Consent finds replaceable tags and vendor div elements once, when it starts. An embed that a later route renders gets its embed placeholder at the next full page load. Handle both with Use TermsFeed Privacy Consent in a Single-Page Application.

Remove tracking components from the Next.js application

The GoogleAnalytics and GoogleTagManager components of @next/third-parties load their scripts on every page, whatever the visitor answers. Remove them, and any tracking script in a layout, once the matching vendor exists. Add the tool with Add Google Analytics 4, or keep a container with one of the approaches in Use Google Tag Manager.

Next.js preview deployments use their own hostnames

Every preview deployment answers on a hostname of its own, so each one asks the visitor again. Privacy Consent stores the answer per origin, and it loads the consent banner only on the domains you add, so a preview hostname you did not add shows none. Test clicks on a listed preview reach the consent log of that consent banner, under the preview hostname in the domain column of the CSV. Decide which hostnames to list and which script address each environment loads with Install TermsFeed Privacy Consent on Netlify and Vercel or Install TermsFeed Privacy Consent on Cloudflare Pages.

Deploy, or run next build and next start, and test the production build in a private window, because it matches what visitors receive. Under Strict, where a new consent banner starts, the question reaches every visitor. Standard in Settings skips a visitor in a US state, so pick a test location from Cookie Banner by Visitor Location.

  1. Open Chrome DevTools, select the Network tab, type termsfeedtag in the filter box, and reload. 7 requests appear with status 200: plugin.js, plugin-2.js, plugin-r2.js, preferences-r2.js, vendors-r2.js, and settings.json twice.
  2. Click a <Link> to another route. No new termsfeedtag request appears, which shows that the script loaded once for the visit.
  3. Select the Console tab. No line after [termsfeed] holds [ee] or [ww], and no hydration error appears.
  4. Filter the Network tab for events.push and click I Agree. A new request with status 201 appears, and your vendors send their first requests.
  5. Click the Privacy Preferences button on another route. The Preferences Center opens.

A saved answer keeps the consent banner hidden on reload, so test I Decline after closing every private window and opening a new one. Complete the checks with Check That Your TermsFeed Privacy Consent Installation Works.

Most Next.js problems come from the script sitting in the wrong file or a tracking component left in the layout.

  • The script sits in app/page.tsx or a nested layout. Routes outside that file do not show the consent banner. Move it to app/layout.tsx.
  • The script uses next/script with lazyOnload. The consent banner appears after the rest of the page. Use a plain <script> element.
  • A @next/third-parties component stays in the layout. Google Analytics runs before any answer. Remove it once the vendor exists.
  • A component reads window during rendering. Server rendering then fails with a ReferenceError. Read window in an event handler or an effect.
  • A nonce-based Content Security Policy covers the page. Next.js adds the nonce to its own scripts, not to a plain element you write. Allow Privacy Consent with the Content Security Policy reference.