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

Next.js LemonSqueezy UTM tracking: carry the visitor into checkout

By Devendra Variya, co-founder of Virling. Published 2026-11-23.

To tie a LemonSqueezy order from a Next.js app to the visit that brought it, load the Virling script once with next/script, then make sure checkout carries the visitor ID as checkout[custom][virling_vid]. Plain links to STORE.lemonsqueezy.com get it from the script with no code. A checkout URL you build in a client component, or a checkout your route handler creates, sets it in one line. LemonSqueezy returns it in its webhook, and Virling joins the order to every visit behind that ID, with the UTM tags of each.

This post covers the App Router and the Pages Router. For what LemonSqueezy does with custom data outside Next.js, see the general guide to LemonSqueezy UTM tracking. Using Stripe instead? See Next.js Stripe UTM tracking. On a Laravel backend? See LemonSqueezy UTM tracking with Laravel. On SvelteKit, see SvelteKit LemonSqueezy UTM tracking.

Why LemonSqueezy checkout loses your UTM tags

UTM tags live on the landing URL. By the time a visitor clicks Buy they are usually a few pages in, and checkout runs on your store's lemonsqueezy.com address, so nothing from your site travels with them unless it is in the checkout URL or request. Passing one visitor ID instead of the tags keeps earlier visits and untagged ones, such as search and referrals, too.

Step 1: add the script once

Use next/script with strategy="afterInteractive" and load it once, so it runs on every route. defer does nothing on next/script, so leave it out. Client-side navigation is counted too. If you self-host, replace app.virling.com with your Virling server.

App Router, in app/layout.tsx:

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

Pages Router, in pages/_app.tsx:

import Script from "next/script";

export default function App({ Component, pageProps }) {
  return (
    <>
      <Script src="https://app.virling.com/v.js"
        data-site="yourdomain.com" strategy="afterInteractive" />
      <Component {...pageProps} />
    </>
  );
}

The script sets the first-party virling_vid cookie on your domain, records the UTM tags of each visit against it, and window.virling?.vid?.() returns the same ID in the browser.

Step 2: checkout links need no code

If your Buy button is a link to STORE.lemonsqueezy.com/checkout/buy/VARIANT_ID, you are done. The script adds checkout[custom][virling_vid] to every such link when the page loads, and again when a visitor clicks one, so links rendered later by React or after a route change are covered too. It never replaces a value that is already there. A plain <a href> or next/link both render a normal link:

<a href="https://STORE.lemonsqueezy.com/checkout/buy/VARIANT_ID">Buy now</a>

Step 3: build the URL in a client component

If you build the checkout URL in your own code, for example to pick a variant, do it in a client component, since window.virling only exists in the browser. Read the ID on click, after the script has loaded:

// app/buy-button.jsx
"use client";

export default function BuyButton() {
  function buy() {
    const url = new URL("https://STORE.lemonsqueezy.com/checkout/buy/VARIANT_ID");
    const vid = window.virling?.vid?.();
    if (vid) url.searchParams.set("checkout[custom][virling_vid]", vid);
    location.href = url.href;
  }
  return <button onClick={buy}>Buy now</button>;
}

The same component works in the Pages Router without the "use client" line.

Or create the checkout in a route handler

If your server creates the checkout with POST /v1/checkouts, read the visitor's virling_vid cookie from the request and set it in data.attributes.checkout_data.custom:

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

export async function POST(req: NextRequest) {
  const vid = req.cookies.get("virling_vid")?.value;
  const res = await fetch("https://api.lemonsqueezy.com/v1/checkouts", {
    method: "POST",
    headers: {
      accept: "application/vnd.api+json",
      "content-type": "application/vnd.api+json",
      authorization: `Bearer ${process.env.LEMONSQUEEZY_API_KEY}`,
    },
    body: JSON.stringify({
      data: {
        type: "checkouts",
        attributes: { checkout_data: { custom: vid ? { virling_vid: vid } : {} } },
        relationships: {
          store: { data: { type: "stores", id: "STORE_ID" } },
          variant: { data: { type: "variants", id: "VARIANT_ID" } },
        },
      },
    }),
  });
  const { data } = await res.json();
  return NextResponse.json({ url: data.attributes.url });
}

The browser then sends the buyer to the returned url. In the Pages Router, do the same in an API route under pages/api/ and read the cookie as req.cookies.virling_vid. LemonSqueezy's reference for the request is create a checkout.

Step 4: connect LemonSqueezy

Create an API key in LemonSqueezy under Settings, API, and paste it into Virling. LemonSqueezy only returns checkout custom data in webhooks, so Virling registers a webhook on each of your stores for order_created and subscription_payment_success and checks each request's X-Signature. The webhook needs VIRLING_BASE_URL to be a public https:// address; without one, LemonSqueezy payments show as Unattributed. The full setup is in the LemonSqueezy docs and on the LemonSqueezy integration page.

Start free

When the order still shows as Unattributed

Two things break this most often in a Next.js app.

  • The tags are gone before the script runs. A redirect that rebuilds the URL from the path alone, such as a middleware locale redirect or a redirects rule from / to /home, drops ?utm_source=... and the visit arrives as Direct. Carry the query string through every redirect; the causes and fixes are in UTM parameters lost after redirect.
  • The overlay is opened from code. A Lemon.js overlay opened from a link with the lemonsqueezy-button class is still a normal link, and the script adds the ID before the overlay reads it. If you call LemonSqueezy.Url.Open(url) yourself, the script never sees that URL: add checkout[custom][virling_vid] to it first, as in step 3.

Check your landing links with the UTM builder too, so a stray # or a duplicate parameter is not the cause.

