Nuxt Stripe UTM tracking: tie each payment to its source
By Devendra Variya, co-founder of Virling. Published 2026-11-22, updated 2026-11-27.
In Nuxt 4, the code that creates a Stripe Checkout Session belongs in a Nitro route under server/api, and that route is where the visitor's source can be attached. Call getCookie(event, "virling_vid") there and send the value as client_reference_id. The tracking script itself goes in app.head of nuxt.config.ts, or in useHead if you prefer to keep it in a component.
Stripe's checkout page runs on Stripe's own domain, so without that ID the payment has no link to the ad or post that brought the buyer. With it, Virling finds the visits that set the same cookie and credits their UTM tags; link checkout to visits covers the general idea. Using Polar instead? See Nuxt Polar UTM tracking.
Step 1: load the script from app.head or useHead
The config entry is static: Nitro writes it into every server-rendered and prerendered page, and the Vue router's route changes are picked up through history.pushState. Self-hosting Virling? Point src at your own server.
// nuxt.config.ts
export default defineNuxtConfig({
app: {
head: {
script: [
{ src: "https://app.virling.com/v.js", defer: true,
"data-site": "yourdomain.com" },
],
},
},
runtimeConfig: {
stripeSecretKey: "", // filled from NUXT_STRIPE_SECRET_KEY at run time
},
});Keys at the top level of runtimeConfig never reach the client bundle; only those under public do. If you would rather add the tag from app/app.vue, for example to render it only after a consent check, useHead takes the same object:
<!-- app/app.vue -->
<script setup lang="ts">
useHead({
script: [
{ src: "https://app.virling.com/v.js", defer: true,
"data-site": "yourdomain.com" },
],
});
</script>
<template>
<NuxtPage />
</template>Use one of the two, not both, or every route is counted twice.
Step 2: a server/api route that reads the cookie
defineEventHandler, getCookie, sendRedirect and useRuntimeConfig are auto-imported in the server directory, which stays at the project root in Nuxt 4. The .post suffix makes Nitro answer this file only for POST:
// server/api/checkout.post.ts
import Stripe from "stripe";
export default defineEventHandler(async (event) => {
const stripe = new Stripe(useRuntimeConfig(event).stripeSecretKey);
const session = await stripe.checkout.sessions.create({
client_reference_id: getCookie(event, "virling_vid"),
line_items: [{ price: "price_...", quantity: 1 }],
mode: "subscription",
success_url: "https://yourdomain.com/thanks",
});
return sendRedirect(event, session.url!, 303);
});Pages live under app/pages in Nuxt 4. A native form is enough, and it works with JavaScript turned off:
<!-- app/pages/pricing.vue -->
<template>
<form method="POST" action="/api/checkout">
<button type="submit">Buy</button>
</form>
</template>Or call it with $fetch and navigateTo
To start checkout from a click handler, return the URL as JSON instead of redirecting. This variant also shows metadata.virling_vid, for apps that already use client_reference_id for their own user or cart ID:
// server/api/checkout-url.post.ts
import Stripe from "stripe";
export default defineEventHandler(async (event) => {
const stripe = new Stripe(useRuntimeConfig(event).stripeSecretKey);
const vid = getCookie(event, "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",
});
return { url: session.url };
});navigateTo needs external: true to leave your domain. Because buy() only runs on a click, $fetch is a browser request and carries the cookie:
<!-- app/pages/pricing.vue -->
<script setup lang="ts">
async function buy() {
const { url } = await $fetch("/api/checkout-url", { method: "POST" });
await navigateTo(url!, { external: true });
}
</script>
<template>
<button type="button" @click="buy">Buy</button>
</template>Every field Virling reads on a Stripe payment, in order, is listed in the Stripe docs. Metadata limits and where the ID shows up in the Stripe dashboard are in Stripe Checkout UTM parameters, and the reports you get are on the Stripe integration page.
routeRules: prerender, swr and isr
A pricing page under routeRules with prerender: true is written to HTML at build time, and one with swr or isr is served from a cache, so useCookie during its render sees nobody's cookie, or a stranger's. That is fine for the page: the form on it still posts to /api/checkout, which runs per request. Keep the API route itself out of cached patterns such as "/api/**": { swr: true }.
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
"/pricing": { prerender: true },
"/blog/**": { isr: 3600 },
// no rule for /api/checkout: it runs on every request
},
});Nitro's response cache only stores GET and HEAD, one more reason the route is a .post.ts file. Then there is nuxt generate: it emits static files and no server, so /api/checkout does not exist after deploy. On such a site, use Stripe Payment Links, which the script fills in the browser (see reading the visitor cookie in server code).
Nitro presets: Node, Vercel, Cloudflare
- node-server, the default, runs
.output/server/index.mjs. SetNUXT_STRIPE_SECRET_KEYin the environment of that process. - vercel runs server routes in a Vercel Function and hands
isrrules to Vercel's cache. AddNUXT_STRIPE_SECRET_KEYin the project's environment variables and redeploy. - cloudflare_module and cloudflare_pages pass environment variables with each request rather than at startup. That is why the handlers above call
useRuntimeConfig(event)inside the handler; a config read at the top of the file may not see the key.
Test it
The steps for a test payment, from a tagged visit to the payments list, are in check that it works. For Nuxt, two details:
- The script ignores
localhost. Mapdev.yourdomain.comto127.0.0.1in your hosts file, runnpx nuxt dev --host dev.yourdomain.com, and openhttp://dev.yourdomain.com:3000/?utm_source=test&utm_medium=email. Put a test key that starts withsk_test_inNUXT_STRIPE_SECRET_KEY. - The dev server renders prerendered pages on request, so it cannot show a page that was baked wrongly. Before you deploy, run
npx nuxt buildand thennpx nuxt previewto try the production server, with prerendered and cached pages as they will be.
To see what the route sent, log session.client_reference_id and session.metadata right after stripe.checkout.sessions.create(); the terminal running Nuxt prints it. The same pattern on other frameworks: Next.js, SvelteKit, Astro, and plain Vue without Nuxt.
Common mistakes in Nuxt
When a payment comes in as Unattributed, open it: no Visitor under Details means the session was created without the ID.
| What you see | Cause | Fix |
|---|---|---|
| No visitor ID, though the browser has the cookie | Checkout is a GET route under a swr or cache rule, which Nitro runs without cookies | Use a POST route, such as checkout.post.ts, and keep it out of the cached patterns |
| Several buyers are sent to the same Checkout Session | The same rule keeps the response of that GET route, session URL included | Create the session in a POST route, once per click |
No visitor ID when $fetch is called in setup | During server rendering $fetch does not pass on the browser's cookies | Call it from a click handler, as above |
| The same or no ID in a hidden field | useCookie is read on a prerendered or cached page | Read the cookie in the server/api route |
404 on /api/checkout after deploy | The site was built with nuxt generate, which includes no server | Deploy with nuxt build, or use Payment Links |
| Sessions in Stripe that nobody asked for | The session is created with useFetch in a page, so on every render of it, crawlers included | Create it when the buyer presses Buy |
| The Stripe key is empty on Cloudflare | useRuntimeConfig() is called outside the handler, before a request brings the environment | Call useRuntimeConfig(event) inside defineEventHandler |
| Two pageviews for each route | The tag is in both app.head and useHead, or also in a tag manager | Keep one of them |
Causes that have nothing to do with Nuxt, such as a blocked script or a redirect that drops the query string, are in Unattributed revenue.
Frequently asked questions
How do I pass UTM parameters to a Stripe Checkout Session in Nuxt?
Read the visitor ID from the virling_vid cookie with getCookie in a server/api route, 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 a Nuxt server route?
Call getCookie(event, "virling_vid") inside defineEventHandler. Both are auto-imported in the server directory. It is a first-party cookie on your domain, so the browser sends it with every request to your app, including $fetch calls from the page.
Is client-side navigation in Nuxt counted?
Yes. With the script in app.head of nuxt.config.ts it is rendered into every page, and route changes made by the Nuxt router are tracked through history.pushState.
Can a site built with nuxt generate use Stripe Checkout?
Not with a server route, because nuxt generate outputs static files only. Use Stripe Payment Links on buy.stripe.com instead: the script adds client_reference_id to those links in the browser.
Which Nitro preset should the checkout route run on?
Any preset with a server: node-server, vercel and the Cloudflare presets all run server/api routes on each request. On Cloudflare, call useRuntimeConfig(event) inside the handler so the Stripe key is there.
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.