Supabase and Stripe UTM tracking: Checkout from an Edge Function
By Devendra Variya, co-founder of Virling. Published 2026-11-22, updated 2026-11-28.
If your app creates Stripe Checkout Sessions in a Supabase Edge Function, the virling_vid cookie does not reach that function: it runs on supabase.co, not on your domain. So read the visitor ID in the browser with window.virling?.vid?.(), send it in the request body, save it on the user's row, and pass it to the session as metadata.virling_vid. Stripe keeps that one ID, and Virling joins the payment to every visit behind it, with the UTM tags of each.
This is a common setup for apps made with AI builders. If you would rather hand the change to your coding assistant, the prompt is in track Stripe revenue in an AI-built app. For a server on your own domain, see Next.js Stripe UTM tracking. For Payment Links, metadata limits and where the values show up in Stripe, see the general guide to Stripe Checkout UTM parameters.
Before you start
Put the Virling script tag in the <head> of your app and read the visitor ID on the checkout click, as the guide to Stripe Checkout UTM parameters shows. Stripe keeps that ID on the session, and Virling matches it to the visits it recorded, with the UTM tags of each (link checkout to visits).
Call the function with functions.invoke
supabase.functions.invoke posts the body as JSON and adds the signed-in user's access token, which the function uses to find the user. Wait briefly for the deferred script and send null if it is blocked:
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 { data, error } = await supabase.functions.invoke("create-checkout", {
body: { vid: await visitorId() },
});
if (error) throw error;
window.location.href = data.url;
}Keep the visitor ID next to the auth user row
A signed-in user can start checkout days later, on another device, where the script has never seen them. If the Edge Function saves the first visitor ID it receives on the user's row, every later checkout can reuse it. Add a column to the table that has one row per auth.users entry, here profiles keyed by the auth user ID:
alter table public.profiles add column virling_vid text;
Row Level Security on the new column
The function writes the column with the service role key, which bypasses Row Level Security, so it needs no new policy. But policies apply to whole rows, not columns. If profiles has the usual "users can update their own profile" policy, a user can overwrite virling_vid from the browser with supabase-js. Postgres column privileges close that gap:
revoke update on public.profiles from anon, authenticated; grant update (full_name, avatar_url) on public.profiles to authenticated;
List the columns users may still edit in the grant, since the revoke takes away all of them. Your row policy still decides which rows they can update. If you would rather not touch grants, put virling_vid in a separate table with RLS on and no policies, which only the service role can reach (column level security).
Create the Checkout Session in the Edge Function
Edge Functions run on Deno, so packages come in through npm: specifiers, secrets through Deno.env.get, and the handler through Deno.serve. Stripe.createFetchHttpClient() makes the Stripe library use fetch, as Supabase's own Stripe examples do. The function finds the user from the token, takes the visitor ID from the row or else from the body, and saves the body's ID when the row has none:
// supabase/functions/create-checkout/index.ts
import Stripe from "npm:stripe";
import { createClient } from "npm:@supabase/supabase-js@2";
const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!, {
httpClient: Stripe.createFetchHttpClient(),
});
const admin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);
const cors = {
"Access-Control-Allow-Origin": "https://yourdomain.com",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
const reply = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), {
status,
headers: { ...cors, "Content-Type": "application/json" },
});
Deno.serve(async (req) => {
if (req.method === "OPTIONS") return new Response("ok", { headers: cors });
try {
const token = (req.headers.get("Authorization") ?? "").replace("Bearer ", "");
const { data: { user } } = await admin.auth.getUser(token);
if (!user) return reply({ error: "Sign in first" }, 401);
const { vid } = await req.json().catch(() => ({}));
const sent = typeof vid === "string" && /^[A-Za-z0-9-]{8,64}$/.test(vid)
? vid
: null;
const { data: profile } = await admin
.from("profiles").select("virling_vid").eq("id", user.id).maybeSingle();
const visitor = profile?.virling_vid ?? sent;
if (sent && !profile?.virling_vid) {
await admin.from("profiles").update({ virling_vid: sent }).eq("id", user.id);
}
const session = await stripe.checkout.sessions.create({
client_reference_id: user.id,
metadata: visitor ? { virling_vid: visitor } : {},
line_items: [{ price: "price_...", quantity: 1 }],
mode: "subscription",
success_url: "https://yourdomain.com/thanks",
});
return reply({ url: session.url });
} catch (err) {
console.error(err);
return reply({ error: "Checkout failed" }, 500);
}
});The Supabase user ID goes in client_reference_id and the visitor ID in metadata.virling_vid, which Virling reads first. Add the Stripe key with supabase secrets set STRIPE_SECRET_KEY=sk_... and ship it with supabase functions deploy create-checkout. SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are already set in deployed functions. The regular expression on vid stops anything that is not a visitor ID from reaching Stripe or the table.
For guest checkout without a signed-in user, skip the table: drop the user lookup and pass the body's ID as client_reference_id: sent ?? undefined. The full lookup order, including PaymentIntents you create for Elements, is in the Stripe docs and on the Stripe integration page.
CORS for the checkout function
Your page and the function live on different origins, and functions.invoke sends an Authorization header and a JSON body, so the browser first sends an OPTIONS preflight. The function answers it before it reads the token. Access-Control-Allow-Origin must match the page's origin exactly, www. included, and every response must carry the headers, because a 500 without them shows up in the browser as a CORS error that hides the real one. To allow a staging host too, compare the request's Origin against a short list and echo it back when it matches.
Test it locally with supabase functions serve
With the local stack running from supabase start, serve the function with hot reload:
supabase functions serve create-checkout
It reads secrets from supabase/functions/.env, so put a Stripe test key there as STRIPE_SECRET_KEY=sk_test_..., and sets SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY for the local stack itself. Point your app's Supabase client at the local API URL that supabase start printed, put your dev server's origin, such as http://localhost:5173, in Access-Control-Allow-Origin, and add data-dev to the script tag so it runs on localhost.
Sign up a local user, click checkout, and watch the terminal running serve: console.log output and errors print there. Open the local Studio to see the user's virling_vid in profiles, and the Stripe Dashboard to see it in the session's metadata. Virling does not count localhost visits, so this checks the ID, not the channel. Remove data-dev before you deploy.
Check it end to end
Run one test payment through the deployed path. Use a separate Supabase project for it: on the live project, a test key in STRIPE_SECRET_KEY would put your real buyers into test mode too.
- In Virling, connect a restricted Stripe key that starts with
rk_test_. Set your own test secret key on the test project withsupabase secrets set STRIPE_SECRET_KEY=sk_test_..., and use a price created in test mode. A new secret is read right away, without another deploy (environment variables). - Deploy the app on a subdomain of your domain, such as
staging.yourdomain.com, and put that origin inAccess-Control-Allow-Origin. Visits on a host other than your domain or its subdomains, such as a builder's preview, are dropped. - Open a private window and visit a page that runs the script through a tagged link, such as
https://staging.yourdomain.com/?utm_source=test&utm_medium=email. Runwindow.virling.vid()in the browser console and note the ID. - In the same window, sign up and start checkout. In the network tab, the body of the
create-checkoutrequest should hold the ID from step 3 asvid. Pay with the card4242 4242 4242 4242, any future date and any three-digit CVC (Stripe testing). - Check that
virling_vidin the session's metadata, in the Stripe Dashboard, and on the user'sprofilesrow, in the Table Editor, is the same ID. Errors from the deployed function are in its Logs tab (logging). - Wait a minute for the next sync, then open the payments list at
/app/yourdomain.com/payments. The payment shows thetestsource and the Email channel of your tagged visit instead of Unattributed. Open it to see its journey.
Sign up as a new user for each test: the function reuses the visitor ID already saved on a row, and if you also set customer, a later payment by the same customer is a renewal and keeps the first payment's channel. A site has one Stripe connection, and test payments stay in your reports after you replace the key with a live one. If a step fails, see test your setup.
Common mistakes
Open an Unattributed payment and look for Visitor under Details. If there is none, checkout did not carry the ID.
| What you see | Cause | Fix |
|---|---|---|
The function reads virling_vid from the Cookie header and gets nothing | The cookie belongs to your domain, and the function runs on supabase.co | Send the ID in the body of functions.invoke (link checkout to visits) |
| CORS error before the function runs | Access-Control-Allow-Origin is not exactly the origin of the page, such as with www. or on a staging host, or a header that the client sends is missing from the list | Set the exact origin. For the header list, with supabase-js 2.95.0 or later, import corsHeaders from npm:@supabase/supabase-js@^2/cors (CORS) |
| CORS error although the preflight passes | The function threw, for example on a wrong price ID, and the error response has no CORS headers | Read the function's logs, then catch the error and return it with the same headers (CORS) |
| 401, and the function logs nothing | verify_jwt is on by default, and the request has no valid token or key, such as a bare fetch | Call it with functions.invoke on a client made with this project's URL and key. Leave the check on (authorization headers) |
vid is null on the first click | window.virling is read before the deferred script has loaded | Wait for it with visitorId() from the functions.invoke section (read the visitor ID) |
vid is in the request, but not in Stripe | The body is read twice. The second req.json() fails, and the catch turns that into an empty object | Read the body once and take every field from it (Request.bodyUsed) |
error.message only says the function returned a non-2xx status | functions.invoke keeps the response in error.context | Read it with await error.context.json() when the error is a FunctionsHttpError (error handling) |
| The Stripe key is missing in one environment | Local functions read supabase/functions/.env, deployed ones read the project's secrets | Set it in both places (environment variables) |
| The payment has a visitor ID but is Unattributed | The visit was on a preview host or localhost, so it was not recorded | Test on your domain or a subdomain (script docs) |
| The visitor ID on the payment is a Supabase user ID | metadata.virling_vid was empty, so Virling fell back to client_reference_id, which holds the user ID | Check that the body carries vid and that the session gets metadata.virling_vid, which is read first (Stripe docs) |
profiles.virling_vid stays empty although vid arrives | The user has no profiles row, so the update matches nothing | Create the row at signup, for example with a trigger on auth.users (user data) |
| The function answers 401 with "Sign in first" | Checkout was started while signed out, so functions.invoke sent the anon key instead of a user token | Ask the user to sign in first, or use the guest variant described under the function code |
| A later checkout is credited to an older visit | The row already held a visitor ID, and the function keeps the first one on purpose | Nothing to fix: the payment is joined to the visits behind the first saved ID |
Every other cause is in Unattributed revenue. A payment made before a fix usually stays Unattributed, so make a new one to check.
Other frameworks
The same steps for other stacks:
- Next.js Stripe UTM tracking
- Firebase Stripe UTM tracking
- Convex Stripe UTM tracking
- React Stripe UTM tracking
- Express Stripe UTM tracking
- SvelteKit Stripe UTM tracking
- Remix Stripe UTM tracking
- Go Stripe UTM tracking
- Django Stripe UTM tracking
- Rails Stripe UTM tracking
- Laravel Stripe UTM tracking
Frequently asked questions
Does the virling_vid cookie reach a Supabase Edge Function?
No. The cookie is set on your domain, and the function runs on supabase.co, so the browser does not send it. 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?
With a signed-in user, put the Supabase user ID in client_reference_id and the visitor ID in metadata.virling_vid, which Virling reads first. For guest checkout, the visitor ID in client_reference_id alone is enough.
Can users change their own virling_vid under Row Level Security?
Yes, if a policy lets them update their own profiles row, because policies cover whole rows. Revoke update on the table from anon and authenticated and grant it back only on the columns users may edit, or keep the visitor ID in a table that only the service role can reach.
Do Stripe Payment Links need an Edge Function?
No. Use a normal link to buy.stripe.com on a page that runs the script. The script adds client_reference_id to the link when the page loads and again on click, unless the link already has one.
Why does my checkout Edge Function return a CORS error?
Either Access-Control-Allow-Origin is not exactly the origin of your page, such as www or a staging subdomain, or the function failed and its error response has no CORS headers. Check the function's logs, then return the same headers on every response, errors included.
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.