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 & Export

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.

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.

Implementation Code & Script

Subdomain Cookie Writer & Backup Scriptcookie-context-preserver.jsjavascript

Writes first-party cookies to the root domain and syncs values with localStorage to prevent tracking resets.

(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 QA & Verification Guide

Cross-Domain Persistence Verification

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

Pre-Production Verification Checklist

✓
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.

Terminal Diagnostic & Debug Commands

Inspect Preserver Storage Entriesjavascript

Returns all tracking context keys currently preserved in localStorage.

Object.keys(localStorage).filter(k => k.startsWith("__fp_")).reduce((acc, k) => ({...acc, [k]: localStorage.getItem(k)}), {})

Failure Remediation & Troubleshooting

Issue: Cross-Domain Linker Creates New Session in GA4

Cause: Target domain was not declared in GA4 "Configure your domains" cross-domain tracking settings.

Fix: Add all brand domains and subdomains in GA4 Web Stream > Configure tag settings > Configure your domains.

Issue: Safari Truncating Cookies After 24 Hours

Cause: Cookies set via document.cookie JavaScript API are capped by Safari ITP when arrival carries click IDs.

Fix: Deploy sGTM HTTP-only cookie headers via Cloud Run custom domain to achieve 2-year persistence.

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/gtm-analytics/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/gtm-analytics/multi-domain-cookie-preserver},
  note = {Head of Performance Media, Empire Amplify}
}

Changelog & Version History

  • v1.0.0Initial release of multi-domain cookie preserver with localStorage backup.