virling Pricing Self-host Demo Changelog Agencies GitHub Start free trial
blog / 2026-11-24

Persist UTM parameters across pages: three ways with code

By Devendra Variya, co-founder of Virling. Published 2026-11-24.

To persist UTM parameters across pages, read the tags on the landing page and save them somewhere the next page can find them. There are three common ways: a first-party cookie, localStorage, or adding the tags to every internal link. A cookie is the best of the three if your server needs the tags at checkout, because subdomains can share it and your server receives it with each request. The other way is to save no tags at all: keep one visitor ID, record the tagged visit under it, and join the payment to that visit later.

The options at a glance

WayCarries the tags toBreaks when
First-party cookieEvery page and subdomain, and your serverThe cookie expires or is cleared, or cookies are refused
localStoragePages on the same origin, in the browser onlyThe visitor moves to a subdomain, or your server needs the tags
Tags on every linkPages opened from a link the script rewroteThe visitor uses a form, a redirect or a bookmark, or comes back later
Visitor ID onlyNothing, the tags stay with the recorded visitThe ID is lost, or checkout does not carry it

All four start from tags that reached the landing page. If they are already gone when the page loads, fix that first: see UTM parameters lost after redirect. Check the link itself with the UTM checker.

Way 1: a first-party cookie

Put this on every page. It saves the tags as one value, only when the page has some, and keeps both the first and the last set.

var keys = ["utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term"];
var query = new URLSearchParams(location.search);
var tags = new URLSearchParams();
keys.forEach(function (k) {
  if (query.get(k)) tags.set(k, query.get(k).slice(0, 100));
});

function save(name) {
  document.cookie = name + "=" + encodeURIComponent(tags) +
    "; path=/; domain=example.com; max-age=7776000; SameSite=Lax; Secure";
}

if (tags.toString()) {
  save("utm_last");
  if (!/(^|; )utm_first=/.test(document.cookie)) save("utm_first");
}

Replace example.com with your own domain. The domain part shares the cookie with subdomains such as app.example.com; leave it out to keep the cookie on one host. 7776000 seconds is 90 days. Your server then reads the cookie when it creates the checkout. With Express, cookie-parser and Stripe:

const saved = new URLSearchParams(req.cookies.utm_last || "");
const metadata = {};
for (const k of ["utm_source", "utm_medium", "utm_campaign"]) {
  if (saved.get(k)) metadata[k] = saved.get(k);
}
const session = await stripe.checkout.sessions.create({
  mode: "payment",
  line_items: [{ price: "price_...", quantity: 1 }],
  success_url: "https://example.com/thanks",
  metadata,
});

When it breaks:

  • Safari shortens it. Safari caps a cookie set with document.cookie at seven days (source: WebKit). It is one day when a domain Safari classifies as a cross-site tracker sent the visitor and the landing URL has a query string, which a tagged link always has (source: WebKit).
  • Another browser or device. The cookie stays in the browser that saw the tagged link.
  • Another domain. A cookie on example.com is not sent to a checkout hosted elsewhere, so hand the value over before the buyer leaves. See cross-domain checkout attribution.
  • No consent. Storing tags in the browser may need consent where you sell. If you wait for it, save the tags from the page the visitor accepts on, and expect to miss those who left the landing page first.

Way 2: localStorage

The same idea without a cookie. Build tags as in way 1, then:

if (tags.toString()) {
  try {
    localStorage.setItem("utm_last", tags);
    if (!localStorage.getItem("utm_first")) localStorage.setItem("utm_first", tags);
  } catch (e) {}
}

The server never sees localStorage, so add the value to the signup or checkout form before it is sent:

<input type="hidden" name="utm" id="utm">
<script>
try {
  document.getElementById("utm").value = localStorage.getItem("utm_last") || "";
} catch (e) {}
</script>

When it breaks:

  • A different origin. Storage belongs to one scheme, host and port. www.example.com, example.com and app.example.com each have their own.
  • No form to put it in. A checkout your server creates without data from the page never gets the value.
  • It never expires by itself. An old tag can be credited a year later unless you save a date next to it and check it.
  • Safari deletes it. Safari removes script-writable storage after seven days of Safari use without the visitor interacting with the site (source: WebKit).

sessionStorage is shorter still: it belongs to one tab and goes away with it.

Way 3: add the tags to every link

Nothing is stored. A click handler copies the tags from the current address onto each link within the site.

var keys = ["utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term"];
document.addEventListener("click", function (e) {
  var a = e.target.closest("a[href]");
  if (!a || a.origin !== location.origin) return;
  var query = new URLSearchParams(location.search);
  var url = new URL(a.href);
  if (keys.some(function (k) { return url.searchParams.has(k); })) return;
  keys.forEach(function (k) {
    if (query.get(k)) url.searchParams.set(k, query.get(k));
  });
  if (url.href !== a.href) a.href = url.href;
}, true);

When it breaks:

  • Anything that is not a link. Forms, buttons that set location.href, router calls and server redirects skip the handler. One untagged page ends the chain.
  • A return visit. The visitor who types your address next week has no tags in it.
  • Shared and bookmarked pages. A copied address still carries the tags, so a friend who opens it is counted as a click on your campaign.
  • Duplicate addresses. Each page now exists with and without tags. Set a canonical link, and check that your cache does not treat each query string as a separate page.

