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

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.

Start free trial

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.net or run.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 __session before 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 documentEnds up onRead by Virling
client_reference_idThe Checkout Session, in both modesYes
metadata.virling_vid, one-time price (mode: "payment")The PaymentIntentYes
metadata.virling_vid, recurring priceThe SubscriptionNo
Anything, on the session's own metadataNot possible: the extension does not set itNot 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

  1. 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 your sk_test_ key, and use a test-mode price. Doing this on the live project would send real buyers to test checkout.
  2. Serve that project on a subdomain you own, such as staging.yourdomain.com, added as a custom domain in Hosting. Visits on web.app, firebaseapp.com, preview channels and localhost are not recorded for your site.
  3. In a private window, open a tagged URL such as https://staging.yourdomain.com/?utm_source=test&utm_medium=email and note what window.virling.vid() returns in the console.
  4. Start checkout. With a callable, the request payload in the network tab looks like {"data":{"vid":"..."}}. With the extension, open the new checkout_sessions document in the Firestore console and look for client_reference_id. Both should hold the ID from step 3.
  5. 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.
  6. After the next sync, about a minute, open /app/yourdomain.com/payments. The payment carries the test source 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.

SymptomCauseFix
req.cookies.virling_vid is empty in the functionA direct call is cross-site, and a Hosting rewrite forwards only __sessionSend the ID as call data or a document field, as in step 2 (Hosting and cookies)
httpsCallable rejects with internal and no detailThe function threw an ordinary error, which onCall hides from the clientRead firebase functions:log, and throw HttpsError for errors the page should see (handle errors)
CORS error from an onRequest functionHTTP functions send no CORS headers unless told toSet 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 missingSpread the field in only when there is an ID, as in step 2b
The checkout_sessions document never gets a urlThe extension failed, for example on a price from the other mode, or the write was refused by Firestore rulesShow 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 UnattributedIn subscription mode the extension copies that metadata to the Subscription, which Virling does not readWrite the ID as client_reference_id instead
The visitor ID on the payment is a Firebase UIDclient_reference_id holds the UID and is taken as the visitor IDIn your own function, add metadata.virling_vid, which wins (Stripe docs)
stripeKey.value() is empty in the emulatorThe emulator does not read Secret ManagerPut the key in functions/.secret.local (configure your environment)
The payment has a visitor ID but no channelThe visits happened on web.app or a preview channel, which are not your domainTest 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:

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.

Start free trial See the demo