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

Astro LemonSqueezy checkout: tie each order to its source

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

To see which traffic source each LemonSqueezy order from an Astro site came from, add the Virling script to your layout with is:inline, then make sure checkout carries the visitor ID as custom data named virling_vid. On a static site the script adds it to your checkout links in the browser, with no code. With server output, an endpoint reads the virling_vid cookie and sets it when it creates the checkout. LemonSqueezy returns it in its webhook, and Virling joins the order to every visit behind that ID, with the UTM tags of each.

For what LemonSqueezy does with custom data outside Astro, see the general guide to LemonSqueezy UTM tracking. Using Stripe instead? See Astro Stripe UTM tracking. On Next.js? See Next.js 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. If the tags never reach your landing page at all, a redirect is usually dropping them; see UTM parameters lost after redirect.

Step 1: add the script to your layout

Put the tag in the <head> of the layout every page uses. Mark it is:inline so Astro leaves the tag as it is instead of bundling it: the script reads its own attributes, which only works on the original tag. If you self-host, replace app.virling.com with your Virling server.

---
// src/layouts/Layout.astro
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <script is:inline defer src="https://app.virling.com/v.js"
      data-site="yourdomain.com"></script>
  </head>
  <body>
    <slot />
  </body>
</html>

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, static site: add the ID to the checkout link in the browser

If your Buy button is a link to STORE.lemonsqueezy.com/checkout/buy/VARIANT_ID, there is nothing to write. The script adds checkout[custom][virling_vid] to every such link when the page loads, and again when a visitor clicks one, and never replaces a value that is already there. LemonSqueezy reads any checkout[custom][...] query parameter as custom data. This works on a fully static build with no adapter:

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

If you build the URL in your own code, for example to pick a variant, add the ID yourself on click. A normal Astro <script> is bundled and runs once, so listen on the document and every button works, including ones that appear after a route change:

<button type="button" data-variant="VARIANT_ID">Buy now</button>

<script>
  document.addEventListener("click", (e) => {
    const btn = (e.target as HTMLElement).closest("[data-variant]");
    if (!btn) return;
    const url = new URL(
      "https://STORE.lemonsqueezy.com/checkout/buy/" + btn.getAttribute("data-variant"));
    const vid = window.virling?.vid?.();
    if (vid) url.searchParams.set("checkout[custom][virling_vid]", vid);
    location.href = url.href;
  });
</script>

TypeScript does not know window.virling, so declare it in src/env.d.ts or cast window to any on that line.

Step 2, server output: create the checkout in an endpoint

If you create checkouts with POST /v1/checkouts, for example to set a custom price or prefill the email, do it in an endpoint that runs on request: it needs a server adapter and prerender = false (or output: "server"). Read the cookie from cookies and set it in data.attributes.checkout_data.custom, as described in LemonSqueezy's create a checkout reference:

// src/pages/api/checkout.ts
import type { APIRoute } from "astro";

export const prerender = false;

export const POST: APIRoute = async ({ cookies, redirect }) => {
  const vid = 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 ${import.meta.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" } },
        },
      },
    }),
  });
  if (!res.ok) return new Response("Checkout failed", { status: 502 });
  const { data } = await res.json();
  return redirect(data.attributes.url, 303);
};

A plain form posts to it, and the browser sends the cookie along. The page with the form can stay prerendered:

<form method="POST" action="/api/checkout">
  <button type="submit">Buy now</button>
</form>

Read the cookie in the request that creates the checkout, never while a page renders. A prerendered or cached page has no cookie of this visitor, and a checkout URL baked into it would be shared by every buyer.

Step 3: 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 trial

View transitions, the overlay and renewals

View transitions. With <ClientRouter />, route changes go through the History API, and the script counts each change of path or query as one pageview. The visitor ID does not change: it lives in the cookie, not in the page, so it is the same on whichever page the buyer presses Buy. Checkout links that a route change swaps in were not there when the page first loaded, and get the ID when they are clicked.

The overlay checkout. Lemon.js opens the overlay from links with the lemonsqueezy-button class. The script handles the click before Lemon.js does, so the ID is on the link by the time the overlay reads it. After a view transition, Lemon.js has not seen the new links; call window.createLemonSqueezy() again, which LemonSqueezy says can be called multiple times:

<script>
  document.addEventListener("astro:page-load", () => window.createLemonSqueezy?.());
</script>

If you open the overlay from code with LemonSqueezy.Url.Open(url), the script never sees that URL: add checkout[custom][virling_vid] to it first, as in the button script above.

Renewals. Only the first order needs the visitor ID. Subscription invoices with billing reason renewal or updated, and any later order by the same customer, keep the channel of that customer's first order. If that order is older than Virling's first import, its renewals are usually Unattributed. See renewals.

Check that it works

Run one test order through the whole path:

  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 on your site. For the endpoint, put a test mode key in LEMONSQUEEZY_API_KEY too: test and live keys only work on their own side of the store. Deploy to your domain or a subdomain such as staging.yourdomain.com, since the script does nothing on localhost.
  3. Open a private window and visit the site through a tagged link, such as https://staging.yourdomain.com/?utm_source=test&utm_medium=email. Run window.virling.vid() in the browser console and note the ID. Click through to the pricing page, so a route change is part of the test.
  4. In the same window, press Buy 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.

The order shows the test source and the Email channel of your tagged visit instead of Unattributed. Open it and 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 order by the same customer is a renewal and keeps the first order's channel. Test orders stay in your reports after you replace the key with a live one. If a step fails, see test your setup.

Common mistakes

What you seeCauseFix
Nothing is recorded, though the script loadsThe tag has no is:inline and was bundled, so the script cannot find its data-siteAdd is:inline, as in step 1
Checkout works in astro dev and is a 404 after deployThe endpoint has no prerender = false, so no POST handler is deployedExport prerender = false and add a server adapter
The overlay stops opening after a route changeLemon.js looked for lemonsqueezy-button links before the new page was swapped inCall window.createLemonSqueezy() on astro:page-load
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
Every order is UnattributedVirling was not on a public https:// address when you connected, so the webhook is missingSet VIRLING_BASE_URL, then use Replace key
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

Orders without a visitor ID still count toward revenue, as Unattributed, for example when the script is blocked. Every other cause is in Unattributed revenue, and how the join works from visit to order is in how to track LemonSqueezy revenue by traffic source.

Frequently asked questions

How do I pass UTM parameters to LemonSqueezy checkout in Astro?

Pass the Virling visitor ID instead, as checkout[custom][virling_vid]. Links to STORE.lemonsqueezy.com get it from the script with no code. In an endpoint that creates the checkout, read the virling_vid cookie and set it in checkout_data.custom. The script records the UTM tags of every visit against that ID, so the order is joined to all of them.

Does a static Astro site need a server for LemonSqueezy attribution?

No. Checkout links work on a fully static site, because the script adds the visitor ID to them in the browser. A server endpoint is only needed if you create checkouts with the LemonSqueezy API.

Do view transitions change the visitor ID?

No. The ID lives in a first-party cookie, so it stays the same across route changes. Checkout links rendered after a route change get it when they are clicked.

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.

Which source do LemonSqueezy renewals get?

Invoices with billing reason renewal or updated, and any later order by the same customer, keep the channel of that customer's first order. Only the first order needs the visitor ID.

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