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

Convex Stripe UTM tracking: Checkout from a Convex action

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

Convex Stripe UTM tracking needs one value carried through checkout. Read the visitor ID in the browser with window.virling?.vid?.(), pass it as an argument to the Convex action that creates the Stripe Checkout Session, and set it there as metadata.virling_vid. The virling_vid cookie cannot do this alone: it belongs to your domain, and the action runs on your Convex deployment. This guide also keeps the first ID on the Convex Auth user document, so a checkout made weeks later on another device still points at the visit that brought them.

The Edge Function version, with Row Level Security instead of internal functions, is in Supabase and Stripe UTM tracking. For other payment providers, the checkout snippet generator writes the code.

Start free trial

Before you start

Put the Virling script tag in your app's index.html and read the visitor ID when the user clicks to pay, as the guide to Stripe Checkout UTM parameters shows. Stripe stores it on the Checkout Session, and Virling joins it to the recorded visits and their UTM tags (link checkout to visits).

Why an action and not a mutation

Convex queries and mutations run inside a database transaction and cannot make network requests, so they cannot call Stripe. Actions can. Mutations still have a job here: one reads and writes the saved visitor ID atomically, and the action calls it with ctx.runMutation. The path is browser, then public action, then internal mutation, then Stripe.

Convex advises against calling actions straight from the client in most cases, in favor of a mutation that schedules the action. A scheduled action cannot hand a Checkout URL back to the click that started it, so this example calls the action directly. See the Convex actions docs.

Call the action from React

With ConvexAuthProvider around your app, useAction sends the signed-in user's token with each call. The helper waits up to two seconds for the deferred script and leaves the argument out if there is still no ID:

// src/CheckoutButton.jsx
import { useAction } from "convex/react";
import { api } from "../convex/_generated/api";

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;
}

export function CheckoutButton() {
  const createCheckout = useAction(api.checkout.create);

  async function checkout() {
    const vid = await visitorId();
    const url = await createCheckout(vid ? { vid } : {});
    if (url) window.location.href = url;
  }

  return <button onClick={checkout}>Subscribe</button>;
}

Store the visitor ID on the Convex Auth user

With Convex Auth, the users table is part of your own schema through authTables, and you can redefine it with extra fields. So the visitor ID can sit on the user document itself. Add an optional field next to the default ones in convex/schema.ts:

users: defineTable({
  // keep the other default Convex Auth fields
  name: v.optional(v.string()),
  virlingVid: v.optional(v.string()),
}),

Then add an internal mutation in convex/visitors.ts. It returns the saved ID if the user has one, and otherwise saves the one the browser sent:

import { v } from "convex/values";
import { internalMutation } from "./_generated/server";

export const keep = internalMutation({
  args: { userId: v.id("users"), vid: v.optional(v.string()) },
  handler: async (ctx, { userId, vid }) => {
    const user = await ctx.db.get("users", userId);
    if (user?.virlingVid) return user.virlingVid;
    if (!user || !vid) return null;
    await ctx.db.patch("users", userId, { virlingVid: vid });
    return vid;
  },
});

Because the mutation is a transaction, two checkouts started at the same moment cannot save two different IDs: Convex retries the one that conflicts. Internal functions cannot be called from the browser, so make sure no public mutation, such as a profile update that spreads its arguments into patch, lets users set virlingVid themselves.

Create the Checkout Session in a Node action

Install the library with npm install stripe and put the action in convex/checkout.ts. The file name and the export name make up api.checkout.create. The "use node" line runs the file in the Convex Node.js runtime, and such a file may only hold actions, which is why the mutation lives in visitors.ts:

"use node";

import Stripe from "stripe";
import { v } from "convex/values";
import { getAuthUserId } from "@convex-dev/auth/server";
import { action } from "./_generated/server";
import { internal } from "./_generated/api";

export const create = action({
  args: { vid: v.optional(v.string()) },
  handler: async (ctx, { vid }): Promise<string | null> => {
    const userId = await getAuthUserId(ctx);
    if (!userId) throw new Error("Sign in first");

    const sent = vid && /^[A-Za-z0-9-]{8,64}$/.test(vid) ? vid : undefined;
    const visitor = await ctx.runMutation(internal.visitors.keep, {
      userId,
      vid: sent,
    });

    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
    const session = await stripe.checkout.sessions.create({
      client_reference_id: userId,
      metadata: visitor ? { virling_vid: visitor } : {},
      line_items: [{ price: "price_...", quantity: 1 }],
      mode: "subscription",
      success_url: "https://yourdomain.com/thanks",
    });

    return session.url;
  },
});

