Polar Next.js checkout metadata: UTM tracking for each order
By Devendra Variya, co-founder of Virling. Published 2026-11-23, updated 2026-11-26.
To tie each Polar order from a Next.js app to the channel that brought the buyer, load the Virling script in app/layout.tsx, then read its virling_vid cookie with cookies() in the route handler or server action that calls polar.checkouts.create, and set it in metadata. Plain links to buy.polar.sh need no code at all. If you use Polar's @polar-sh/nextjs adapter, wrap its Checkout handler so it adds the cookie to the checkout's metadata.
Polar checkout runs on Polar's domain, so the UTM tags of your landing page never reach the order unless you pass a visitor ID into checkout. Why a visitor ID beats copied tags, how checkout links get one with no code, and what Virling reads from each order are in the general guide to Polar UTM tracking; this post only covers the App Router. Using Stripe instead? See Next.js Stripe UTM tracking. On Nuxt instead? See Nuxt Polar UTM tracking.
Step 1: load the script in the root layout
Use next/script with strategy="afterInteractive" in app/layout.tsx, so it loads once and keeps counting visits across client-side route changes. If you self-host, replace app.virling.com with your Virling 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>
);
}A checkout link to buy.polar.sh rendered with <a href> or next/link is a normal link, so the script tags it and you can stop here. The rest of this post is for checkout sessions your server creates.
Route handler or server action
Both run on the server for each request and both see the cookie, because the browser sends it with any request to your own domain. Pick by where the Buy button lives:
| Route handler | Server action | |
|---|---|---|
| File | app/api/checkout/route.ts | A "use server" function, for example in app/actions.ts |
| Called by | Any form, link or fetch() that reaches its URL | A form or component in your own Next.js app |
| Reads the cookie with | req.cookies.get("virling_vid") or cookies() | cookies() from next/headers |
| Sends the buyer to Polar with | NextResponse.redirect(checkout.url, 303) | redirect(checkout.url) from next/navigation |
| Use it when | The button is outside React, or you want one URL for every page, as the adapter does | The button is in a React component and you want no API route |
Step 2a: a route handler
// app/api/checkout/route.ts
import { NextRequest, NextResponse } from "next/server";
import { Polar } from "@polar-sh/sdk";
const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN });
export async function POST(req: NextRequest) {
const checkout = await polar.checkouts.create({
products: ["PRODUCT_ID"],
successUrl: "https://yourdomain.com/thanks",
metadata: { virling_vid: req.cookies.get("virling_vid")?.value },
});
return NextResponse.redirect(checkout.url, 303);
}Post to it from a plain form, so the browser follows the redirect itself:
<form action="/api/checkout" method="POST"> <button type="submit">Buy</button> </form>
Use POST, not GET: a GET handler can be cached, and a cached response hands the same checkout to every buyer.
Step 2b: a server action
// app/actions.ts
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { Polar } from "@polar-sh/sdk";
const polar = new Polar({ accessToken: process.env.POLAR_ACCESS_TOKEN });
export async function buy() {
const vid = (await cookies()).get("virling_vid")?.value;
const checkout = await polar.checkouts.create({
products: ["PRODUCT_ID"],
successUrl: "https://yourdomain.com/thanks",
metadata: { virling_vid: vid },
});
redirect(checkout.url);
}Then use it from any component, server or client: <form action={buy}><button>Buy</button></form>. Keep redirect() outside any try block, because it works by throwing.
Reading cookies() in server code
cookies() is async since Next.js 15, and Next.js 16 removed the synchronous form, so write (await cookies()).get("virling_vid")?.value. Three more rules apply to the visitor cookie in particular:
- Read it when the buyer clicks, not while a page renders. The script sets the cookie in the browser after the first page loads, so a server component on the first page view sees no cookie. A checkout created during render is also baked into any prerendered or cached copy of that page.
- Do not read it inside
use cache. Cached functions cannot callcookies(). Read it outside and do not cache the function that creates the checkout. - Keep the handler on your own domain. The cookie belongs to your site, so a checkout API on another domain never receives it.
With output: "export" there is no server to read cookies, so use plain checkout links. More cases are in reading the visitor cookie in server code.
Step 2c: with the Polar Next.js adapter
Polar publishes @polar-sh/nextjs, whose Checkout helper returns a GET route handler. It creates the checkout from the query string, such as /checkout?products=PRODUCT_ID, and takes metadata only as a JSON metadata parameter. It has no option to read a cookie, so wrap it and set that parameter from the cookie on the server:
// app/checkout/route.ts
import { Checkout } from "@polar-sh/nextjs";
import { NextRequest } from "next/server";
const checkout = Checkout({
accessToken: process.env.POLAR_ACCESS_TOKEN!,
successUrl: process.env.SUCCESS_URL,
});
export async function GET(req: NextRequest) {
const url = new URL(req.url);
const vid = req.cookies.get("virling_vid")?.value;
if (vid) url.searchParams.set("metadata", JSON.stringify({ virling_vid: vid }));
return checkout(new NextRequest(url));
}Link to it with a normal <a href="/checkout?products=PRODUCT_ID">. The script does not tag links to your own /checkout route, so without the wrapper these orders carry no visitor ID. Reading the cookie also keeps this GET handler from being cached.
Step 3: connect Polar
Paste an Organization Access Token with read access to orders and refunds into Virling, as described in the Polar docs. It is a different token from the POLAR_ACCESS_TOKEN your app uses, which needs checkouts:write. Nothing else changes in your Next.js app: there is no webhook route to add.
Check it in the sandbox
- Connect a sandbox token to Virling.
- In your app, put a sandbox token in
POLAR_ACCESS_TOKEN, use a sandbox product ID, and addserver: "sandbox"tonew Polar(). - Deploy to your domain or a subdomain such as
staging.yourdomain.com. The script does nothing onlocalhost, sonext devnever gets a cookie. - In a private window, open a page through
?utm_source=test&utm_medium=email, press Buy and pay with a test card. - A minute later, open
/app/yourdomain.com/payments: the payment shows thetestsource instead of Unattributed.
When a Next.js order has no visitor ID
| Symptom | Cause | Fix |
|---|---|---|
| Every buyer gets the same checkout | The checkout is created in a cached GET handler or while a page renders | Create it in a POST handler or a server action, when the buyer clicks |
cookies(...).get is not a function | cookies() is async | Write (await cookies()).get("virling_vid") |
| The server action creates a checkout, but the buyer stays on the page | redirect() is inside try, and catch swallows it | Call redirect() after the try block |
A CORS error on /api/checkout | A client component calls fetch(), which follows the redirect to Polar's domain | Post a form, or return checkout.url as JSON and set location.href |
| Adapter orders are all Unattributed | The adapter route is used without the wrapper | Wrap Checkout as in step 2c |
Causes that apply to every stack, such as renewals, sandbox links and consent, are in Polar UTM tracking and Unattributed revenue.
Frequently asked questions
How do I pass UTM parameters to a Polar checkout in Next.js?
Pass the Virling visitor ID instead. In the route handler or server action that calls polar.checkouts.create, read the virling_vid cookie with cookies() and set metadata: { virling_vid }. The Virling script records the UTM tags of every visit against that ID, so the order is joined to all of them.
Should I use a route handler or a server action for Polar checkout?
Either works, since both run on the server and receive the cookie. Use a server action when the Buy button is in a React component, and a POST route handler when you need a URL that any form or page can post to.
Does the @polar-sh/nextjs adapter pass the visitor ID?
Not by itself. Its Checkout handler only takes metadata from the query string, so wrap it in your own GET handler that reads the virling_vid cookie and sets the metadata parameter before calling it.
Why is the cookie empty in my server component?
On a buyer's first page view the script has not set it yet, because it runs in the browser after the page loads. Read the cookie when the buyer clicks Buy, in a route handler or server action.
Do I need a Polar webhook in my Next.js app?
No. Virling reads orders from the Polar API with an organization access token and checks for new orders every minute.
See which campaigns bring Polar 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.