Skip to content

Multi-Domain Cookie & First-Party Context Preserver Script

Lightweight JavaScript snippet to preserve client identifiers across subdomains and mitigate Safari ITP cookie expiration.

By Gordon Geraghty·MIT Licence·Updated: 24 September 2026·INTERMEDIATE
01 Prerequisites & Architecture
Stage 01 Architecture

Multi-Domain Cookie & Context Preserver Architecture

Mitigates Safari ITP 24-hour and 7-day cookie expiration caps by bridging first-party tracking identifiers across parent domains, subdomains, and checkout payment portals via localStorage and sGTM header restoration.

Difficulty:Intermediate Engineering
Time:20–30 mins
Required Access & Permissions:
GTM Container Publishing RightsOrigin Domain DNS ControlCheckout Portal Script Access
STEP 01Origin Domain (.example.com)
Primary Domain HitUser visits main marketing site
STEP 02gtag Linker Module
Cross-Domain LinkerAppends decorated query string (_gl=...)
STEP 03Client Storage Engine
Context Storage BackupMirrors _ga & _fbp to localStorage & HTTP cookie
STEP 04Checkout Domain (.shop.example.com)
Secondary CheckoutRestores persistent ID on subdomain/portal
02 Interactive Configurator

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

Worked Example · Deterministic Calculation

Safari ITP First-Party Cookie Preserver — Cross-Domain Sync & 730-Day Storage

First-party cookie preservation and localStorage fallback synchronization across multi-domain checkout architectures.

1 Input Parameters & Assumptions

ParameterValueContext & Provenance
Target Domain Ecosystem3 Domains Domainsgordongeraghty.com, shop.gordongeraghty.com, checkout.gordongeraghty.com
Preserved Cookie Identifiers_ga, _fbp, gg_uid Cookie KeysGoogle Analytics Client ID, Meta Browser ID, Custom CRM ID
Target Cookie Lifetime730 Days Lifetime2-year persistence target for longitudinal customer cohort tracking
LocalStorage BackupEnabled (true) Storage LayerSecondary browser storage mirror immune to standard document.cookie deletion

2 Explicit Mathematical Formula

ITP 7-Day Cap Mitigation: Reads document.cookie -> writes localStorage backup (__bk__ga, __bk__fbp)
Root Domain Scope: .gordongeraghty.com (shares cookie context across gordongeraghty.com, shop, checkout)
Cookie Lifetime: Max-Age = 63,072,000 seconds (730 Days / 2 Years)
Security Headers: SameSite=Lax, Secure=true
Cross-Domain Sync: Restores client identifiers upon subdomain transitions even if Safari ITP cleared cookies after 7 days

3 Computed Output Metrics

Configured Cookie Lifetime730 Days (2 Years)Max-AgeExtends tracking persistence far beyond Safari's default 7-day ITP deletion cap
Cross-Subdomain Coverage100% SharedScopeRoot domain scoping (.gordongeraghty.com) eliminates cross-domain session breakage
Computed MetricResultInterpretation & Threshold
Configured Cookie Lifetime730 Days (2 Years) Max-AgeExtends tracking persistence far beyond Safari's default 7-day ITP deletion cap
Cross-Subdomain Coverage100% Shared ScopeRoot domain scoping (.gordongeraghty.com) eliminates cross-domain session breakage
Client-Side Footprint< 1.2 KB Script WeightUltra-lightweight vanilla JS execution with zero external library dependencies

Strategic Takeaway & Operational Guidelines

Apple Safari ITP deletes client-set cookies after 7 days of inactivity, fragmenting returning customers into new users. This preserver script maintains persistent identity across subdomains and checkout flows.

INSTRUMENT BOUNDARIES

Multi-Domain Cookie & First-Party Context Preserver Script — Scope & Limitations

Explicit operational boundaries and constraints defining target use cases and out-of-scope scenarios.

Built For (Target Use Cases)

  • Generating a vanilla JavaScript snippet that mirrors first-party cookies into localStorage across subdomains.
  • Configuring which cookie names, domains, and expiry (up to 730 days) the script preserves.
  • Mitigating Safari ITP's 7-day deletion of client-set cookies by backing them up locally.

Not Built For (Limitations & Out-of-Scope)

  • Restoring cookies that Safari ITP has already deleted before the backup script last ran.
  • Setting server-side or HttpOnly cookies; the generated snippet only reads and writes client-side storage.
  • Syncing identifiers to a backend or CDP; output stays in the visitor's own browser.