getAuthUserId reads the user from the token useAction sent. Stripe gets the Convex user ID as client_reference_id and the visitor ID as metadata.virling_vid; Virling looks at the metadata first. The Promise<string | null> return type is there because the action calls a function from the same generated api; without it, TypeScript can report a circular type.

Set the key with npx convex env set STRIPE_SECRET_KEY, which asks for the value. The pattern test on vid keeps anything that is not a visitor ID out of Stripe and the user document. A public action can be called by anyone who has your deployment URL, so choose the price in the action, not from an argument.

Without Convex Auth, drop the user lookup and the table and pass sent straight to metadata. If you use the @convex-dev/stripe component, pass metadata: { virling_vid: visitor } to createCheckoutSession. Its subscriptionMetadata goes to the Subscription, which Virling does not read. All the session fields are in the Stripe Checkout Session reference.

Test it with npx convex dev

Keep npx convex dev running: it type-checks the convex/ folder and pushes every change to your dev deployment. Set that deployment's STRIPE_SECRET_KEY to a Stripe test key and price_... to a test price. Internal functions can be run from the CLI, so you can try the mutation on its own from a second terminal:

npx convex run visitors:keep '{"userId":"USER_ID","vid":"vtest12345678"}'

Replace USER_ID with an _id from the users table in the Convex dashboard. It prints the ID it kept; run it again with another vid and it should still print the first one.

For the whole path, add data-dev to the script tag, because the script skips localhost without it. Sign in to your app on localhost, click the button, and open the new session in the Stripe Dashboard: virling_vid in its metadata should match window.virling.vid() in the console and the user's virlingVid in the dashboard. Virling still does not count localhost visits toward yourdomain.com, so this checks the ID, not the channel. Take data-dev off again before npx convex deploy.

Check it on production

Set the key on production with npx convex env set STRIPE_SECRET_KEY --prod and deploy with npx convex deploy. Sign up as a new user from a tagged link such as https://yourdomain.com/?utm_source=test&utm_medium=test, pay, wait for the next sync, and open the payments list at /app/yourdomain.com/payments. The payment should show the test source instead of Unattributed.

Virling only sees payments made in the mode of the key you connected: a restricted rk_test_ key for test payments, rk_live_ for live ones. Payments imported with a test key stay in your reports, so if you want only real ones, make a small live payment and refund it.

Usual mistakes

  • Calling Stripe from a mutation. Mutations cannot make network requests; only actions can.
  • Putting the mutation in the "use node" file. Convex rejects queries and mutations there, so keep them in another file.
  • Sending null. v.optional(v.string()) takes a string or no value, so leave the argument out when there is no ID.
  • Making the argument required. Checkout then fails for visitors who block the script.
  • Rendering the button outside ConvexAuthProvider. The action then gets no user and throws "Sign in first".
  • Setting STRIPE_SECRET_KEY on the dev deployment only. Dev and production keep separate environment variables.
  • Putting the ID in subscription_data.metadata, or on the customer or product. Virling does not read those.
  • Pasting the Stripe secret key into Virling. The action needs a key that can create sessions, while Virling refuses sk_ keys and asks for a restricted read-only one.

If a payment still shows as Unattributed, open its Checkout Session in the Stripe Dashboard. If virling_vid is missing there, check the argument your browser sends to the action and the user's virlingVid field.

Other frameworks

The same steps for other stacks:

Frequently asked questions

Can a Convex action read the virling_vid cookie?

No. The browser only sends that cookie to your own domain, and Convex functions run on your deployment's convex.cloud address. Read the ID in the browser with window.virling?.vid?.() and pass it to the action as an argument.

Can a Convex mutation create the Checkout Session?

No. Convex queries and mutations cannot make network requests, so they cannot call the Stripe API. Create the session in an action, and use an internal mutation from the action for the database work, such as saving the visitor ID.

Do I need to pass the UTM tags to Stripe?

No. The Virling script records the UTM tags of every visit against the visitor ID, so passing the ID is enough. Virling joins the payment to all the visits behind it, including untagged ones such as search and referrals.

Do I need a Stripe webhook in Convex for this?

Not for attribution. Virling reads charges and Checkout Sessions from Stripe with a restricted read-only key. Your app may still need a webhook to unlock the product after payment.

What happens if the visitor ID is missing?

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