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

Cloudflare Workers and Stripe UTM tracking: Checkout from a Worker

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

A Worker usually does not render your pages, so Stripe UTM tracking from a Worker is about the request. The Virling script on your pages sets a virling_vid cookie, and the Worker that creates the Stripe Checkout Session pulls it out of the Cookie header and sends it to Stripe as client_reference_id. That ID is what lets Virling join the payment to every visit behind it instead of leaving it in Direct; link checkout to visits explains the join.

The examples are TypeScript, first with a plain fetch handler, then with Hono. For a Node server, see Express Stripe UTM tracking, and for the App Router, Next.js Stripe UTM tracking.

Start free trial

Step 1: add the script to your pages

The tag belongs in the <head> of your pages wherever they are served from: Cloudflare Pages, Workers static assets or another host on the same domain. On a self-hosted Virling, load v.js from your own instance.

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

Step 2: read the cookie from the Request headers

The Workers runtime has no cookie parser. Every cookie for the request arrives in a single Cookie header string, so take virling_vid out with a pattern that also rejects anything that is not a visitor ID:

function visitorId(req: Request): string | undefined {
  const m = (req.headers.get("Cookie") ?? "").match(/(?:^|;\s*)virling_vid=([A-Za-z0-9-]{8,64})(?:;|$)/);
  return m ? m[1] : undefined;
}

Step 3: create the Checkout Session

The stripe npm package has a build for Workers, which Wrangler picks automatically and which sends requests with the runtime's fetch. Passing Stripe.createFetchHttpClient() only makes that explicit:

// src/index.ts
import Stripe from "stripe";

interface Env {
  STRIPE_SECRET_KEY: string;
}

export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const url = new URL(req.url);
    if (req.method !== "POST" || url.pathname !== "/checkout") {
      return new Response("Not found", { status: 404 });
    }

    const stripe = new Stripe(env.STRIPE_SECRET_KEY, {
      httpClient: Stripe.createFetchHttpClient(),
    });

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

    return Response.redirect(session.url!, 303);
  },
} satisfies ExportedHandler<Env>;

An undefined client_reference_id is left out of the request, so a visit without the cookie still gets a session. The 303 turns the form's POST into a GET to Stripe:

<form action="/checkout" method="POST">
  <button type="submit">Subscribe</button>
</form>

Calling Stripe with plain fetch

To keep the bundle small, skip the package and call the Stripe API directly. It takes form-encoded bodies, with nested fields written as line_items[0][price]:

const vid = visitorId(req);
const form = new URLSearchParams({
  mode: "subscription",
  "line_items[0][price]": "price_...",
  "line_items[0][quantity]": "1",
  success_url: "https://yourdomain.com/thanks",
});
if (vid) form.set("client_reference_id", vid);

const res = await fetch("https://api.stripe.com/v1/checkout/sessions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${env.STRIPE_SECRET_KEY}`,
    "Content-Type": "application/x-www-form-urlencoded",
  },
  body: form,
});
if (!res.ok) return new Response("Checkout failed", { status: 502 });
const session = (await res.json()) as { url: string };
return Response.redirect(session.url, 303);

Keep the Stripe key in a secret

Variables under vars in your Wrangler config are stored in plain text, so the secret key does not belong there. Store it with npx wrangler secret put STRIPE_SECRET_KEY; it reaches the handler as env.STRIPE_SECRET_KEY, which is why the example builds the Stripe client inside fetch. For wrangler dev, put a test key in a .dev.vars file and keep that file out of git. npx wrangler types can generate the Env interface from your config.

The same route with Hono

In Hono, getCookie from hono/cookie does the header parsing, and the secret is a binding on c.env, typed through the Bindings generic:

// src/index.ts
import { Hono } from "hono";
import { getCookie } from "hono/cookie";
import Stripe from "stripe";

const app = new Hono<{ Bindings: { STRIPE_SECRET_KEY: string } }>();

