---
title: "Multi-Domain Cookie & First-Party Context Preserver Script"
description: "Lightweight JavaScript snippet to preserve client identifiers across subdomains and mitigate Safari ITP cookie expiration."
canonical: "https://gordongeraghty.com/resources/multi-domain-cookie-preserver"
type: "resource"
date: "2026-08-22T08:00:00+10:00"
updated: "2026-09-24T15:40:35+10:00"
---



# Multi-Domain Cookie & First-Party Context Preserver Script

**Gordon Geraghty:** Multi-Domain Cookie & First-Party Context Preserver Script. Lightweight JavaScript snippet to preserve client identifiers across subdomains and mitigate Safari ITP cookie expiration.

**Category: GTM & Analytics · Type: script · Level: intermediate · Licence: MIT**

## Mitigating Safari ITP Tracking Loss

Safari Intelligent Tracking Prevention caps client-set cookies to 7 days or 24 hours when link decoration is detected. This script pairs root domain cookies with persistent localStorage keys so users returning after 7 days retain their original attribution parameters.

### Subdomain Cookie Writer & Backup Script

```javascript
(function() {
  function getRootDomain() {
    var parts = window.location.hostname.split('.');
    if (parts.length <= 2) return window.location.hostname;
    return '.' + parts.slice(-2).join('.');
  }

  function setRootCookie(name, value, days) {
    var expires = '';
    if (days) {
      var d = new Date();
      d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = '; expires=' + d.toUTCString();
    }
    var domain = getRootDomain();
    document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/; domain=' + domain + '; SameSite=Lax; Secure';
  }

  function syncContext(key) {
    var match = document.cookie.match(new RegExp('(^| )' + key + '=([^;]+)'));
    var cookieVal = match ? decodeURIComponent(match[2]) : null;
    var storageVal = null;
    try { storageVal = localStorage.getItem('gg_' + key); } catch(e) {}

    if (cookieVal && !storageVal) {
      try { localStorage.setItem('gg_' + key, cookieVal); } catch(e) {}
    } else if (!cookieVal && storageVal) {
      setRootCookie(key, storageVal, 90);
    }
  }

  // Preserve critical advertising and analytics identifiers
  ['_fbp', '_fbc', '_ga', 'user_id'].forEach(syncContext);
})();
```

### Changelog
- **1.0.0:** Initial release of multi-domain cookie preserver with localStorage backup.

**Tags:** Server-Side GTM, Meta CAPI

[Canonical URL](https://gordongeraghty.com/resources/multi-domain-cookie-preserver)