Operational Assumptions & Defaults

  • Accepts any Cookie Lifetime Days value typed in; the field is not clamped to its 1-730 display range.
  • Assumes the root domain can be derived by taking the last two labels of the hostname.
  • Backup applies only to cookie names explicitly listed in the Preserved Cookie Identifiers field.

Multi-Domain Cookie & First-Party Context Preserver

Cross-Domain & ITP Shield

Generate resilient first-party cookie synchronization and LocalStorage recovery scripts to safeguard client identifiers (_ga, _fbp, user_id) across subdomains and Safari ITP caps.

Architecture Parameters

gordongeraghty.comshop.gordongeraghty.comcheckout.gordongeraghty.com
_ga_fbpgg_uid


(function(window, document) {
  var ALLOWED_DOMAINS = ["gordongeraghty.com","shop.gordongeraghty.com","checkout.gordongeraghty.com"];
  var COOKIE_NAMES = ["_ga","_fbp","gg_uid"];
  var EXPIRY_DAYS = 730;

  function getRootDomain() {
    var parts = window.location.hostname.split('.');
    return parts.slice(-2).join('.');
  }

  function preserve() {
    if (COOKIE_NAMES.length === 0) return;
    var regex = new RegExp('(^|;\\s*)(' + COOKIE_NAMES.join('|') + ')=([^;]+)', 'g');
    var match;
    while ((match = regex.exec(document.cookie)) !== null) {
      if (true) {
        try { localStorage.setItem('__bk_' + match[2], match[3]); } catch(e) {}
      }
    }
  }
  preserve();
})(window, document);

ITP-Resilient First-Party Preserver

Export & Deployment Actions1-click clipboard transfer, shareable URL hash, and local file downloads.

Built by Gordon Geraghty, Head of Performance MediaClient-Side Cookie Engine
03 Deployment & Production Recipes

Deploy Cookie & Identity Preserver Tag

Deploy the lightweight preserver tag on all brand domains to automatically back up tracking cookies to localStorage and restore them on session initialization.

Export & Deployment Actions1-click clipboard transfer, shareable URL hash, and local file downloads.

cookie-preserver.jsjavascript
(function initCookiePreserver(domains, cookieNames) {
  const isAllowedDomain = domains.some(d => window.location.hostname.endsWith(d));
  if (!isAllowedDomain) return;

  // 1. Restore from localStorage if cookie missing
  cookieNames.forEach(name => {
    const cookieVal = (document.cookie.match(new RegExp('(^|; )' + name + '=([^;]*)')) || [])[2];
    const storedVal = localStorage.getItem('__fp_' + name);
    if (!cookieVal && storedVal) {
      document.cookie = name + '=' + storedVal + '; path=/; domain=.' + window.location.hostname.split('.').slice(-2).join('.') + '; max-age=63072000; SameSite=Lax';
    } else if (cookieVal) {
      localStorage.setItem('__fp_' + name, cookieVal);
    }
  });
})(['example.com', 'shop.example.com'], ['_ga', '_fbp', '__uid']);
cookie-context-preserver.jsjavascript
(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);
})();
04 Verification Checklist

Cross-Domain Persistence Verification

Test cookie survival across subdomains and verify that Safari ITP does not truncate client IDs after 24 hours.

Verify Cookie Domain Scope (.domain.com)

Inspect Application > Cookies in Chrome DevTools to ensure Domain is set with leading dot for subdomain sharing.

Test LocalStorage Backup Restoration

Delete _ga cookie in DevTools, refresh the page, and verify cookie is instantly restored from localStorage backup.

Verify Linker Query Decoration (?_gl=...)

Click an outbound link to secondary domain and verify _gl query parameter is appended and parsed.

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.

How to cite and attribute this tool

MIT Licence

This resource is free, open and un-gated under the MIT Open Source Licence. You are encouraged to use, integrate and cite it with attribution:

Geraghty, G. (2026). Multi-Domain Cookie & First-Party Context Preserver Script. Gordon Geraghty Resources Hub. https://gordongeraghty.com/resources/multi-domain-cookie-preserver
BibTeX Format
@misc{geraghty_multi_domain_cookie_preserver,
  author = {Geraghty, Gordon},
  title = {Multi-Domain Cookie & First-Party Context Preserver Script},
  year = {2026},
  url = {https://gordongeraghty.com/resources/multi-domain-cookie-preserver},
  note = {Head of Performance Media, Empire Amplify}
}