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

SvelteKit Stripe UTM tracking: tie each payment to its source

By Devendra Variya, co-founder of Virling. Published 2026-11-22, updated 2026-11-27.

SvelteKit hands every form action and +server.ts handler a cookies object, so the visitor ID is one cookies.get("virling_vid") away from the code that creates your Stripe Checkout Session. Send it as client_reference_id, then redirect(303) to the session URL. The tag goes in src/app.html, and the Stripe key is declared in src/env.ts on SvelteKit 3.

Checkout itself happens on Stripe's domain, where nothing knows which campaign sent the buyer; the ID on the session is what ties the payment back to the visit and its UTM tags. The provider-neutral version of this is link checkout to visits. On LemonSqueezy, see SvelteKit LemonSqueezy UTM tracking.

Step 1: the tag in src/app.html

Put it before %sveltekit.head%. Use your own server's address in src if you self-host.

<!-- src/app.html -->
<head>
  <meta charset="utf-8" />
  <script defer src="https://app.virling.com/v.js"
    data-site="yourdomain.com"></script>
  %sveltekit.head%
</head>

Because app.html is outside Svelte, the script loads on every page, including pages with export const csr = false. On those, each link is a full page load and a pageview of its own; on the rest, the SvelteKit router's navigations are counted without extra code.

Step 2: declare the key with $app/env/private

SvelteKit 3 reads environment variables declared in src/env.ts and serves private ones from $app/env/private, which only server code may import:

// src/env.ts
import { defineEnvVars } from "@sveltejs/kit/env";

export const variables = defineEnvVars({
  STRIPE_SECRET_KEY: {},
});

Still on SvelteKit 2? Skip that file and import STRIPE_SECRET_KEY from $env/static/private. SvelteKit 3 still accepts that import but warns that it is deprecated.

Step 3: a form action that redirects to Checkout

The action gets cookies from its request event. In SvelteKit 3, redirect() refuses another origin unless the third argument allows it, so pass { external: true } (SvelteKit 2 has no such argument):

// src/routes/pricing/+page.server.ts
import { redirect } from "@sveltejs/kit";
import Stripe from "stripe";
import { STRIPE_SECRET_KEY } from "$app/env/private";
import type { Actions } from "./$types";

const stripe = new Stripe(STRIPE_SECRET_KEY);

export const actions = {
  checkout: async ({ cookies }) => {
    const session = await stripe.checkout.sessions.create({
      client_reference_id: cookies.get("virling_vid"),
      line_items: [{ price: "price_...", quantity: 1 }],
      mode: "subscription",
      success_url: "https://yourdomain.com/thanks",
    });
    redirect(303, session.url!, { external: true });
  },
} satisfies Actions;

With use:enhance the form posts through fetch, and on a redirect to another origin SvelteKit falls back to a full page navigation, so the buyer lands on checkout.stripe.com. Without JavaScript the browser follows the 303 by itself:

<!-- src/routes/pricing/+page.svelte -->
<script lang="ts">
  import { enhance } from "$app/forms";
</script>

<form method="POST" action="?/checkout" use:enhance>
  <button type="submit">Buy</button>
</form>

Or a shared +server.ts endpoint

When more than one page sells, a POST handler in +server.ts keeps checkout in one place. This one writes the ID to metadata.virling_vid, the field to use when client_reference_id already carries your own user or cart ID:

// src/routes/api/checkout/+server.ts
import { redirect } from "@sveltejs/kit";
import Stripe from "stripe";
import { STRIPE_SECRET_KEY } from "$app/env/private";
import type { RequestHandler } from "./$types";

const stripe = new Stripe(STRIPE_SECRET_KEY);

export const POST: RequestHandler = async ({ cookies }) => {
  const vid = cookies.get("virling_vid");
  const session = await stripe.checkout.sessions.create({
    // client_reference_id stays free for your own ID
    metadata: vid ? { virling_vid: vid } : {},
    line_items: [{ price: "price_...", quantity: 1 }],
    mode: "subscription",
    success_url: "https://yourdomain.com/thanks",
  });
  redirect(303, session.url!, { external: true });
};

Any page, prerendered ones included, can post to it with <form method="POST" action="/api/checkout">. The order in which Virling checks these fields is in the Stripe docs; for Payment Links and how long a metadata value may be, read the Stripe Checkout UTM guide. What Virling shows for Stripe revenue per channel is on its integration page.

