Express Stripe UTM tracking: Checkout in Node.js
By Devendra Variya, co-founder of Virling. Published 2026-11-21, updated 2026-11-29.
An Express app carries the visitor ID to Stripe in a single route: cookie-parser turns the virling_vid cookie into req.cookies.virling_vid, and the route hands it to stripe.checkout.sessions.create() as client_reference_id. Below is a complete server.js with that route and a webhook verified with express.raw, and the middleware order that keeps both working.
Checkout happens on Stripe's domain, which never sees your landing page's UTM tags. The Virling script records them against a visitor ID in a first-party cookie, and any Stripe payment carrying that ID is joined to the visits behind it. The guide to Stripe Checkout UTM parameters covers Payment Links, metadata limits and where the values show up in Stripe. For a Nest app, see NestJS Stripe UTM tracking; with a single-page app in front of Express, see Angular or Vue. A C# backend does the same in one endpoint, as in the ASP.NET Core guide with Stripe.net.
The tag in your views
Put the script before </head> in the template every page extends, such as views/layout.ejs or views/layout.pug, or in public/index.html if express.static serves a built frontend. On a self-hosted Virling, swap app.virling.com for your server's address.
<script defer src="https://app.virling.com/v.js" data-site="yourdomain.com"></script>
One server.js: webhook, cookie-parser, checkout
Express runs middleware in the order you register it. The webhook route goes first with its own express.raw parser, then cookie-parser and express.json() for every route after them:
// server.js
const express = require("express");
const cookieParser = require("cookie-parser");
const Stripe = require("stripe");
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const app = express();
app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
req.headers["stripe-signature"],
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
return res.status(400).send(`Webhook error: ${err.message}`);
}
// act on event.type here
res.json({ received: true });
});
app.use(cookieParser());
app.use(express.json());
app.post("/checkout", async (req, res) => {
const session = await stripe.checkout.sessions.create({
mode: "subscription",
line_items: [{ price: "price_...", quantity: 1 }],
success_url: "https://yourdomain.com/thanks",
client_reference_id: req.cookies.virling_vid,
});
res.redirect(303, session.url);
});
app.listen(3000);req.cookies.virling_vid is a string when the buyer has the cookie and undefined when not, and the stripe library drops undefined fields, so one line covers both. Read req.cookies, not req.signedCookies: the script's cookie is unsigned, so a secret passed to cookieParser() changes nothing for it.
express.raw leaves req.body as a Buffer of the exact bytes Stripe signed, which constructEvent() needs. Had app.use(express.json()) come first, the body would already be an object and every check would fail. Virling reads payments with a restricted key and needs no webhook; this route is for your own logic, such as provisioning an account.
On Express 5, a rejected promise in an async route goes to the error handler. Express 4 does not catch it, so wrap the await in try/catch and call next(err), or the failed call becomes an unhandled rejection, which stops the process on current Node versions. Post a plain form to the route, so the browser follows the 303 to Stripe:
<form action="/checkout" method="POST"> <button type="submit">Subscribe</button> </form>
When client_reference_id is your user ID
If Passport or your own session code already puts the user's ID in client_reference_id, move the visitor ID to the session's metadata. Virling looks there first:
const vid = req.cookies.virling_vid;
const session = await stripe.checkout.sessions.create({
client_reference_id: req.user.id,
metadata: vid ? { virling_vid: vid } : undefined,
mode: "subscription",
line_items: [{ price: "price_...", quantity: 1 }],
success_url: "https://yourdomain.com/thanks",
});A custom Elements flow takes the same metadata on stripe.paymentIntents.create(). The full lookup order is in the Stripe docs, and the checkout snippet generator writes the equivalent code for other providers.
Calling the route from another origin
A page on www.yourdomain.com calling api.yourdomain.com already has the cookie, because the script sets it on the parent domain. Add credentials: "include" to the fetch call and cors({ origin: "https://www.yourdomain.com", credentials: true }) to the app, since browsers refuse the default * origin on a request with credentials. An API on an unrelated domain never gets the cookie, so read the ID in the browser, waiting for the deferred script, and post 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://api.example.com/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ vid: await visitorId() }),
});
location.href = (await res.json()).url;
}In the route, req.body.vid || undefined goes into client_reference_id, and res.json({ url: session.url }) replaces the redirect. The Content-Type header matters: without it express.json() skips the body, which leaves req.body undefined on Express 5 and {} on Express 4.
Check it
Start the server with a test secret key in STRIPE_SECRET_KEY and a test-mode price, connect a restricted rk_test_ key in Virling, and make one tagged visit and one payment as in test your setup. A temporary console.log(session.client_reference_id) after the create call should print what window.virling.vid() returns in the browser console. For the webhook, stripe listen --forward-to localhost:3000/webhook prints the whsec_ secret to put in STRIPE_WEBHOOK_SECRET.
Renewals and plan changes are credited to the first payment's channel with no extra code, as in renewals. Server-side revenue tracking covers refunds, and the SaaS page shows the per-channel view.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
Cannot read properties of undefined (reading 'virling_vid') | cookie-parser is missing, or registered below the checkout route | Move app.use(cookieParser()) above the route (cookie-parser) |
Every webhook fails with No signatures found matching the expected signature for payload | app.use(express.json()) is registered above the webhook route and parses the body first | Register the webhook route with express.raw({ type: "application/json" }) before the global JSON parser (express.raw, Stripe signature docs) |
| The server exits when Stripe rejects a checkout request | Express 4 does not pass rejected promises from async routes to the error handler | Upgrade to Express 5, or catch the error and call next(err) (Express error handling) |
The browser reports a CORS error for checkout.stripe.com | The button uses fetch, which follows the 303 to Stripe's domain in the background | Post a plain form, or return res.json({ url: session.url }) and set location.href (res.json) |
After paying, the buyer lands on an http:// or internal address | success_url is built from req.protocol and req.hostname, and Express does not trust the proxy in front of it | Set app.set("trust proxy", 1) for exactly one proxy that sets X-Forwarded-*, or use a fixed URL (Express behind proxies) |
| The visitor ID is set in a job, and is always missing | The session is created in a queue worker or in the webhook route, where the buyer's cookie is not available | Read req.cookies.virling_vid in the route the browser posts to and pass the value on (link checkout to visits) |
req.cookies is empty on node server.js at localhost:3000 | The script ignores localhost and 127.* unless its tag carries data-dev | Add data-dev in the layout while developing, and test end to end on a subdomain of your site |
Some Unattributed payments are expected: a blocked script, cookieless mode or pending consent means no cookie, and the payment still counts toward revenue (Unattributed revenue). Do not let a cache or CDN in front of Express strip the Cookie header from /checkout (page caching and CDNs).
Frequently asked questions
How do I pass UTM parameters to Stripe Checkout in Express?
In the route that calls stripe.checkout.sessions.create(), set client_reference_id to req.cookies.virling_vid. The script files every visit and its UTM tags under that ID, so the payment is credited to the right campaign.
Why is req.cookies undefined in Express?
Nothing parses the Cookie header until the cookie-parser middleware runs. Register app.use(cookieParser()) above the checkout route; middleware added after a route does not run for it.
Should the Stripe webhook route use express.json()?
No. Give it express.raw({ type: "application/json" }) and register it before app.use(express.json()), so stripe.webhooks.constructEvent() receives the raw Buffer that Stripe signed.
Do I need try/catch around the Stripe call in an Express route?
On Express 4, yes: a rejected promise in an async route never reaches the error handler, so catch it and call next(err). Express 5 forwards it to the error handler for you.
Why does fetch not send the virling_vid cookie to my Express API?
By default, fetch sends cookies only to the same origin, and a subdomain such as api.yourdomain.com is another origin. Set credentials: "include" on the request, and use the cors middleware with your site's origin and credentials: true. If the API is on another domain, send the visitor ID in the request body instead.
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.