How to A/B test prices on Cloudflare Workers

Price testing on Cloudflare Workers: build the client per isolate, fill a static pricing page with HTMLRewriter, charge with Stripe, flush via waitUntil.

Short answer

Create the client at module scope with env imported from cloudflare:workers, call getPrice() with the incoming request, append every Set-Cookie value and flush with ctx.waitUntil(leverprice.flush()). For a static pricing page, run the Worker first on /pricing and fill the price in with HTMLRewriter. Charge quote.price from a POST route with Stripe.

  • Workers serve matching static assets without running your code; listing /pricing in run_worker_first hands that path to the Worker.
  • Import env from cloudflare:workers to build the client once per isolate, at module scope.
  • ctx.waitUntil keeps the Worker running for up to 30 seconds after the response, long enough to send queued exposures.
  • Drop the asset's ETag and send Cache-Control: private, no-store, so no browser revalidates a stale price.
  • The nodejs_compat flag fills process.env, which is where the SDK reads its LEVERPRICE_DISABLED kill switch.

A Worker is a natural home for a price test: it runs before your HTML leaves Cloudflare, and the Leverprice SDK needs nothing beyond fetch and WebCrypto. Two defaults get in the way. Static assets that match a request are served without running your Worker at all, so a pricing.html never meets the SDK. And an isolate can stop shortly after the response, taking queued events with it unless you hand them to ctx.waitUntil().

This guide builds a plain Worker that fills a static pricing page with each visitor's price and creates a Stripe Checkout session. Server-side price testing covers why the price has to come from a server. If your Worker uses Hono, the Hono guide covers the same ground with middleware.

How do you set up the Worker and its secrets?

Install the SDK and Stripe's library, then configure the Worker with static assets:

Terminal
npm install @leverprice/sdk stripe
wrangler.jsonc
{
  "name": "pricing-site",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-01",
  "compatibility_flags": ["nodejs_compat"],
  "assets": {
    "directory": "./public",
    "binding": "ASSETS",
    "run_worker_first": ["/pricing"]
  }
}
.dev.vars
LEVERPRICE_SECRET_KEY=pp_sk_test_…
STRIPE_SECRET_KEY=sk_test_…

By default, a request that matches a static asset is answered from ./public without invoking your code (static assets). run_worker_first takes a list of paths, so /pricing reaches the Worker while every other asset is still served directly.

nodejs_compat is there for the kill switch. With the flag and a compatibility date on or after 2025-04-01, Workers copy your variables and secrets into process.env (environment variables), which is where the SDK reads LEVERPRICE_DISABLED. Without the flag, pass disabled to the constructor yourself.

Wrangler reads local secrets from .dev.vars or .env, never both: if .dev.vars exists, .env is ignored (secrets). Run npx wrangler types afterwards so Env knows about the ASSETS binding and both keys. The test key comes from the dashboard when you create a project, and the docs list every SDK option.

How do you create the client once per isolate?

Import env from cloudflare:workers and build both clients at module scope:

src/clients.ts
import { Leverprice } from "@leverprice/sdk";
import { env } from "cloudflare:workers";
import Stripe from "stripe";

// Module scope: created once per isolate and reused by every request it serves.
export const leverprice = new Leverprice({
  secretKey: env.LEVERPRICE_SECRET_KEY,
  products: {
    pro: { currency: "usd", fallbackPrice: 1900, minPrice: 1500, maxPrice: 3900 },
  },
});

export const stripe = new Stripe(env.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);
}

Workers let you read variables and secrets at the top level through this import; only I/O, such as a KV read, has to wait for a request (bindings). The SDK does no I/O in its constructor, so module scope is safe. An isolate that has the signed config prices from memory, and a cold one waits at most 500 ms for it before serving your fallbackPrice.

The stripe package ships a Workers build that talks to Stripe over fetch, so it needs no custom HTTP client. minPrice and maxPrice are hard bounds the SDK checks in the Worker, in minor units: 1900 is $19.00.

How do you put the price into a static pricing page?

Keep the page in ./public, with the fallback price in a marked element so it reads correctly even before the Worker touches it:

public/pricing.html
<h1>Pro</h1>
<p data-price>$19.00</p>
<form method="post" action="/checkout"><button>Buy Pro</button></form>

The Worker fetches that asset, rewrites the marked element as the HTML streams through, and adds the cookies:

src/index.ts
import { formatPrice, leverprice, stripe } from "./clients";

export default {
  async fetch(request, env, ctx): Promise<Response> {
    const url = new URL(request.url);

    if (url.pathname === "/pricing" && request.method === "GET") {
      const quote = await leverprice.getPrice("pro", { request });
      const page = new HTMLRewriter()
        .on("[data-price]", {
          element(element) {
            element.setInnerContent(formatPrice(quote));
          },
        })
        .transform(await env.ASSETS.fetch(request));

      // Copy into a response whose headers can change, and keep it out of every cache.
      const response = new Response(page.body, page);
      response.headers.delete("ETag");
      response.headers.set("Cache-Control", "private, no-store");
      for (const cookie of quote.setCookie) response.headers.append("Set-Cookie", cookie);
      ctx.waitUntil(leverprice.flush());
      return response;
    }

    if (url.pathname === "/checkout" && request.method === "POST") {
      return checkout(request, url, ctx);
    }

    return env.ASSETS.fetch(request);
  },
} satisfies ExportedHandler<Env>;