First or last value?

A visitor can arrive from two campaigns before paying, so decide what happens to the first set of tags. A made-up journey:

Visitutm_firstutm_last
Day 1: link in a newsletter, taggednewsletternewsletter
Day 4: link on a partner site, taggednewsletterpartner
Day 6: Google search, no tags, paysnewsletterpartner
  • First value says which campaign introduced the buyer. Write it once and never replace it.
  • Last value says which campaign came most recently. Replace the whole set at once. If you replace key by key, the source of one link ends up next to the campaign of another.
  • Neither sees the Google search. An untagged visit writes nothing, so the last stored tag is not always the last visit. Search, AI answers and links you did not tag never show up in saved tags.

Saving both keeps the choice open. Whichever you report, use the same one everywhere. First touch vs last touch attribution covers which fits which business.

The other way: keep a visitor ID and join later

Saved tags are a copy of something your analytics already recorded on the landing page. Instead of carrying the copy to checkout, you can carry one random ID and look the visits up afterwards. This is how Virling works:

  1. The script reads utm_source, utm_medium, utm_campaign, utm_content and utm_term from the address on each pageview, and the referrer on the first one of a page load. They are stored with the visit on the server, not in the browser.
  2. It sets one first-party cookie, virling_vid, with a random ID. The cookie is on your registrable domain, so subdomains share it.
  3. Your checkout carries that ID, and the payment arrives with it.
  4. Virling finds the visits of that ID before the payment and credits one of them.

Your server has one value to pass on, whatever the campaign was:

const session = await stripe.checkout.sessions.create({
  client_reference_id: req.cookies.virling_vid,
  mode: "payment",
  line_items: [{ price: "price_...", quantity: 1 }],
  success_url: "https://example.com/thanks",
});

The checkout snippet generator writes this line for Stripe, Paddle, Shopify and the other providers, and the checkout guide explains each one. On Stripe, Polar, Dodo Payments and LemonSqueezy checkout links on your pages the script adds the ID itself.

Two things change. In the journey above, all three visits are on record, including the Google search. And first or last becomes a setting: Virling credits the last visit that was not Direct by default, so the Google search here. Switching the site to first touch recomputes past payments too and credits the newsletter. See model and lookback window.

When it breaks: the ID is also a cookie set by a script, so the Safari caps above apply to it. The script renews it on each page load, but a Safari visitor who stays away longer comes back as a new one, and earlier visits are not joined. A cleared cookie or a second device does the same. In cookieless mode there is no ID to pass, and a payment link opened straight from an email carries none. A payment without an ID still counts toward revenue, as Unattributed, unless it can be matched by email.

Which one to use

  • You want the tags inside your CRM or payment records: the cookie, first and last
  • One host, and a form you control: localStorage with UTM parameters in a hidden form field is enough
  • You cannot store anything, and the visit ends in one sitting: tags on links, knowing that return visits are lost
  • You want revenue by channel, untagged visits included: a visitor ID, joined to the visits later

How to check it works

  1. Open your site in a private window with ?utm_source=test&utm_medium=email on the end
  2. Click through two or three pages, including one subdomain if you have one
  3. In the browser tools, look under Storage or Application for the cookie or the stored value
  4. Open the site again in the same window without tags, and confirm the saved value is still there
  5. Pay in your provider’s test mode and find the tags, or the visitor ID, on the payment

Start free trial See the demo

Frequently asked questions

How do I keep UTM parameters across pages?

Read them from the landing page address and save them in a first-party cookie, or in localStorage if you only need them in the browser on one host. Adding them to every internal link also works within one visit, but breaks on forms, redirects and return visits.

Should I store UTM parameters in a cookie or localStorage?

Use a cookie if your server or a subdomain needs the tags, because the browser sends it with each request and it can cover subdomains. Use localStorage if one host reads them in the browser and adds them to a form. Safari limits how long both last.

How long do saved UTM parameters last?

A cookie lasts as long as its max-age, except in Safari, which caps cookies set by a script at seven days and in some cases one day. localStorage has no expiry of its own, but Safari deletes it after seven days of use without interaction on the site.

Should I save the first or the last UTM parameters?

Save both if you can. The first set says which campaign introduced the buyer and the last set says which came most recently. Replace the last set as a whole, so tags from two campaigns never mix.

Should I add UTM parameters to internal links?

Not by hand with new values, because that overwrites the source the visitor arrived with. Copying the arriving tags onto internal links keeps the source, but a copied or bookmarked address then counts as another campaign click.

Do I need to pass UTM parameters to Stripe?

Only if you want them on the payment itself, in metadata. To see revenue by source, pass a visitor ID such as client_reference_id instead, and join the payment to the visits that ID made.

Join each payment to the visit that brought it

Virling is open source under AGPL. Self-host it free, or use the hosted version with a 14-day free trial. It connects to Stripe, Paddle, Shopify, WooCommerce, Polar, LemonSqueezy, Dodo, Creem and RevenueCat.

Start free trial See the demo