How to A/B test prices in Astro

Price testing in Astro: render the pricing page on demand, set the price cookie in page frontmatter, and charge it from an API endpoint with Stripe.

Short answer

Mark the pricing page with export const prerender = false, call getPrice() in its frontmatter with Astro.request, and append each Set-Cookie value to Astro.response.headers there, since components can't change headers once streaming starts. Create the Stripe Checkout session in an on-demand API endpoint that prices again and passes quote.metadata whole.

  • Astro prerenders every page by default, so a pricing page without export const prerender = false bakes one price into the build for everyone.
  • Set the cookie in the page's frontmatter: by the time a component or layout runs, Astro has already sent the response headers.
  • Read the key through astro:env with access: secret, so it never lands in the client bundle.
  • On Cloudflare, flush through Astro.locals.cfContext.waitUntil(); on the Node adapter, the SDK sends events by itself.

Astro builds every page to static HTML unless you say otherwise, and a static page can show only one price. So an Astro price test starts with export const prerender = false on the pricing page. The second rule is about timing: the cookie that keeps each visitor's price has to be set in the page's frontmatter, because Astro streams HTML and has already sent the headers by the time a component runs (on-demand rendering).

This guide uses Astro 7 with a server adapter, the Leverprice SDK and Stripe Checkout. Server-side price testing covers why the price must come from a server. If your Astro site has no server at all, no-code mode tests prices through hosted checkout links instead, with one limit: the page itself can't show the tested price.

How do you install Leverprice in Astro?

Add an adapter so pages can render on demand (Node here; Vercel, Netlify and Cloudflare work the same way), then the SDK and Stripe:

Terminal
npx astro add node
npm install @leverprice/sdk stripe

Declare the keys as server secrets in astro.config.mjs:

astro.config.mjs
import node from "@astrojs/node";
import { defineConfig, envField } from "astro/config";

export default defineConfig({
  adapter: node({ mode: "standalone" }),
  env: {
    schema: {
      LEVERPRICE_SECRET_KEY: envField.string({ context: "server", access: "secret", optional: true }),
      STRIPE_SECRET_KEY: envField.string({ context: "server", access: "secret", optional: true }),
    },
  },
});
.env
LEVERPRICE_SECRET_KEY=pp_sk_test_…
STRIPE_SECRET_KEY=sk_test_…

Secret server variables stay out of your final bundle (environment variables). The Leverprice key is optional on purpose: without it, the SDK serves your fallback price instead of failing the build. The test key comes from the dashboard when you create a project, and the docs list the SDK's options.

Create the clients once, in a module the page and the endpoint share:

src/lib/leverprice.ts
import { Leverprice } from "@leverprice/sdk";
import { LEVERPRICE_SECRET_KEY, STRIPE_SECRET_KEY } from "astro:env/server";
import Stripe from "stripe";

export const leverprice = new Leverprice({
  secretKey: LEVERPRICE_SECRET_KEY,
  products: {
    pro: { currency: "usd", fallbackPrice: 1900, minPrice: 1500, maxPrice: 3900 },
  },
});

export const stripe = new Stripe(STRIPE_SECRET_KEY!);

export function formatPrice({ price, currency }: { price: number; currency: string }) {
  const format = new Intl.NumberFormat("en-US", { style: "currency", currency });
  const digits = format.resolvedOptions().maximumFractionDigits ?? 2;
  return format.format(price / 10 ** digits);
}

fallbackPrice is what everyone sees when Leverprice is off, slow (no config within 500 ms) or down, and getPrice() never throws for those reasons. minPrice and maxPrice are hard limits checked on your server. Prices are minor units: 1900 is $19.00.

Why must the pricing page render on demand?

Because a prerendered page runs its frontmatter once, at build time, with no visitor attached. Whatever price that build draws ships to everyone, and no cookie is ever set. Astro prerenders the whole site by default; with an adapter installed, export const prerender = false switches a single page or endpoint to rendering per request, and the rest of the site stays static.

If most of your site is dynamic, you can flip the default with output: "server" and mark static pages with prerender = true instead. Either way, the pricing page and the checkout endpoint must render per request.

Ask for the price at the top of the page, before any HTML:

src/pages/pricing.astro
---
import { formatPrice, leverprice } from "../lib/leverprice";