app.post("/checkout", async (c) => {
  const stripe = new Stripe(c.env.STRIPE_SECRET_KEY, {
    httpClient: Stripe.createFetchHttpClient(),
  });
  const vid = getCookie(c, "virling_vid");

  const session = await stripe.checkout.sessions.create({
    client_reference_id: vid && /^[A-Za-z0-9-]{8,64}$/.test(vid) ? vid : undefined,
    line_items: [{ price: "price_...", quantity: 1 }],
    mode: "subscription",
    success_url: "https://yourdomain.com/thanks",
  });

  return c.redirect(session.url!, 303);
});

export default app;

Cookie scope: workers.dev or a route on your domain

Where the Worker answers decides whether it ever sees the cookie. The script sets virling_vid for your own domain, so a Worker on a route such as yourdomain.com/checkout* or on a custom domain such as pay.yourdomain.com gets it with every request, and a route on the same hostname as your pages needs no CORS at all. A workers.dev address is another site to the browser and never receives it. If the Worker has to stay there, read the ID in the browser with window.virling?.vid?.() and send it in the request body. The script loads with defer, so wait for it:

async function visitorId() {
  for (let i = 0; i < 20 && !window.virling?.vid; i++) {
    await new Promise((r) => setTimeout(r, 100));
  }
  return window.virling?.vid?.() || null;
}

async function checkout() {
  const res = await fetch("https://checkout.example.workers.dev/checkout", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ vid: await visitorId() }),
  });
  location.href = (await res.json()).url;
}

In the Worker, answer the browser's OPTIONS preflight with Access-Control-Allow-Origin set to your site, read vid from await req.json() with the same pattern check, and return { url: session.url } instead of redirecting. The ID is null in cookieless mode, and the payment then counts as Unattributed.

When client_reference_id is taken

Many apps already put their own user ID in client_reference_id. Leave it there and send the visitor ID as metadata.virling_vid; Virling checks both:

  const vid = visitorId(req);
  const session = await stripe.checkout.sessions.create({
    client_reference_id: user.id, // your own ID stays
    metadata: vid ? { virling_vid: vid } : {},
    line_items: [{ price: "price_...", quantity: 1 }],
    mode: "subscription",
    success_url: "https://yourdomain.com/thanks",
  });

A Worker that creates its own PaymentIntent for Elements sets the same metadata on stripe.paymentIntents.create(). The Stripe docs give the order Virling looks in, and the Stripe integration page shows what Virling imports.

Check that it works

Subscription renewals inherit the channel of the first payment without any Worker code, per renewals. Test with one tagged visit and one test payment from a page on your deployed site, as in test your setup. The script sends nothing from localhost unless the tag has data-dev, so a page served by wrangler dev stays silent by default.

If the payment shows as Unattributed, open its Checkout Session in the Stripe Dashboard. An empty client_reference_id and no metadata.virling_vid means the Worker did not get the cookie: check that it runs on a route or custom domain of your site, not on workers.dev, and that the page you bought from loads the script. How to track Stripe revenue by traffic source covers the rest of the path from visit to payment.

Other frameworks

The same steps for other stacks:

Frequently asked questions

How do I pass UTM parameters to Stripe Checkout from a Cloudflare Worker?

Parse virling_vid out of the request's Cookie header in the Worker that creates the Checkout Session and send it as client_reference_id. Virling links the payment to every visit with that ID, including each visit's UTM tags.

Does the virling_vid cookie reach my Worker?

Only when the Worker runs on your own domain or one of its subdomains, for example through a route or custom domain. On a workers.dev address the browser does not send it, so read the ID in the browser with window.virling?.vid?.() and send it in the request body.

Should I use client_reference_id or metadata.virling_vid?

Use client_reference_id unless it already holds your own user or order ID. In that case put the visitor ID in the session's metadata.virling_vid. Virling reads either.

Where should I keep the Stripe secret key in a Worker?

Store it with npx wrangler secret put STRIPE_SECRET_KEY and read it from env.STRIPE_SECRET_KEY. Do not put it under vars in your Wrangler config, which is plain text. For wrangler dev, use a .dev.vars file kept out of git.

What happens if the visitor ID is missing?

visitorId() returns undefined, and the session is created without one, for example when the script is blocked or runs in cookieless mode. The payment still counts toward revenue, as Unattributed.

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