TermsFeed Privacy Consent (CMP) starts once, when the document loads, and keeps running unchanged while your single-page application swaps routes. A route change in React, Vue, Angular, SvelteKit, or Next.js does not reload the document, so the script neither restarts nor looks at the new route. Your code handles what changes per route: links to the Preferences Center, embeds, and page views.

The setup takes 5 steps and about 30 minutes. You need edit access to the HTML shell of your application and, for Step 4, a Google Tag Manager container.

Step 1: Load the script once from the application shell

Put the Privacy Consent snippet in the HTML shell your framework serves on every route, never in a component. A component mounted after the script has started adds a request and changes nothing. 2 copies on one page print [ee][205bde55] or [ee][1040992c] in the Console, and only the first copy runs.

The shell goes in the <head> of a Vite index.html, used by React and Vue. Its inline script holds the reader functions, the only set of callbacks on the page, and the page view function the next steps use. Replace YOUR_TOKEN with the token in the snippet the TermsFeed app gives you.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My App</title>
    <script>
      function tfStoredState() {
        try {
          var state = JSON.parse(window.localStorage.getItem('termsfeed_privacy_consent_state') || '{}').consentState;
          if (!state || !state.consentedDate) return null;
          var expires = new Date(state.consentedDate * 1000);
          expires.setDate(expires.getDate() + 365);
          return expires.getTime() < Date.now() ? null : state;
        } catch (error) {
          return null;
        }
      }

      function tfConsent() {
        var ids = ['functionality', 'analytics', 'advertising', 'marketing'];
        var state = tfStoredState();
        var result = { chosen: state !== null, essential: 'granted' };
        ids.forEach(function (id) { result[id] = state ? 'denied' : 'not_chosen'; });
        if (!state) return result;
        (state.categories || []).forEach(function (category) {
          if (ids.indexOf(category.id) === -1) return;
          var vendors = category.vendors || [];
          var accepted = category.enabled === true || (vendors.length > 0 && vendors.every(function (vendor) {
            return vendor.enabled === true;
          }));
          result[category.id] = accepted ? 'granted' : 'denied';
        });
        return result;
      }

      function tfVendorConsent(vendorId) {
        var state = tfStoredState();
        var answer = 'not_chosen';
        ((state && state.categories) || []).forEach(function (category) {
          (category.vendors || []).forEach(function (vendor) {
            if (vendor.id !== vendorId) return;
            answer = vendor.enabled === true || category.enabled === true ? 'granted' : 'denied';
          });
        });
        return answer;
      }

      function tfAnnounceConsent() {
        window.dispatchEvent(new CustomEvent('tf-consent-change'));
      }

      var callbacks = {
        acceptedAll: tfAnnounceConsent,
        acceptedSome: tfAnnounceConsent,
        rejectedAll: tfAnnounceConsent
      };

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

      function tfPushPageview() {
        var consent = tfConsent();
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
          event: 'spa_pageview',
          page_path: window.location.pathname + window.location.search,
          page_title: document.title,
          page_location: window.location.href,
          tf_consent_analytics: consent.analytics,
          tf_consent_advertising: consent.advertising,
          tf_consent_marketing: consent.marketing
        });
      }
    </script>
    <!-- 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></script>
    <!-- End Privacy Consent by TermsFeed (https://www.termsfeed.com) -->
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

The shell file differs by framework. Copy the placement for Next.js from install on Next.js, and for React, Vue, Angular, and SvelteKit from install on React, Vue, or Angular. Privacy Consent reads none of these helpers: they use its callbacks and its storage key, and everything else in them is yours.

Step 2: Open the Preferences Center from a component

Call window.termsfeed_privacy_consent.v1.openPrivacyPreferences() from the click handler of your own button. The optional chaining in the component skips the call while the script is still loading. A call made before the script is ready does nothing and prints [ee][478058ef], and Privacy Consent does not queue it.

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

An element with the class termsfeed-pc1-open-privacy-preferences opens the Preferences Center with no handler. Privacy Consent listens for those clicks on document, so an element a route renders later works too. A link with an empty href or # does not jump to the top of the page, which keeps a hash router on its route. Prefer the class to the ID open_privacy_preferences_element, because a component rendered twice on one page duplicates an ID.

TypeScript projects need a declaration for the globals. Add the next file to your project, for example as src/global.d.ts.

export {};

declare global {
  interface Window {
    termsfeed_privacy_consent?: {
      callbacks: (callbacks: {
        acceptedAll?: (categories: string[]) => void;
        acceptedSome?: (categories: string[]) => void;
        rejectedAll?: () => void;
        initialized?: () => void;
      }) => void;
      openPrivacyPreferences: () => void;
    };
    tfConsent: () => { chosen: boolean; [category: string]: string | boolean };
    tfVendorConsent: (vendorId: string) => string;
    tfPushPageview: () => void;
  }
}

Step 3: Handle embeds that mount after the first paint

Render a late embed from your own component, because Privacy Consent looks for embeds once, when it starts. A replaceable tag a route renders later never gets a placeholder and never loads. A vendor div added later does not get an embed placeholder, and it receives the HTML vendor tag at the next answer in that page view.

The component shows a placeholder until the visitor accepts the vendor, then renders the player. It checks again on every tf-consent-change event the shell dispatches. Pass the vendor ID from the address of the "Edit vendor" page in the TermsFeed app.

import { useEffect, useState } from 'react';

export default function ConsentVideo({ vendorId, videoId, title }) {
  const [allowed, setAllowed] = useState(false);

  useEffect(() => {
    const check = () => setAllowed(window.tfVendorConsent(vendorId) === 'granted');
    check();
    window.addEventListener('tf-consent-change', check);
    return () => window.removeEventListener('tf-consent-change', check);
  }, [vendorId]);

  if (!allowed) {
    return (
      <div className="video-consent-placeholder" style={{ aspectRatio: '16 / 9' }}>
        <p>This video loads from YouTube once you accept it in Privacy Preferences.</p>
        <button
          type="button"
          onClick={() => window.termsfeed_privacy_consent?.v1?.openPrivacyPreferences()}
        >
          Privacy Preferences
        </button>
      </div>
    );
  }

  return (
    <iframe
      width="560"
      height="315"
      src={`https://www.youtube-nocookie.com/embed/${videoId}`}
      title={title}
      allowFullScreen
    />
  );
}

Privacy Consent does not show an embed placeholder for this video or remove it after a withdrawal, so the component decides alone. It reads recorded answers only, which means a first visit under the opt-out model shows the placeholder until the visitor saves an answer. Check that limit in what the reader does not see.

Push a page view event with the consent state after every route change, and trigger your Google Tag Manager page view tags on it. A vendor tag runs once per document, so a vendor tag that counts a page view counts the first route only. The shell function tfPushPageview() pushes spa_pageview with granted, denied, or not_chosen for 3 vendor categories.

In React Router, render the next component once inside your router. The effect runs on the first render and on every change of path or query string.

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

export default function ConsentPageviews() {
  const location = useLocation();

  useEffect(() => {
    window.tfPushPageview();
  }, [location.pathname, location.search]);

  return null;
}

In Vue Router, register the push in src/main.js. The hook runs after the initial navigation and after every later one.

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

router.afterEach(() => {
  window.tfPushPageview();
});

createApp(App).use(router).mount('#app');

In Google Tag Manager, create a Custom Event trigger with the event name spa_pageview and the condition tf_consent_analytics equals granted. Attach it to your analytics page view tag in place of the All Pages trigger, so the first page does not count twice. The first push of a page load reads the stored record before the script has applied it, so an override applied on that load reaches the next route. Fire a tag at the moment a visitor accepts with fire tags without a page reload.

The public API has no method that restarts Privacy Consent, and a route change does not need one. The consent banner, the Preferences Center, the floating buttons, and the stored answer stay valid for the whole document. The initialized callback runs once per document too, not once per route.

Routers that replace the whole <body> element on navigation are the exception. Astro View Transitions and Turbo Drive swap <body>, which removes the consent banner, the Preferences Center, and the floating buttons that Privacy Consent appended there. Privacy Consent does not add them back, so switch body replacement off on sites that use it.

A consent banner that returns on every route means the document itself reloads. A link with a full href outside the router, or a server redirect, reloads the page, and each reload starts Privacy Consent again.

Confirm that the script loads once per session and that every route pushes its consent state. Open your application in a private window with Chrome DevTools open.

  1. Select the Network tab, tick Preserve log, and type plugin-2.js in the filter box.
  2. Move between 5 routes and confirm that plugin-2.js appears once, which shows that no route reloads the document.
  3. Click the Privacy Preferences button on the last route, confirm that the Preferences Center opens, switch every vendor category on, and click Save Preferences.
  4. Move to 2 more routes and select the Console tab.
  5. Type dataLayer.filter(function (e) { return e.event === 'spa_pageview'; }) and confirm 1 push per route, with granted only after the save.
  6. Open a route with a ConsentVideo component and confirm that the player loads and the consent banner stays hidden.