Check that it works

  1. Switch your LemonSqueezy store to test mode, create an API key there and connect it, so Virling reads test orders and registers its webhook in test mode. Virling must be on a public https:// address.
  2. Use a test mode checkout link in your app. For the route handler, put a test mode key in LEMONSQUEEZY_API_KEY too: test and live keys only work on their own side of the store.
  3. Open a private window and visit a page that runs the script through a tagged link, such as https://yourdomain.com/?utm_source=test&utm_medium=email. Run window.virling.vid() in the browser console and note the ID. The script does nothing on localhost, so use your domain or a subdomain such as staging.yourdomain.com.
  4. In the same window, click the checkout link or button and pay with one of the test cards LemonSqueezy lists.
  5. Wait a minute for the next sync, then open the payments list at /app/yourdomain.com/payments.

What the order looks like: in the list it shows the test source and the Email channel of your tagged visit instead of Unattributed. Open it and Credited to shows the same, Journey starts at the tagged visit and ends with the LemonSqueezy order, and Details lists the ID from your browser console as Visitor.

Use a new email address for each test, because a later payment by the same customer is a renewal and keeps the first payment's channel. A site has one LemonSqueezy connection, and test orders stay in your reports after you replace the key with a live one. If the order lists no visitor ID, checkout did not carry virling_vid: check that the page with the button loads the script. The full checklist is in test your setup.

Orders without a visitor ID still count toward revenue, as Unattributed. How the join works from visit to order is in how to track LemonSqueezy revenue by traffic source.

Common mistakes

Start from an Unattributed order. Open it from /app/yourdomain.com/payments and look for Visitor under Details. If there is none, checkout did not carry the ID. The table lists what usually goes wrong in an App Router app.

SymptomCauseFix
window is not defined during the buildA client component reads window.virling while it renders. Client components are prerendered on the server tooRead it in the click handler, as in step 3
The overlay opens on the first page, but not after a route changeLemon.js looked for lemonsqueezy-button links before your component renderedCall window.createLemonSqueezy() in useEffect, once Lemon.js is loaded (Lemon.js with frameworks)
Orders opened with LemonSqueezy.Url.Open are UnattributedThe URL goes straight to Lemon.js, so the script never sees a linkAdd checkout[custom][virling_vid] to it first, as in step 3
data.attributes is undefined in the route handlerLemonSqueezy answered with an errors array, for example because the key is wrongCheck res.ok and log the errors before you read data
Checkout breaks after you go liveA product copied to live mode gets a new ID and checkout URLChange the links, VARIANT_ID and the API key to the live ones
No payment has a visitor ID, and every buyer gets the same checkoutThe request to LemonSqueezy runs in a GET handler with dynamic = "force-static", where cookies are empty and the response is cachedCreate it in a POST handler. Only GET handlers can be cached
An error about cookies() inside use cacheCached functions cannot read cookiesRead the cookie outside the cached function, and do not cache the one that creates the checkout
The server action fails with cookies(...).get is not a functioncookies() is async, and Next.js 16 removed synchronous accessWrite (await cookies()).get("virling_vid")?.value
A server action creates the checkout, but the buyer stays on the pageredirect() is inside a try block. It works by throwing an error, which your catch swallowsCreate the checkout inside try and call redirect() after it
Several buyers share one visitor ID, or have noneThe checkout is created while a page renders, and a prerendered or cached page gives its URL to everyoneCreate it in the route handler, when the buyer presses Buy
The checkout route or server action fails in a static exportWith output: "export", server actions, cookies and handlers that read the request are not supportedUse checkout links or the client component, as in steps 2 and 3
Every order is UnattributedVirling was not on a public https:// address when you connected, so the webhook is missingSet VIRLING_BASE_URL, restart Virling, then use Replace key
A test on localhost carries no visitor IDThe script does nothing on localhost, so there is no cookie to readTest on your domain or a subdomain of it
A second test keeps the first test's channelAny later order by the same customer is a renewalUse a new email address for each test

Every other cause is in Unattributed revenue. A payment made before a fix usually stays Unattributed, so make a new one to check.

Frequently asked questions

How do I pass UTM parameters to LemonSqueezy checkout in Next.js?

Pass the Virling visitor ID instead, as checkout[custom][virling_vid]. Links to STORE.lemonsqueezy.com get it from the script with no code. For a URL you build in a client component, add it from window.virling?.vid?.(). The script records the UTM tags of every visit against that ID, so the order is joined to all of them.

Do I need a client component?

Only if you build the checkout URL yourself. window.virling only exists in the browser, so mark that file with "use client" and read the ID on click. Plain checkout links and checkouts created on the server need none.

How do I set the visitor ID on a checkout created on my server?

Read the virling_vid cookie in the route handler, with req.cookies.get("virling_vid")?.value, or req.cookies.virling_vid in a Pages Router API route, and set data.attributes.checkout_data.custom to { virling_vid: ... } in POST /v1/checkouts.

Does it work with the Lemon.js overlay?

Yes, when the overlay opens from a link with the lemonsqueezy-button class: the script adds the ID to the link before the overlay reads it. If you call LemonSqueezy.Url.Open yourself, add checkout[custom][virling_vid] to the URL first.

Why can I not see virling_vid on my orders in LemonSqueezy?

LemonSqueezy only returns checkout custom data in webhooks, not when you read orders from the API. Virling registers a webhook for order_created and subscription_payment_success when you connect, which needs a public https address.

Does LemonSqueezy test mode work with Virling?

Yes. Connect an API key created in test mode: Virling reads test orders and registers its webhook in test mode. Test orders stay in your reports after you replace the key with a live one.

See which campaigns bring LemonSqueezy orders

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 See the demo