Firebase and Stripe UTM tracking: Cloud Functions and the extension
By Devendra Variya, co-founder of Virling. Published 2026-11-23, updated 2026-11-27.
Firebase apps start Stripe Checkout in one of two ways: a Cloud Function you write, or the Stripe Firebase extension (Run Payments with Stripe), which creates the session when your app adds a Firestore document. Either way, Virling credits the payment to a channel only when the session carries the visitor's ID. The virling_vid cookie never gets to Cloud Functions, so the browser reads the ID with window.virling?.vid?.() and hands it over: as call data to your own function, or as the client_reference_id field of the checkout_sessions document for the extension.
Building on Supabase instead? See Supabase and Stripe UTM tracking. Payment Links and the metadata limits Stripe sets are covered in Stripe Checkout UTM parameters, and the reports you get afterwards in track Stripe revenue by traffic source.
Why the cookie does not get through
The Virling script stores the visitor ID in a first-party cookie on your domain. Firebase gives the backend two other ways in, and neither passes it on:
- Calling the function directly. It answers on
cloudfunctions.netorrun.app, a different site, so the browser keeps your domain's cookies to itself. - Through a Firebase Hosting rewrite. The request stays on your domain, but Hosting removes every cookie except one named
__sessionbefore it forwards the request to the function (Hosting and cookies). - Through the extension. The session is created by the extension's own function from a Firestore document, so no browser request of yours reaches it at all.
So in every case the ID has to be part of the data your app sends.
Step 1: load the script and read the ID
Add the Virling tag to the <head> of public/index.html, or of whatever HTML file your framework serves for every route, with defer left in place. On a self-hosted Virling, point src at your own server.
<script defer src="https://app.virling.com/v.js" data-site="yourdomain.com"></script>
Because the tag is deferred, checkout code that runs early can find window.virling not yet defined. This helper polls for up to two seconds and gives back null when there is no ID, as with a blocked script or cookieless mode:
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;
}Step 2a: a callable Cloud Function
With onCall, the Firebase SDK handles CORS and sends the signed-in user's token for you. The function takes the ID from request.data, drops anything that does not look like a visitor ID, and puts it on the session:
// functions/index.js
const { onCall, HttpsError } = require("firebase-functions/v2/https");
const { defineSecret } = require("firebase-functions/params");
const Stripe = require("stripe");
const stripeKey = defineSecret("STRIPE_SECRET_KEY");
exports.createCheckout = onCall({ secrets: [stripeKey] }, async (request) => {
if (!request.auth) throw new HttpsError("unauthenticated", "Sign in first");
const stripe = new Stripe(stripeKey.value());
const vid = request.data?.vid;
const visitor = typeof vid === "string" && /^[A-Za-z0-9-]{8,64}$/.test(vid)
? vid
: undefined;
const session = await stripe.checkout.sessions.create({
client_reference_id: visitor,
metadata: { firebase_uid: request.auth.uid },
line_items: [{ price: "price_...", quantity: 1 }],
mode: "subscription",
success_url: "https://yourdomain.com/thanks",
});
return { url: session.url };
});Store the Stripe key with firebase functions:secrets:set STRIPE_SECRET_KEY, then run firebase deploy --only functions. The Firebase UID rides along in metadata.firebase_uid, so client_reference_id stays free for the visitor ID. If your webhooks already expect the UID in client_reference_id, swap them: keep the UID there and send metadata: visitor ? { virling_vid: visitor } : {}, which Virling reads before client_reference_id.
On the page, call it and redirect:
import { getFunctions, httpsCallable } from "firebase/functions";
const createCheckout = httpsCallable(getFunctions(), "createCheckout");
async function checkout() {
const { data } = await createCheckout({ vid: await visitorId() });
window.location.href = data.url;
}If you use onRequest instead, nothing handles CORS for you: pass cors: ["https://yourdomain.com"] in the function's options, and read the ID from req.body.
Step 2b: the Stripe Firebase extension
Here your app never calls Stripe. It adds a document to customers/{uid}/checkout_sessions, the extension builds a Checkout Session from that document's fields, and writes the session's url (or an error) back to it. client_reference_id is one of the fields the extension passes through, so the visitor ID goes there. Firestore rejects undefined, which is why the field is spread in only when an ID exists:
import { getFirestore, collection, addDoc, onSnapshot } from "firebase/firestore";
async function checkout(uid) {
const vid = await visitorId();
const ref = await addDoc(
collection(getFirestore(), "customers", uid, "checkout_sessions"),
{
price: "price_...",
success_url: window.location.origin + "/thanks",
cancel_url: window.location.href,
...(vid && { client_reference_id: vid }),
},
);
onSnapshot(ref, (snap) => {
const { url, error } = snap.data();
if (error) showError(error.message);
if (url) window.location.assign(url);
});
}If you picked another collection than customers when installing the extension, use that path, and swap showError for your app's own error display.
Where the extension puts metadata
The document also accepts a metadata field, and it is tempting to put virling_vid there. Where it lands depends on the checkout mode:
| Field on the document | Ends up on | Read by Virling |
|---|---|---|
client_reference_id | The Checkout Session, in both modes | Yes |
metadata.virling_vid, one-time price (mode: "payment") | The PaymentIntent | Yes |
metadata.virling_vid, recurring price | The Subscription | No |
Anything, on the session's own metadata | Not possible: the extension does not set it | Not applicable |
So client_reference_id is the field that works for subscriptions and one-time payments alike. If your app already fills it with something else, the extension leaves no other session field for the visitor ID; start that checkout from a callable function as in step 2a. Virling's full lookup order is in the Stripe docs, and the subscription side is on the Stripe for SaaS page. The UTM tags themselves never need to go to Stripe: the script has them on file under the visitor ID.
Test it on a Firebase project
- Connect a restricted Stripe key starting with
rk_test_in Virling. On a separate Firebase project, set the function's secret, or the extension's Stripe API key parameter, to yoursk_test_key, and use a test-mode price. Doing this on the live project would send real buyers to test checkout. - Serve that project on a subdomain you own, such as
staging.yourdomain.com, added as a custom domain in Hosting. Visits onweb.app,firebaseapp.com, preview channels andlocalhostare not recorded for your site. - In a private window, open a tagged URL such as
https://staging.yourdomain.com/?utm_source=test&utm_medium=emailand note whatwindow.virling.vid()returns in the console. - Start checkout. With a callable, the request payload in the network tab looks like
{"data":{"vid":"..."}}. With the extension, open the newcheckout_sessionsdocument in the Firestore console and look forclient_reference_id. Both should hold the ID from step 3. - Pay with
4242 4242 4242 4242, any future expiry and any CVC (Stripe testing). In the Stripe Dashboard, the Checkout Session shows the same ID as its client reference ID. - After the next sync, about a minute, open
/app/yourdomain.com/payments. The payment carries thetestsource and the Email channel; open it for the full journey.
A repeat buyer's payment is a renewal and keeps the first payment's channel, and the extension reuses one Stripe customer per Firebase user, so test with a fresh user each time. More checks are in test your setup.
Firebase problems and fixes
Start from the payment in Virling: if Details shows no Visitor, the ID was lost before Stripe.
| Symptom | Cause | Fix |
|---|---|---|
req.cookies.virling_vid is empty in the function | A direct call is cross-site, and a Hosting rewrite forwards only __session | Send the ID as call data or a document field, as in step 2 (Hosting and cookies) |
httpsCallable rejects with internal and no detail | The function threw an ordinary error, which onCall hides from the client | Read firebase functions:log, and throw HttpsError for errors the page should see (handle errors) |
CORS error from an onRequest function | HTTP functions send no CORS headers unless told to | Set the cors option to your origin, or switch to onCall |
addDoc fails with "Unsupported field value: undefined" | client_reference_id was written straight from window.virling?.vid?.() while the script was missing | Spread the field in only when there is an ID, as in step 2b |
The checkout_sessions document never gets a url | The extension failed, for example on a price from the other mode, or the write was refused by Firestore rules | Show the document's error field, and read the extension's function logs in the Firebase console |
virling_vid is in the document's metadata, yet subscriptions are Unattributed | In subscription mode the extension copies that metadata to the Subscription, which Virling does not read | Write the ID as client_reference_id instead |
| The visitor ID on the payment is a Firebase UID | client_reference_id holds the UID and is taken as the visitor ID | In your own function, add metadata.virling_vid, which wins (Stripe docs) |
stripeKey.value() is empty in the emulator | The emulator does not read Secret Manager | Put the key in functions/.secret.local (configure your environment) |
| The payment has a visitor ID but no channel | The visits happened on web.app or a preview channel, which are not your domain | Test on a custom domain or subdomain (script docs) |
Other reasons are listed in Unattributed revenue. Fixes apply to new payments only, so pay again to confirm one.
Other frameworks
The same steps for other stacks:
- Supabase Stripe UTM tracking
- Convex Stripe UTM tracking
- Next.js Stripe UTM tracking
- React Stripe UTM tracking
- Express Stripe UTM tracking
- Cloudflare Workers Stripe UTM tracking
- SvelteKit Stripe UTM tracking
- Nuxt Stripe UTM tracking
Frequently asked questions
Does the virling_vid cookie reach a Firebase Cloud Function?
No. Called directly, the function runs on its own Google domain, so the browser does not send your cookie. Behind a Firebase Hosting rewrite, Hosting strips every cookie except __session. Read the ID in the browser with window.virling?.vid?.() and send it in the request.
Does the Stripe Firebase extension pass the visitor ID to Stripe?
Yes, if you write it as client_reference_id on the checkout_sessions document. The extension copies that field onto the Checkout Session, where Virling reads it.
Can I use metadata.virling_vid with the extension?
Only in payment mode. The extension puts the document's metadata on the PaymentIntent in payment mode, which Virling reads, but on the Subscription in subscription mode, which Virling does not read. It never sets metadata on the Checkout Session itself. Use client_reference_id instead.
Should my checkout function use onCall or onRequest?
onCall is simpler: the Firebase SDK sends the user's token, handles CORS and wraps the visitor ID in the call data. Use onRequest only if something other than your Firebase app calls the function, and then set its cors option to your origin.
Are visits on a Firebase preview channel recorded?
No. Preview channels, web.app and firebaseapp.com are not your domain, so the script does not record visits there. Test on a custom domain or subdomain connected to Hosting. A payment whose visits were not recorded 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.