Skip to content
HomeScripts/first-party-cookie-keeper

Safari ITP cookie restore

Copies _ga and _fbp into localStorage and writes them back when a Safari visitor returns after the 7-day ITP window has expired the cookies.

GTM Custom HTML Tag (JavaScript)
<script>
(function() {
  var COOKIES = ['_ga', '_fbp', '_gcl_au'];
  var PREFIX = 'gl_first_party_';

  function getCookie(name) {
    var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
    return match ? match[2] : null;
  }

  function setCookie(name, val, days) {
    var d = new Date();
    d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
    document.cookie = name + '=' + val + ';path=/;expires=' + d.toUTCString() + ';SameSite=Lax';
  }

  COOKIES.forEach(function(c) {
    var current = getCookie(c);
    var saved = null;
    try { saved = localStorage.getItem(PREFIX + c); } catch(e) {}

    if (current) {
      try { localStorage.setItem(PREFIX + c, current); } catch(e) {}
    } else if (saved) {
      setCookie(c, saved, 365);
    }
  });
})();
</script>

How it works

  1. When tracking scripts set _ga or _fbp, this GTM tag mirrors them into browser localStorage.
  2. When a Safari visitor returns after 8+ days, the tag reads localStorage and re-sets the first-party cookies before analytics scripts execute.
  3. Keeps attribution intact across sales cycles longer than the 7 days ITP allows.

Step-by-step installation

  1. Create a Custom HTML Tag in GTM.
  2. Set trigger to "Consent Initialization - All Pages" with highest firing priority (e.g., 100).
  3. Publish container.

Frequently asked questions

What does this mean for consent?

The tag only mirrors identifiers your analytics already set, so it inherits whatever consent state let them be set in the first place — fire it behind your consent trigger, not before it. Whether that satisfies a given regulator is a question for your counsel, not for this page.

Need one of these adapted to your account?

We write Google Ads scripts, set up server-side GA4, and build the reporting that answers a specific question.