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

Next.js Stripe Checkout UTM tracking: pass the visit to the session

By Devendra Variya, co-founder of Virling. Published 2026-11-19, updated 2026-11-27.

In a Next.js app, the work happens in two places: next/script loads the Virling tag once in the root layout, and the route handler or server action that calls stripe.checkout.sessions.create() reads the virling_vid cookie and hands it to Stripe as client_reference_id. The sections below cover what Next.js changes about that: the script strategy, cookies() being async, the Pages Router, a proxy that rewrites headers, Embedded Checkout and static export.

Why one ID is enough, and what Payment Links and metadata limits look like in Stripe, is in the general guide to Stripe Checkout UTM parameters.

Load the tag with next/script

Put a Script in app/layout.tsx. The root layout is not re-rendered when the visitor moves between routes, so the tag loads once per tab, and the router's pushState calls are counted as pageviews. Extra props such as data-site go straight onto the generated <script> element. Self-hosted Virling users swap app.virling.com for their own server.

// app/layout.tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script src="https://app.virling.com/v.js"
          data-site="yourdomain.com" strategy="afterInteractive" />
      </body>
    </html>
  );
}

Keep afterInteractive. It runs right after hydration, so the cookie exists by the time anyone can press Buy. lazyOnload waits until the browser is idle, and a visitor who clicks a Payment Link on a busy first page can leave before the tag has added the ID. beforeInteractive blocks hydration for a tag that does not need it.

App Router: a route handler

A NextRequest exposes cookies synchronously through req.cookies. A POST handler is never cached, so it sees the cookie of the visitor who pressed the button even when the pricing page itself is static:

// app/api/checkout/route.ts
import { NextRequest, NextResponse } from "next/server";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(req: NextRequest) {
  const session = await stripe.checkout.sessions.create({
    client_reference_id: req.cookies.get("virling_vid")?.value,
    line_items: [{ price: "price_...", quantity: 1 }],
    mode: "subscription",
    success_url: "https://yourdomain.com/thanks",
  });
  return NextResponse.redirect(session.url!, 303);
}

The 303 turns the form's POST into a GET on checkout.stripe.com. Any <form action="/api/checkout" method="POST"> on any page can start it, with no client component.

App Router: a server action, with await

In a server action there is no request object, so use cookies() from next/headers. Since Next.js 15 it returns a promise, and Next.js 16 dropped the synchronous fallback, so code written for Next.js 14 as cookies().get(...) must become (await cookies()).get(...). This version leaves client_reference_id for your own user ID and puts the visitor in metadata.virling_vid, which Virling checks first:

// app/actions.ts
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function checkout(userId: string) {
  const vid = (await cookies()).get("virling_vid")?.value;
  const session = await stripe.checkout.sessions.create({
    client_reference_id: userId,
    metadata: vid ? { virling_vid: vid } : {},
    line_items: [{ price: "price_...", quantity: 1 }],
    mode: "subscription",
    success_url: "https://yourdomain.com/thanks",
  });
  redirect(session.url!);
}

Bind the user ID on the server, as in <form action={checkout.bind(null, user.id)}>. redirect() accepts an external URL, so the browser lands on Stripe. The full order in which Virling looks for the ID is in the Stripe docs.

Start free trial

Pages Router: an API route, not getServerSideProps

On the Pages Router, put the same Script in pages/_app.tsx and create the session in an API route, where req.cookies is a plain object:

// pages/api/checkout.ts
import type { NextApiRequest, NextApiResponse } from "next";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== "POST") return res.status(405).end();
  const session = await stripe.checkout.sessions.create({
    client_reference_id: req.cookies.virling_vid,
    line_items: [{ price: "price_...", quantity: 1 }],
    mode: "subscription",
    success_url: "https://yourdomain.com/thanks",
  });
  res.redirect(303, session.url!);
}

getServerSideProps can read context.req.cookies.virling_vid as well, but it runs on every view of the page, crawlers included, so a session created there is created for people who never meant to pay. Reading the cookie there just to print it into the page also gains nothing over reading it in the API route.

A proxy must pass the cookie through

The tag writes virling_vid in the browser, so your proxy (proxy.ts, called middleware.ts before Next.js 16) never has to set it. It can lose it, though. NextResponse.next({ request: { headers } }) replaces the headers that route handlers and server actions see, and a fresh Headers object has no Cookie header. Copy the incoming headers and change only what you need:

// proxy.ts
import { NextRequest, NextResponse } from "next/server";

export function proxy(req: NextRequest) {
  const headers = new Headers(req.headers); // keeps Cookie
  headers.set("x-pathname", req.nextUrl.pathname);
  return NextResponse.next({ request: { headers } });
}

Do not set a server cookie named virling_vid either, for example in an auth library's cookie list, or it will replace the visitor ID with a value Virling has never seen.

Embedded Checkout instead of a redirect

With Stripe Embedded Checkout the payment form opens inside your own page, and the server returns a client secret instead of a URL. It is still a Checkout Session, so the visitor ID goes in the same field. Set ui_mode to embedded_page and swap success_url for return_url:

