Next.js Dodo Payments UTM tracking: carry the visitor into checkout
By Devendra Variya, co-founder of Virling. Published 2026-11-23.
Dodo Payments gives a Next.js app two ways into checkout: a static payment link on checkout.dodopayments.com/buy/..., or a checkout session your server creates with the dodopayments SDK. Both accept metadata, and that is where the Virling visitor ID goes, as virling_vid. On a payment link it rides in the metadata_virling_vid query parameter; on a session it goes in the metadata object of client.checkoutSessions.create. Virling then reads metadata.virling_vid from each Dodo payment it imports.
Why bother: checkout happens on Dodo's domain, so a sale arrives in your reports as Direct unless something carries the visit across. The Virling script gives each visitor an ID and records the UTM tags of every visit against it, and Virling joins the payment to those visits through the ID. The full reference is in the Dodo Payments docs; the version without Next.js is Dodo Payments UTM tracking, and the Creem equivalent of this post is Next.js Creem UTM tracking.
Load the script in the root layout
Put it in app/layout.tsx through next/script, so every route runs it and client-side navigation is counted. In the Pages Router the same tag goes in pages/_app.tsx. Self-hosting Virling? Swap app.virling.com for your own server.
import Script from "next/script";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
<Script src="https://app.virling.com/v.js"
data-site="yourdomain.com" strategy="afterInteractive" />
</body>
</html>
);
}Payment links built in a client component
A payment link written straight into the page as <a href="https://checkout.dodopayments.com/buy/pdt_..."> needs nothing more. The script spots links to that host and appends metadata_virling_vid before the click goes through, unless the link already has one. That suits credit packs in an AI app, and Dodo Payments for AI apps covers how packs, plans and top-ups are credited after that.
Apps that pick the product at click time, say from a monthly and yearly toggle, build the URL in JavaScript, and the script never sees it as a link. Do it in a client component and append the parameter yourself, reading the ID from window.virling?.vid?.() inside the handler rather than during render:
// app/pricing/plan-button.tsx
"use client";
const PRODUCTS = { monthly: "pdt_monthly...", yearly: "pdt_yearly..." };
export default function PlanButton({ plan }: { plan: keyof typeof PRODUCTS }) {
function go() {
const url = new URL(`https://checkout.dodopayments.com/buy/${PRODUCTS[plan]}`);
url.searchParams.set("quantity", "1");
const vid = window.virling?.vid?.();
if (vid) url.searchParams.set("metadata_virling_vid", vid);
window.location.assign(url.href);
}
return <button onClick={go}>Choose {plan}</button>;
}Dodo turns every metadata_ query parameter into a metadata field, so metadata_virling_vid becomes metadata.virling_vid on the payment. With TypeScript, declare window.virling once in a global.d.ts, or cast it, so the build accepts the call.
Checkout sessions from a route handler
For carts, discounts or a customer you already know, create a checkout session instead. The virling_vid cookie sits on your own domain, so a POST from the buyer's browser to app/api/checkout/route.ts brings it along:
// app/api/checkout/route.ts
import { NextRequest, NextResponse } from "next/server";
import DodoPayments from "dodopayments";
const key = process.env.DODO_PAYMENTS_API_KEY!;
const client = new DodoPayments({
bearerToken: key,
environment: key.startsWith("dodo_test_") ? "test_mode" : "live_mode",
});
export async function POST(req: NextRequest) {
const vid = req.cookies.get("virling_vid")?.value;
const session = await client.checkoutSessions.create({
product_cart: [{ product_id: "pdt_...", quantity: 1 }],
return_url: "https://yourdomain.com/thanks",
metadata: vid ? { virling_vid: vid } : {},
});
if (!session.checkout_url) {
return NextResponse.json({ error: "no checkout url" }, { status: 502 });
}
return NextResponse.redirect(session.checkout_url, 303);
}A <form action="/api/checkout" method="POST"> with a submit button is enough to call it, and the 303 turns the form post into a plain navigation to Dodo. The SDK types checkout_url as nullable, hence the guard before the redirect. Each checkout_url is for one buyer, so never create the session while a page renders.
Live and test keys
Dodo keeps two separate worlds: each mode has its own API keys, products and webhooks, and a key used in the wrong one gets 401. Test keys start with dodo_test_ and live keys with dodo_live_. The SDK talks to live mode unless you pass environment: "test_mode", which is why the route handler above picks the mode from the key prefix. Product IDs differ between modes too, so keep them in environment variables next to the key.
Virling needs no mode setting either. Paste a key into the site's payment connection and it tries live.dodopayments.com, then test.dodopayments.com, and keeps whichever accepts it. Payments from the last 90 days come in on the first run, then new ones every minute, with refunds, disputes and renewals; Virling polls the API, so there is no Dodo webhook for your Next.js app to forward. A site holds one Dodo connection, and test payments remain in the reports after you move to a live key, so a staging site is a good home for test runs. The setup is on the Dodo Payments integration page.
Try a test payment
- Connect a
dodo_test_key to Virling, and put another test key inDODO_PAYMENTS_API_KEYwith a test mode product ID. - Deploy to a real host such as
staging.yourdomain.com; the script stays silent onlocalhost. - In a private window, land on
https://staging.yourdomain.com/?utm_source=test&utm_medium=emailand copy the result ofwindow.virling.vid()from the console. - Submit the checkout form, pay with one of Dodo's test cards, and give the payment a fresh email address.
- A minute later, the payment at
/app/yourdomain.com/paymentsshould show thetestsource and the Email channel, with your copied ID as Visitor under Details.
Use the checkout session route for this test. The script rewrites live links on checkout.dodopayments.com but not test mode payment links, so a test link stays Unattributed unless your code adds metadata_virling_vid. A repeat payment by the same email is a renewal and keeps the earlier channel. More checks are in test your setup, and the visit-to-payment join is explained in how to track Dodo Payments revenue by traffic source.
Common mistakes
Open an Unattributed Dodo payment and check Details for a Visitor. No visitor means the metadata never reached Dodo, and one of these is the usual reason.
| Symptom | Cause | Fix |
|---|---|---|
Links from PlanButton carry no visitor ID | The URL is built in code, and the script only rewrites <a href> elements | Set metadata_virling_vid in the click handler, as above |
window is not defined during the build | window.virling is read while the component renders, and client components are prerendered on the server too | Read it inside the click handler |
Dodo answers 401 | A dodo_test_ key reaches live mode, or a dodo_live_ key reaches test mode | Set environment from the key, as in the route handler |
| Dodo cannot find the product | The product ID belongs to the other mode | Keep a test and a live product ID per environment |
| Every buyer lands on the same Dodo checkout | The session is created in a page or a cached GET handler, and its checkout_url is served to everyone | Create it in the POST route handler, once per click |
The browser shows a CORS error on /api/checkout | fetch() follows the 303 to Dodo's domain | Use the form, or return checkout_url as JSON and navigate to it |
| Only some payments import | Only these product IDs is set in site settings and leaves products out | Add the missing product IDs, or clear the list |
| A test payment link is Unattributed | The script does not rewrite test mode links | Test through the checkout session route |
Other causes are listed in Unattributed revenue. Fixes apply to new payments, so check with a fresh one.
Frequently asked questions
How do I pass UTM parameters to Dodo Payments checkout in Next.js?
Pass the Virling visitor ID instead. In the route handler that calls client.checkoutSessions.create, read the virling_vid cookie and set metadata: { virling_vid }. The Virling script records the UTM tags of every visit against that ID, so the payment is joined to all of them.
Do Dodo payment links in a Next.js app need code?
Not when the link is a normal <a href> to checkout.dodopayments.com/buy on a page that runs the script; the script adds metadata_virling_vid itself. A link URL built in JavaScript needs the parameter set in your click handler.
How do I add the visitor ID to a payment link I build in a client component?
Read it on click with window.virling?.vid?.() and, when there is a value, set metadata_virling_vid on the URL before you send the buyer to it. window.virling only exists in the browser, so the file needs "use client".
Do I need a Dodo Payments webhook in my Next.js app?
No. Virling reads payments, refunds and subscriptions from the Dodo Payments API with an API key and checks for new payments every minute.
Should my Next.js app use a dodo_test_ or dodo_live_ key?
Use a dodo_test_ key with environment: "test_mode" and test products while you build, and a dodo_live_ key with live products in production. Virling detects the mode of the key you connect, so it needs no setting.
Can Virling import only the products this Next.js site sells?
Yes. When one Dodo account sells more than this site's products, list the site's product IDs in site settings, under Payment connections, in Only these product IDs. Virling then imports only payments, refunds and subscriptions for those products.
See which campaigns bring Dodo Payments 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.