Multi-Domain Cookie & First-Party Context Preserver Script
Lightweight JavaScript snippet to preserve client identifiers across subdomains and mitigate Safari ITP cookie expiration.
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.
Multi-Domain Cookie & First-Party Context Preserver Script Configurator
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
| Parameter | Value | Context & Provenance |
|---|---|---|
| Target Domain Ecosystem | 3 Domains Domains | gordongeraghty.com, shop.gordongeraghty.com, checkout.gordongeraghty.com |
| Preserved Cookie Identifiers | _ga, _fbp, gg_uid Cookie Keys | Google Analytics Client ID, Meta Browser ID, Custom CRM ID |
| Target Cookie Lifetime | 730 Days Lifetime | 2-year persistence target for longitudinal customer cohort tracking |
| LocalStorage Backup | Enabled (true) Storage Layer | Secondary 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 days3 Computed Output Metrics
| Computed Metric | Result | Interpretation & Threshold |
|---|---|---|
| Configured Cookie Lifetime | 730 Days (2 Years) Max-Age | Extends tracking persistence far beyond Safari's default 7-day ITP deletion cap |
| Cross-Subdomain Coverage | 100% Shared Scope | Root domain scoping (.gordongeraghty.com) eliminates cross-domain session breakage |
| Client-Side Footprint | < 1.2 KB Script Weight | Ultra-lightweight vanilla JS execution with zero external library dependencies |
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 ShieldGenerate 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
(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
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.
(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']);(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);
})();Cross-Domain Persistence Verification
Test cookie survival across subdomains and verify that Safari ITP does not truncate client IDs after 24 hours.
Inspect Application > Cookies in Chrome DevTools to ensure Domain is set with leading dot for subdomain sharing.
Delete _ga cookie in DevTools, refresh the page, and verify cookie is instantly restored from localStorage backup.
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 LicenceThis resource is free, open and un-gated under the MIT Open Source Licence. You are encouraged to use, integrate and cite it with attribution:
@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}
}
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.