Astro Stripe UTM tracking: tie each payment to its source
By Devendra Variya, co-founder of Virling. Published 2026-11-22, updated 2026-11-27.
Astro builds a static site unless a route asks for a server, and that choice decides how the visitor ID reaches Stripe. With an adapter installed, an API endpoint marked export const prerender = false reads virling_vid from cookies and passes it to the Checkout Session as client_reference_id. With no adapter at all, Stripe Payment Links do the same job from the browser, and the site stays fully static.
Stripe Checkout runs on checkout.stripe.com, which never sees the campaign that brought the buyer, so the ID on the session is what Virling joins back to the visit and its UTM tags. The provider-neutral version of this is link checkout to visits. On LemonSqueezy, see Astro LemonSqueezy UTM tracking.
Step 1: an is:inline tag in the layout
Astro processes and bundles the <script> tags it finds in components. is:inline tells it to print this one exactly as written, which matters because the script reads data-site from its own tag. Put it in the <head> of the layout every page uses, and point src at your own server if you self-host:
---
// src/layouts/Layout.astro
---
<html lang="en">
<head>
<meta charset="utf-8" />
<script is:inline defer src="https://app.virling.com/v.js"
data-site="yourdomain.com"></script>
</head>
<body>
<slot />
</body>
</html>Without <ClientRouter /> every link is a full page load and a pageview of its own. With it, view transitions change the route through pushState, and the script counts those too, so it belongs in the layout once and not in individual pages or islands.
Static output, server output and adapters
In the default static output, every page and endpoint is rendered once, at build time. There is no request then, so Astro.cookies is empty and a POST handler is never deployed. To run code per request, add an adapter, such as npx astro add node (Vercel, Netlify and Cloudflare have their own), and choose one of two setups:
- Keep
output: "static"and putexport const prerender = falsein the one endpoint that creates the session. Every other page stays prerendered and can be served from a CDN. - Set
output: "server"and every route renders on request, unless it exportsprerender = true. This suits sites that are mostly dynamic already.
Either way, declare the Stripe key with astro:env, which reads a secret when the server runs instead of when the site is built, and keeps it out of client code:
// astro.config.mjs
import { defineConfig, envField } from "astro/config";
import node from "@astrojs/node";
export default defineConfig({
adapter: node({ mode: "standalone" }),
env: {
schema: {
STRIPE_SECRET_KEY: envField.string({ context: "server", access: "secret" }),
},
},
});Step 2: an on-demand endpoint that redirects to Checkout
An endpoint receives the same cookie object that pages see as Astro.cookies, as cookies on its context. cookies.get("virling_vid")?.value is the visitor ID, or undefined when the script did not run:
// src/pages/api/checkout.ts
import type { APIRoute } from "astro";
import { STRIPE_SECRET_KEY } from "astro:env/server";
import Stripe from "stripe";
export const prerender = false;
const stripe = new Stripe(STRIPE_SECRET_KEY);
export const POST: APIRoute = async ({ cookies, redirect }) => {
const session = await stripe.checkout.sessions.create({
client_reference_id: cookies.get("virling_vid")?.value,
line_items: [{ price: "price_...", quantity: 1 }],
mode: "subscription",
success_url: "https://yourdomain.com/thanks",
});
return redirect(session.url!, 303);
};The pricing page itself can stay prerendered. A plain HTML form posts to the endpoint, the browser attaches the cookie, and the 303 takes the buyer to Stripe:
<form method="POST" action="/api/checkout"> <button type="submit">Buy</button> </form>
Astro checks the Origin of form posts to on-demand routes (security.checkOrigin, on by default), so keep the form and the endpoint on the same domain.
Or a page that handles its own POST
An on-demand .astro page can create the session in its frontmatter with Astro.cookies and Astro.redirect. This version writes the ID to metadata.virling_vid, for when client_reference_id already carries your own user or cart ID:
---
// src/pages/pricing.astro
import { STRIPE_SECRET_KEY } from "astro:env/server";
import Stripe from "stripe";
import Layout from "../layouts/Layout.astro";
export const prerender = false;
if (Astro.request.method === "POST") {
const stripe = new Stripe(STRIPE_SECRET_KEY);
const vid = Astro.cookies.get("virling_vid")?.value;
const session = await stripe.checkout.sessions.create({
metadata: vid ? { virling_vid: vid } : {},
line_items: [{ price: "price_...", quantity: 1 }],
mode: "subscription",
success_url: "https://yourdomain.com/thanks",
});
return Astro.redirect(session.url!, 303);
}
---
<Layout>
<form method="POST">
<button type="submit">Buy</button>
</form>
</Layout>The cost is that the whole pricing page now renders on each request. The order in which Virling checks these fields, and PaymentIntents for Elements, are in the Stripe docs; what you get per channel is on the Stripe integration page.
A fully static site: Payment Links
If your Astro site has no adapter and you would rather keep it that way, create a Payment Link in the Stripe dashboard and link to it from any .astro page:
<a href="https://buy.stripe.com/...">Buy</a>
The script finds buy.stripe.com links when the page loads and again on click, and adds client_reference_id unless the link already has one. Nothing runs on your side, so the build can go to any static host. The link has to be a normal <a href> on a page with the script; a Payment Link sent by email or shown as a QR code carries no visitor ID. Limits on Payment Link parameters are in the Stripe Checkout UTM guide.
Test it in Astro
Follow the test payment in check that it works, with these Astro details:
- Visits to
localhostare not kept. Add127.0.0.1 dev.yourdomain.comto your hosts file, runnpm run dev -- --host dev.yourdomain.comand openhttp://dev.yourdomain.com:4321/?utm_source=test&utm_medium=email. - Put a
sk_test_key inSTRIPE_SECRET_KEYin.env;astro:envreads it from there in development. astro devrenders every route on request, prerendered or not, so it runs an endpoint that a build would skip. Runastro buildandastro previewonce (the Node adapter supports preview) or deploy to a subdomain such asstaging.yourdomain.com.
To check what the endpoint sent, log session.client_reference_id and session.metadata after the session is created. Other framework guides: Next.js, SvelteKit, Nuxt and Remix, and Cloudflare Workers for checkout in a plain Worker.
Common mistakes in Astro
An Unattributed payment with no Visitor under Details was created without the ID.
| What you see | Cause | Fix |
|---|---|---|
Checkout works in astro dev and is a 404 after deploy | The endpoint has no prerender = false, so the build prerenders it and no POST handler is deployed | Export prerender = false and add an adapter |
| The build fails because no adapter is set | A route has prerender = false or output is "server", and Astro has nothing to run it on | Add one with npx astro add, or switch to Payment Links |
| No visitor ID, or the same one on many payments | The cookie is read in a prerendered page, at build time, or in a page a CDN caches | Read it in the on-demand endpoint that creates the session |
The build warns that Astro.request.headers was used on a prerendered page | A prerendered page reads a cookie or header | Move the read to the endpoint, or render the page on demand |
403, Cross-site POST form submissions are forbidden | The form is on another origin than the endpoint | Serve both from one domain |
| Nothing is recorded, though a script was added | The tag lost data-site or was moved into a component script that Astro bundles | Use the is:inline tag from step 1 in the layout |
The dev server refuses dev.yourdomain.com | Vite answers only hosts it knows | Start it with --host dev.yourdomain.com, or add the host to vite.server.allowedHosts |
Causes outside Astro, from blocked scripts to cookieless mode and repeat customers, are in Unattributed revenue.
Frequently asked questions
How do I pass UTM parameters to a Stripe Checkout Session in Astro?
Pass the visitor ID instead of the tags. In an endpoint with export const prerender = false, read cookies.get("virling_vid")?.value and send it as client_reference_id when you create the session. Virling has the UTM tags of every visit under that ID.
How do I read the virling_vid cookie in Astro?
In an API endpoint, use cookies.get("virling_vid")?.value on the context. In the frontmatter of a page, use Astro.cookies.get("virling_vid")?.value. Both only work on routes that render on request, because a prerendered route has no request to read.
Why does the script tag need is:inline?
is:inline makes Astro print the tag exactly as written instead of processing and bundling it. The Virling script reads data-site from its own tag, so the tag has to reach the browser unchanged.
Do I need output: "server" to use Stripe Checkout in Astro?
No. Keep the default static output, add an adapter, and export prerender = false from the checkout endpoint only. Every other page is still built ahead of time.
Do Stripe Payment Links on a static Astro site need code?
No. Link to buy.stripe.com from a page that runs the script, and no adapter or server code is needed. The script adds client_reference_id to the link when the page loads and again on click, unless the link already has one.
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.