export const prerender = false;

const quote = await leverprice.getPrice("pro", { request: Astro.request });
for (const cookie of quote.setCookie) Astro.response.headers.append("Set-Cookie", cookie);
Astro.response.headers.set("Cache-Control", "private, no-store");
---

<h1>Pro</h1>
<p>{formatPrice(quote)}</p>
<form method="post" action="/api/checkout">
  <button type="submit">Buy Pro</button>
</form>

Astro.request is the standard Request, so the SDK reads the visitor's cookie and user agent from it. Astro.response.headers is a real Headers object, and appending keeps the SDK's cookie attributes exactly as they came. Astro.cookies.set() would work too, but you'd have to unpack each header into options first.

Keep this code in the page. Astro allows response headers to be changed only at the page level, never in components or layouts, because it has already sent the headers by the time those run. A pricing component that calls getPrice() for itself still renders a price, but its cookie never reaches the browser, so the next request draws again.

Cache-Control: private, no-store keeps CDNs and browsers from serving one visitor's price to another.

How do you charge the price from an API endpoint?

The buy form posts to an on-demand endpoint that prices the visitor again and creates the Stripe session:

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

export const prerender = false;

export const POST: APIRoute = async ({ request, url }) => {
  const quote = await leverprice.getPrice("pro", { request }); // never trust a price from the form

  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: [
      {
        quantity: 1,
        price_data: { currency: quote.currency, unit_amount: quote.price, product_data: { name: "Pro" } },
      },
    ],
    metadata: quote.metadata, // signed attribution: pass it whole
    payment_intent_data: { metadata: quote.metadata },
    success_url: `${url.origin}/thanks`,
    cancel_url: `${url.origin}/pricing`,
  });

  const headers = new Headers({ Location: session.url! });
  for (const cookie of quote.setCookie) headers.append("Set-Cookie", cookie);
  return new Response(null, { status: 303, headers });
};

The endpoint needs its own prerender = false; a prerendered endpoint becomes a static file that can't answer a POST. Building the 303 response by hand lets you append the cookies, and the visitor's cookie maps them to the same variant, so Stripe shows the amount the page showed.

price_data makes a one-off price from quote.price, with unit_amount in minor units (Checkout Sessions API). Pass quote.metadata whole, on the session and the payment intent: it's the signed record of which price this visitor saw. Polar, Lemon Squeezy and Dodo Payments take the same quote through their own custom-price fields, namely ad-hoc prices on a Polar checkout, custom_price on a Lemon Squeezy checkout (metadata in checkout_data.custom) and amount on a Dodo Payments pay-what-you-want product. The Stripe, Polar, Lemon Squeezy and Dodo Payments pages show each call. Lemon Squeezy stops processing payments on March 31, 2027 (announcement).

How does verified revenue work?

Stripe sends signed webhooks straight to Leverprice, so your Astro project needs no webhook endpoint for the test. In the dashboard, open Payments and connect Stripe in Test mode. In Stripe, add the URL it shows as a webhook endpoint for checkout.session.completed, checkout.session.async_payment_succeeded and charge.refunded, then paste the endpoint's signing secret back into Leverprice.

That secret lets Leverprice confirm events but can't charge, refund or read customers, so an API key never goes there. Refunds reduce the revenue of the price that sold. Stripe verification covers one-time payment sessions, which is what the endpoint above creates.

The page asks for the price on your server, the endpoint charges it, and Stripe confirms the sale.

How do regional prices work in Astro?

Regional prices (SDK 0.4 or later) charge each country its own price; during a test, each visitor keeps one variant at that variant's price for their country. The country comes from a header your adapter's platform sets: x-vercel-ip-country on Vercel, cf-ipcountry on Cloudflare.

src/lib/leverprice.ts
export const leverprice = new Leverprice({
  secretKey: LEVERPRICE_SECRET_KEY,
  countryHeader: "cf-ipcountry", // set by Cloudflare, never by the visitor
  products: {
    pro: {
      currency: "usd",
      fallbackPrice: 1900,
      minPrice: 1500,
      maxPrice: 3900,
      // Currencies you can charge in, each with its own hard bounds. The dashboard writes this block for you.
      regional: {
        usd: { minPrice: 800, maxPrice: 4900 },
        eur: { minPrice: 1100, maxPrice: 6000 },
        inr: { minPrice: 48000, maxPrice: 230000 },
      },
    },
  },
});