Start free trial

Page options: prerender, ssr and csr

SvelteKit refuses to prerender a page that has form actions, and the build stops with prerender_actions. If your root +layout.ts sets prerender = true, either export prerender = false from the pricing page or keep the page prerendered and post to the +server.ts endpoint. Avoid reading the cookie in load: on a prerendered page it ran at build time, for no visitor. csr = false on the pricing page is fine, since the plain form still posts to the action (see reading the visitor cookie in server code).

Adapters

  • adapter-node checks that form posts come from the app's own origin. Behind a reverse proxy, set ORIGIN, or PROTOCOL_HEADER and HOST_HEADER, or the Buy button returns 403.
  • adapter-vercel can cache a route with export const config = { isr: { expiration: 60 } }. Leave that off the route that creates the session.
  • adapter-cloudflare runs actions and endpoints in a Worker on each request; set STRIPE_SECRET_KEY as a secret of the Worker.
  • adapter-static has no server at run time, so there is no action to read the cookie. Use Stripe Payment Links, which the script fills in the browser.

Test it

Follow the test payment in check that it works, with these SvelteKit specifics:

  1. Visits to localhost are not kept. Add 127.0.0.1 dev.yourdomain.com to your hosts file and run npm run dev -- --host dev.yourdomain.com; the flag also adds the name to the hosts Vite answers. Open http://dev.yourdomain.com:5173/?utm_source=test&utm_medium=email.
  2. Keep a sk_test_ key in STRIPE_SECRET_KEY in .env.
  3. npm run dev never prerenders. Run npm run build and npm run preview once, so a prerender_actions error or a prerendered page behaves as it will in production.

To check what the action sent, log session.client_reference_id and session.metadata after the session is created. The Nuxt version of this guide is Nuxt Stripe UTM tracking; there are also guides for Next.js and Astro, and for SvelteKit with Polar.

Common mistakes in SvelteKit

An Unattributed payment with no Visitor under Details was created without the ID.

What you seeCauseFix
The Buy button fails with redirect_external_not_allowedSvelteKit 3 lets redirect() leave the site only when told toPass { external: true } as the third argument
The build fails with prerender_actionsA page with form actions is prerendered, often through prerender = true in the root layoutExport prerender = false on that page, or post to a +server.ts endpoint
No visitor ID, or the same one on many paymentsThe cookie is read in the load of a prerendered or cached pageRead it in the action or endpoint that creates the session
403, Cross-site POST form submissions are forbiddenThe form is on another origin than the app, or adapter-node behind a proxy does not know its public originKeep the form and the endpoint on one domain, and set ORIGIN
Blocked request. This host is not allowed on the dev serverVite does not answer to the test hostStart it with --host dev.yourdomain.com, or add the host to server.allowedHosts
Sessions in Stripe that nobody asked forThe session is created in a load function, which can also run when a visitor hovers over a linkCreate it in an action or a POST handler
$env/static/private is deprecated, in the consoleThe key is imported the SvelteKit 2 wayDeclare it in src/env.ts and import from $app/env/private

Anything not specific to SvelteKit, from blocked scripts to cookieless mode, is in Unattributed revenue.

Frequently asked questions

How do I pass UTM parameters to a Stripe Checkout Session in SvelteKit?

Read the visitor ID from the virling_vid cookie with cookies.get in a form action or a +server.ts endpoint, and pass it as client_reference_id when you create the session. The Virling script records the UTM tags of every visit against that ID, so the payment is joined to all of them.

How do I read the virling_vid cookie in SvelteKit?

Form actions, +server.ts handlers and server load functions all receive a cookies object on the request event, so cookies.get("virling_vid") returns the ID. It is a first-party cookie on your domain, so the browser sends it with every request to your app.

Is client-side navigation in SvelteKit counted?

Yes. With the script tag in src/app.html it loads once for the whole app, and page changes made by the SvelteKit router are counted on their own.

Can a site built with adapter-static use Stripe Checkout?

Not through a form action, because adapter-static leaves no server to run one. Use Stripe Payment Links instead: the script adds client_reference_id to buy.stripe.com links in the browser.

Does use:enhance work when the action redirects to Stripe?

Yes. When the action calls redirect(303, session.url, { external: true }), use:enhance sees a redirect to another origin and does a full page navigation to Stripe Checkout. Without JavaScript the browser follows the 303 itself.

See which campaigns bring Stripe revenue

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