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

Vue Stripe UTM tracking: pass UTM tags to Stripe Checkout

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

In a Vue 3 app built with Vite, a composable reads the virling_vid cookie, the buy button posts it to your backend, and the backend sets it as metadata.virling_vid on the Stripe Checkout Session. Vue Router needs no setup for this: the Virling script already counts each route change as a pageview.

UTM tags in the landing URL never reach Stripe's checkout page, so the script stores them against the visitor ID and Virling joins the payment to the visits behind that ID. Payment Links, metadata limits and where the values appear in Stripe are in the general guide to Stripe Checkout UTM parameters. Nuxt has its own server routes, covered in Nuxt Stripe UTM tracking, and React is in React Stripe UTM tracking.

Start free trial

The tag in index.html, above the Vite entry

A project made with npm create vue@latest is a Vite app (Vue quick start), and Vite treats the index.html at the project root as its entry point (Vite guide). Put the tag in its <head>. A self-hosted server goes in place of app.virling.com.

<!-- index.html -->
<script defer src="https://app.virling.com/v.js"
  data-site="yourdomain.com"></script>

Deferred scripts and module scripts run in document order, so this tag runs before Vite's <script type="module" src="/src/main.js"> in the body, and the cookie is set before any component mounts. A component cannot load it instead: Vue ignores <script> tags in templates.

A useCheckout composable that reads the cookie

A composable is a function that uses the Composition API to hold state any component can reuse (Vue composables). This one reads the visitor ID from document.cookie, posts it to your backend, and keeps a busy flag and an error message in refs:

// src/composables/useCheckout.js
import { ref } from "vue";

function visitorId() {
  const m = document.cookie.match(/(?:^|; )virling_vid=([^;]+)/);
  return m ? m[1] : null;
}

export function useCheckout() {
  const busy = ref(false);
  const error = ref("");

  async function start() {
    busy.value = true;
    error.value = "";
    try {
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ vid: visitorId() }),
      });
      if (!res.ok) throw new Error(res.statusText);
      window.location.assign((await res.json()).url);
    } catch {
      error.value = "Checkout could not start. Please try again.";
      busy.value = false;
    }
  }

  return { busy, error, start };
}

The ID travels in the request body, so the same code works when the API runs on another domain, where the browser would not send the cookie. In cookieless mode the script creates no cookie, visitorId() returns null, and the payment is counted as Unattributed.

The buy button

Any component can now start checkout in a few lines with <script setup> (Vue SFC reference):

<!-- src/components/BuyButton.vue -->
<script setup>
import { useCheckout } from "@/composables/useCheckout";

const { busy, error, start } = useCheckout();
</script>

<template>
  <button type="button" :disabled="busy" @click="start">Buy</button>
  <p v-if="error">{{ error }}</p>
</template>

Top-level refs unwrap in the template, so busy and error need no .value there. The @ alias points at src in the vite.config.js that create-vue generates.

The endpoint that creates the session

Creating a session takes the Stripe secret key, and everything in a Vite bundle is public, including any variable prefixed with VITE_ (Vite env variables). So the call runs in a small Express server next to the app, installed with npm install express stripe (Stripe API reference):

// server.mjs
import express from "express";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const appUrl = process.env.APP_URL || "http://localhost:5173";
const app = express();
app.use(express.json());

app.post("/api/checkout", async (req, res) => {
  const vid = String(req.body.vid ?? "");
  const session = await stripe.checkout.sessions.create({
    mode: "subscription",
    line_items: [{ price: process.env.STRIPE_PRICE_ID, quantity: 1 }],
    success_url: `${appUrl}/thanks`,
    metadata: /^[A-Za-z0-9-]{8,64}$/.test(vid) ? { virling_vid: vid } : {},
  });
  res.json({ url: session.url });
});

app.listen(3000);

The price ID is read on the server, so a visitor cannot pick a cheaper one, and the regular expression keeps anything that is not a visitor ID out of the metadata. Virling reads metadata.virling_vid on the session, or client_reference_id if you prefer that field (Stripe docs).

What Vue Router navigation means for tracking

With createWebHistory(), router.push calls history.pushState and router.replace calls history.replaceState. The Virling script listens to both and to popstate, so each route is a pageview without a router.afterEach hook (single-page apps). Route changes carry no referrer, so they stay in the channel of the landing page.

  • Startup. Vue Router calls replaceState with the current URL to store its own state. The script skips a repeat of the same URL, so the landing counts once.
  • Guards. A navigation guard that returns another route redirects before the URL changes, so only the final route is counted (Vue Router navigation guards).
  • RouterLink. A link to /pricing drops the query string of the landing URL. That is fine: the tags were recorded with the first pageview.
  • Query state. router.push({ query: { q } }) on every keystroke of a search box sends a pageview each time. Keep that state in a ref instead.
  • Hash mode. createWebHashHistory() keeps the route after the #, so the path never changes and only the first page is counted (Vue Router history modes).

Test it with the Vite dev server

Proxy /api from the dev server to Express, so the fetch stays on one origin (Vite server options). Keep the plugins your config already has and add only server.proxy, then restart npm run dev:

// vite.config.js
import vue from "@vitejs/plugin-vue";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: { "/api": "http://localhost:3000" },
  },
});

Add data-dev to the tag, since the script skips localhost without it, and set data-site to a test site connected to a restricted rk_test_ key. Start Express with STRIPE_SECRET_KEY=sk_test_... STRIPE_PRICE_ID=price_... node server.mjs, open http://localhost:5173/?utm_source=test&utm_medium=test in a private window, follow a RouterLink and click Buy. Pay with 4242 4242 4242 4242 (Stripe testing), and after the next sync the payment shows the test source in Virling.

The proxy only exists in npm run dev. In production, serve /api/checkout from the app's domain, or allow the app's origin with CORS; the ID is in the body, so no cookie has to cross. Remove data-dev and set APP_URL before you deploy. The full checklist is in test your setup, the join from visit to payment is explained in how to track Stripe revenue by traffic source, and the server side has its own post, Express Stripe UTM tracking.

Frequently asked questions

How do I pass UTM parameters to Stripe Checkout from a Vue app?

Pass the visitor ID instead. A composable reads the virling_vid cookie, the buy button posts it to your backend, and the backend sets it as metadata.virling_vid on the Checkout Session. Virling has the UTM tags of each visit recorded under that ID.

Do I need a router.afterEach hook to track route changes?

No. With createWebHistory(), Vue Router changes the URL with history.pushState and history.replaceState, which the Virling script listens to. Each new path or query string is one pageview.

Why does createWebHashHistory count only the first page?

Hash mode keeps the route after the # in the URL, so the path and query never change, and the script sends a pageview only when one of them does. Switch to createWebHistory().

Can the Vue app create the Checkout Session without a backend?

No. The secret key would end up in the Vite bundle, which anyone can read. Use a small server or serverless function, or a Stripe Payment Link in a normal link on a page that runs the script, which adds the visitor ID to it.

Can I use the composable with the Options API?

Yes. Call useCheckout() inside the setup() option and return busy, error and start from it. The template uses them the same way as with script setup.

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