// app/actions.ts
"use server";
import { cookies } from "next/headers";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function fetchClientSecret() {
  const session = await stripe.checkout.sessions.create({
    ui_mode: "embedded_page",
    client_reference_id: (await cookies()).get("virling_vid")?.value,
    line_items: [{ price: "price_...", quantity: 1 }],
    mode: "subscription",
    return_url: "https://yourdomain.com/thanks?session_id={CHECKOUT_SESSION_ID}",
  });
  return session.client_secret!;
}

A client component passes the server action to Stripe's React wrapper, which calls it when it mounts. The call is a POST from the browser, so the cookie goes with it:

// app/checkout/embedded.tsx
"use client";
import { loadStripe } from "@stripe/stripe-js";
import { EmbeddedCheckoutProvider, EmbeddedCheckout } from "@stripe/react-stripe-js";
import { fetchClientSecret } from "../actions";

const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);

export default function Embedded() {
  return (
    <EmbeddedCheckoutProvider stripe={stripePromise} options={{ fetchClientSecret }}>
      <EmbeddedCheckout />
    </EmbeddedCheckoutProvider>
  );
}

Every mount creates a session, so render this only on the checkout page, not in a shared layout. The redirect flow above is simpler when you do not need the form on your own page; Virling attributes both the same way.

Static export and cached routes

With output: "export", next build writes plain files and there is no Next.js server, so POST route handlers, server actions and cookies() are not available. Use Stripe Payment Links instead: the tag adds the visitor ID to every buy.stripe.com link on the page. If you need Checkout Sessions, create them in a small backend on your own domain, such as a Cloudflare Worker; a form that posts to it sends the cookie, because the tag stores it on your registrable domain.

On a server build, three settings hide the cookie: export const dynamic = "force-static" on the checkout route, a "use cache" function around the code that reads it, and reading it in a layout or page instead of the handler. More on caches in reading the visitor cookie in server code.

Try it on the dev server

The tag ignores localhost, so give the dev server a name under your domain: map dev.yourdomain.com to 127.0.0.1 in your hosts file, then run npm run dev -- -H dev.yourdomain.com. Open http://dev.yourdomain.com:3000/?utm_source=test&utm_medium=email in a private window, note the result of window.virling.vid() in the console, and pay with Stripe's test card 4242 4242 4242 4242 after connecting an rk_test_ key in Virling. A console.log(session.client_reference_id, session.metadata) after the create call shows the ID in the terminal, and the payment should appear under /app/yourdomain.com/payments with the Email channel a minute later. The full checklist is in test your setup.

Next.js problems that lose the ID

SymptomCause in Next.jsFix
cookies(...).get is not a function after an upgradeCode from Next.js 14 calls cookies() without awaitUse (await cookies()).get("virling_vid")
The handler gets no cookie, though the browser has itThe route exports dynamic = "force-static", or the proxy builds new request headersDrop the export; start from new Headers(req.headers) in the proxy
A static pricing page turned dynamicIts layout or page calls cookies() to pass the ID downRead the cookie only where the session is created
Build error about cookies() in "use cache"A cached function reads the requestRead the cookie outside it and pass the value in
Stripe shows sessions nobody startedA GET handler or getServerSideProps creates them, and prefetching or crawlers hit itCreate sessions in a POST handler or server action
Dev server refuses requests from dev.yourdomain.comNext.js serves dev assets only to known originsStart it with -H, or list the host in allowedDevOrigins
View source shows only a preload of v.jsafterInteractive inserts the tag after hydrationNothing; it is in the Elements panel
Two pageviews per route changeThe tag is in the root layout and also in a nested layout or tag managerKeep the one in the root layout

Causes that are not specific to Next.js, such as blocked scripts or consent, are listed in Unattributed revenue. Payments without an ID still count toward revenue.

Other frameworks

The same steps for other stacks:

Other payment providers on Next.js

The same idea when checkout runs on another provider:

Frequently asked questions

How do I pass UTM parameters to a Stripe Checkout Session in Next.js?

You pass one value instead of the tags: read virling_vid in the route handler or server action that creates the session and set it as client_reference_id. Virling already holds the UTM tags of each visit under that ID and joins them to the payment.

How do I read the virling_vid cookie in the App Router?

In a route handler, req.cookies.get("virling_vid")?.value on the NextRequest. In a server action or server component, (await cookies()).get("virling_vid")?.value with cookies imported from next/headers, which is async since Next.js 15.

Should I use client_reference_id or metadata.virling_vid?

If your Next.js app already sets client_reference_id to a user or team ID from your auth session, keep it and send the visitor as metadata.virling_vid. Otherwise client_reference_id alone is enough.

What happens if the cookie is missing?

The get call returns undefined, the Stripe library leaves the field out, and checkout works as before. The payment is counted as Unattributed revenue.

Do Stripe Payment Links in a Next.js app need code?

No server code. Render them as plain anchors or next/link elements pointing to buy.stripe.com on a page where the root layout loads the tag, and it adds client_reference_id to them.

Does this work with the Pages Router?

Yes. Load the tag with next/script in pages/_app.tsx, and in pages/api/checkout.ts read req.cookies.virling_vid when you create the Checkout Session.

Can I use this with output: "export" and no server?

Not with route handlers or server actions, which a static export does not include. Use Payment Links, which the tag fills in the browser, or create sessions in a separate backend on your own domain.

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