There's deliberately no default, since a header the visitor controls would let them pick their own price. The page and the endpoint both pass the request, so they read the country without other changes, and the endpoint already sends quote.currency to Stripe. Bots, unknown countries and currencies you didn't list get the standard price. Regional pricing explains how each country's price is set.

How do you test it locally?

  1. Run npm run dev and open http://localhost:4321/pricing in Chrome or Firefox. The document response should set a __pp cookie, and the price should sit inside your range.
  2. Reload: the price holds. A private window is a new visitor and may get another price.
  3. Run curl -i http://localhost:4321/pricing. Command-line clients count as bots, so you get the standard price and no Set-Cookie.
  4. Click Buy and pay on Stripe's test page with 4242 4242 4242 4242 (Stripe testing). The amount equals the page's, and the order arrives in Leverprice as verified test revenue.
  5. Restart with LEVERPRICE_DISABLED=1 npm run dev. Everyone gets the fallback price, with no cookie and no network calls.
  6. Run npm run build and check that /pricing isn't among the prerendered pages. If it is, the prerender export is missing or misspelled.

The dashboard's Install page shows Connected after your server's first request, marked test mode only until a live key is used.

What changes when you deploy?

Switch to the live keys (pp_sk_live_… and Stripe's live key) in the host's environment and connect a Live-mode webhook endpoint; test and live data never mix. Sending queued events depends on the adapter:

AdapterSending queued events
@astrojs/nodeLong-lived server: the SDK's timer sends them
@astrojs/vercel, @astrojs/netlifyAdd await leverprice.flush() after getPrice() in the page and the endpoint; with nothing queued it makes no network call
@astrojs/cloudflareAstro.locals.cfContext.waitUntil(leverprice.flush()) in the page, locals.cfContext.waitUntil(…) in the endpoint

On Cloudflare, add the secrets with the Wrangler CLI and keep local values in .dev.vars; the adapter's variables work with astro:env, so the module above runs unchanged (Cloudflare adapter). To turn the test off in an emergency, set LEVERPRICE_DISABLED=1 and redeploy: every visitor gets your fallback price.

Troubleshooting

SymptomLikely causeFix
Everyone sees the same price and no __pp cookie appearsThe page was prerendered at build timeAdd export const prerender = false to the page
The price shows, but no cookie is setgetPrice() runs inside a component or layout, after the headers were sentMove it, and the cookie loop, into the page's frontmatter
The checkout form gets a 404 or 405 in productionThe endpoint was prerendered or doesn't export POSTAdd export const prerender = false and export POST
Everyone gets the fallback price in productionLEVERPRICE_SECRET_KEY is optional and was never set thereSet it in the host's environment
Exposures never show up on Vercel, Netlify or CloudflareThe function ends before the SDK's queue is sentAdd the flush from the table above
The price changes on every reload, but only in SafariThe cookie is Secure, and Safari has a long-open bug that drops Secure cookies on http://localhost (WebKit bug 232088)Test in Chrome or Firefox, or set cookieSecure: false in development
Stripe charges a different amount than the page showedThe endpoint read a price from the form or used another product keyCall getPrice() in the endpoint with the same key

Frequently asked questions

Can the rest of my Astro site stay static?

Yes. Only the pricing page and the checkout endpoint need prerender = false; every other page keeps prerendering as usual. The adapter just gives those two routes a server.

Can a React or Svelte island show the price?

Yes: call getPrice() in the page's frontmatter and pass formatPrice(quote) to the island as a prop. The island never needs the SDK, and the cookie is still set by the page.

Can I test a subscription price?

Yes. Use mode: "subscription", add recurring: { interval: "month" } to price_data and drop payment_intent_data, which only payment mode accepts. Leverprice's Stripe webhook verifies one-time sessions only, so report the first payment with leverprice.trackPurchase() from your own webhook handler; it shows as unverified, and renewals never count toward the test.

Do crawlers see the test price?

No. Crawlers, link previews, headless browsers and monitors get the standard price, never receive a cookie and never count as visitors.