This is the pattern Cloudflare documents for running code before an asset: fetch it through the ASSETS binding, then transform it with HTMLRewriter (Worker script routing). With the default auto-trailing-slash handling, /pricing serves pricing.html.

Deleting the ETag matters more than it looks. The asset's ETag describes the static file, not the price written into it, so a browser revalidating with If-None-Match would get a 304 and keep showing whatever price it saw first, even after you lock in a winner. no-store stops that copy from being kept at all.

ctx.waitUntil() keeps the Worker running for up to 30 seconds after the response is sent (context), long enough to deliver the exposure the SDK queued. If your pricing page is rendered in the browser instead, return { price, currency } from a JSON route with the same cookies; nothing else changes.

How do you charge the price with Stripe Checkout?

The form posts to /checkout, which isn't an asset, so it reaches the Worker without any routing change:

src/index.ts
async function checkout(request: Request, url: URL, ctx: ExecutionContext): Promise<Response> {
  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`,
  });

  // Response.redirect() returns immutable headers, so build the 303 by hand to add cookies.
  const response = new Response(null, { status: 303, headers: { Location: session.url! } });
  for (const cookie of quote.setCookie) response.headers.append("Set-Cookie", cookie);
  ctx.waitUntil(leverprice.flush());
  return response;
}

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 what this visitor was shown.

Polar, Lemon Squeezy and Dodo Payments work the same way through their own custom-price fields: ad-hoc prices on a Polar checkout session, custom_price in cents 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 have each call. Lemon Squeezy stops processing payments on March 31, 2027 (announcement).

How does verified revenue work?

Stripe's signed webhooks go straight to Leverprice, so the Worker gets no webhook route. In the dashboard, open Payments and connect Stripe in Test mode. Add the URL it shows as a webhook endpoint in Stripe for checkout.session.completed, checkout.session.async_payment_succeeded and charge.refunded, then paste the endpoint's signing secret back into Leverprice.

A signing secret confirms 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 route above creates.

Stripe confirms each purchase to Leverprice directly; the Worker only creates the checkout.

How do regional prices work on Workers?

Regional prices (SDK 0.4 or later) charge each country its own price, and in a running test each visitor keeps one variant at that variant's price for their country. On Cloudflare, the country arrives in cf-ipcountry, which IP geolocation adds to requests (managed transforms):

src/clients.ts
export const leverprice = new Leverprice({
  secretKey: env.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 },
      },
    },
  },
});

Workers also expose the country as request.cf?.country; pass it as country to getPrice() if you prefer, and it wins over the header. The option has no default because a header visitors can send would let them choose their own price. Both routes pass the request, and the checkout already sends quote.currency to Stripe. Bots, unknown countries (Cloudflare reports XX, and T1 for Tor) and currencies you didn't list get the standard price. Regional pricing explains how each country's price is chosen.

How do you test it with wrangler dev?

  1. Run npx wrangler dev and open http://localhost:8787/pricing in Chrome or Firefox. The placeholder should be replaced by a price inside your range, and a __pp cookie should appear.
  2. Reload a few times: the price holds. A private window is a new visitor and may draw a different one.
  3. Run curl -i http://localhost:8787/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 matches the page, and the order shows up in Leverprice as verified test revenue.
  5. Add LEVERPRICE_DISABLED=1 to .dev.vars and restart. The page shows the fallback price, with no cookie and no network calls.

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

What changes when you deploy?

Store the live keys as secrets and deploy:

Terminal
npx wrangler secret put LEVERPRICE_SECRET_KEY
npx wrangler secret put STRIPE_SECRET_KEY
npx wrangler deploy

Use pp_sk_live_… and Stripe's live key, and connect a Live-mode webhook endpoint in Leverprice; test and live data never mix. wrangler secret put creates and deploys a new version immediately, which also makes it the fastest kill switch: npx wrangler secret put LEVERPRICE_DISABLED with the value 1 sends every visitor your fallback price until you delete it.

Keep /pricing out of any Cache Rule that caches HTML, and never put a priced response into caches.default: either one serves a single visitor's price to everyone behind that edge.

Troubleshooting

SymptomLikely causeFix
/pricing shows the placeholder price and sets no cookieThe asset is served before the Worker runsAdd /pricing to run_worker_first
TypeError: Can't modify immutable headersHeaders were appended to a response with immutable headers, such as one from Response.redirect()Copy it into new Response(body, response) first, or build the response yourself
Exposures never show up in the dashboardThe isolate stopped before the SDK's queue was sentCall ctx.waitUntil(leverprice.flush()) on every priced route
LEVERPRICE_DISABLED has no effectnodejs_compat is off or the compatibility date is before 2025-04-01, so process.env is emptyAdd the flag, or pass disabled: env.LEVERPRICE_DISABLED === "1"
Everyone gets the fallback price in wrangler devThe key sits in .env while a .dev.vars file existsKeep local secrets in one of the two files
A browser keeps showing an old price after a lock-inThe asset's ETag passed through, so the browser revalidated its stale copyDelete ETag and send Cache-Control: private, no-store
Every visitor sees the same priceA Cache Rule or caches.default stores the priced pageExclude /pricing from caching

Frequently asked questions

Do I need KV or Durable Objects?

No. Each visitor's assignment lives in their HMAC-signed cookie, and the signed config sits in the isolate's memory, so the Worker stores nothing.

Does this work with Pages Functions?

The SDK calls are the same: a Pages Function receives context.request, context.env and context.waitUntil, and you pass them where this guide uses request, env and ctx.

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.