# How to A/B test prices in Hono

Source: https://leverprice.com/guides/hono
Updated: 2026-11-17

> Pass c.req.raw to getPrice(), add each Set-Cookie value with c.header and the append option, and build the response with c.html() so Hono includes those headers. At checkout, price again, create a Stripe session with price_data and quote.metadata, then c.redirect() with 303. On Cloudflare Workers, flush through c.executionCtx.waitUntil().

Hono hands every handler the same standard `Request` as `c.req.raw`, whether the app runs on Node, Bun, Deno or Cloudflare Workers, and the Leverprice SDK reads that object as is. What changes between runtimes is everything around the call: where the secret key comes from, and whether queued events need a `waitUntil` to get out before the runtime stops.

The Hono-specific part is small but easy to get wrong. `c.header()` replaces a header unless you ask it to append, and only responses built through the context pick up headers set that way. This guide covers both, with Stripe Checkout, and [server-side price testing](https://leverprice.com/blog/server-side-price-testing) explains why the price has to come from your server.

## How do you install Leverprice in a Hono app?

For a Node server, install Hono's Node adapter along with the SDK and Stripe:

```bash
npm install hono @hono/node-server @leverprice/sdk stripe
```

```bash title=".env"
LEVERPRICE_SECRET_KEY=pp_sk_test_…
STRIPE_SECRET_KEY=sk_test_…
```

The test key comes from the dashboard when you create a project, and the [docs](https://leverprice.com/docs) list the SDK's options. Create the clients once, at module scope:

```ts title="src/leverprice.ts"
import { Leverprice } from "@leverprice/sdk";
import Stripe from "stripe";

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

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

On Workers, `process.env` is only filled when the `nodejs_compat` flag is on, but bindings can also be read at module scope through an import, so the client is still built once per isolate:

```ts title="src/leverprice.ts on Workers"
import { env } from "cloudflare:workers";
// …the same module as above, with env.LEVERPRICE_SECRET_KEY and env.STRIPE_SECRET_KEY
```

Cloudflare allows reading variables and secrets this way at the top level, though not other I/O ([bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/)). Either way, `fallbackPrice` is what visitors get when Leverprice is off, slow (no config within 500 ms) or down, and `minPrice` and `maxPrice` are hard bounds the SDK checks on your server. Amounts are minor units: 1900 is $19.00.

## How do you set the price cookie with c.header()?

Price the visitor in a middleware and attach it only to routes that show or charge the price:

```ts title="src/index.ts"
import { serve } from "@hono/node-server";
import type { Quote } from "@leverprice/sdk";
import { Hono } from "hono";
import { getRuntimeKey } from "hono/adapter";
import { createMiddleware } from "hono/factory";
import { html } from "hono/html";
import { formatPrice, leverprice, stripe } from "./leverprice";

// Prices the visitor and queues the cookies on the response.
const priced = createMiddleware<{ Variables: { quote: Quote } }>(async (c, next) => {
  const quote = await leverprice.getPrice("pro", { request: c.req.raw });
  for (const cookie of quote.setCookie) c.header("Set-Cookie", cookie, { append: true });
  c.set("quote", quote);
  await next();
  if (getRuntimeKey() === "workerd") c.executionCtx.waitUntil(leverprice.flush());
});

const app = new Hono();

app.get("/pricing", priced, (c) => {
  c.header("Cache-Control", "private, no-store");
  return c.html(html`<!doctype html>
    <h1>Pro</h1>
    <p>${formatPrice(c.var.quote)}</p>
    <form method="post" action="/checkout"><button>Buy Pro</button></form>`);
});
```

`c.req.raw` gives the SDK the visitor's cookie and user agent, so returning visitors keep their variant and crawlers get the standard price. `{ append: true }` matters because `c.header()` otherwise replaces the header, along with any cookie another middleware already queued, such as a session. The `html` helper escapes interpolated values, and `c.html()` builds the response from the headers the middleware queued.

That last point is the one people trip on. A handler that returns `new Response(...)` directly skips headers set with `c.header()` earlier in the request, so the cookie never arrives. Return `c.html()`, `c.json()`, `c.body()` or `c.redirect()`, and the queued headers come along.

`c.executionCtx` exists only where the runtime provides an execution context, and on Node it throws "This context has no ExecutionContext" ([context API](https://hono.dev/docs/api/context)). The `getRuntimeKey()` check from `hono/adapter` keeps the flush to Workers, where the isolate may stop soon after the response ([adapter helper](https://hono.dev/docs/helpers/adapter)).

## How do you charge the price with Stripe Checkout?

Reuse the middleware on the checkout route, so the quote comes from the visitor's cookie rather than the form:

```ts title="src/index.ts"
app.post("/checkout", priced, async (c) => {
  const { quote } = c.var; // priced on the server, never read from the form
  const { origin } = new URL(c.req.url);

  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: `${origin}/thanks`,
    cancel_url: `${origin}/pricing`,
  });

  return c.redirect(session.url!, 303);
});

serve({ fetch: app.fetch, port: 3000 }); // Bun and Workers: export default app
```

`c.redirect()` defaults to 302; the 303 turns the form POST into a GET of Stripe's page, and the cookies queued by the middleware ride along. The `stripe` package ships a Workers build that talks to Stripe over `fetch`, so the same route runs there unchanged.

`price_data` makes a one-off price from `quote.price`, with `unit_amount` in minor units ([Checkout Sessions API](https://docs.stripe.com/api/checkout/sessions/create)). Pass `quote.metadata` whole, on the session and on 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: 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. See [Stripe](https://leverprice.com/integrations/stripe), [Polar](https://leverprice.com/integrations/polar), [Lemon Squeezy](https://leverprice.com/integrations/lemon-squeezy) and [Dodo Payments](https://leverprice.com/integrations/dodo-payments) for the full calls. Lemon Squeezy stops processing payments on March 31, 2027 ([announcement](https://www.lemonsqueezy.com/blog/saying-goodbye-to-lemon-squeezy)).

## How do queued events get sent on each runtime?

The SDK queues exposures and sends them in batches instead of blocking a request. Whether that queue empties by itself depends on how long the runtime lives after the response:

| Runtime | Where the key comes from | Sending queued events |
|---|---|---|
| Node with `@hono/node-server` | `process.env`, loaded with Node's `--env-file` flag | The SDK's timer sends them |
| Bun | `process.env`; Bun reads `.env` on its own | The SDK's timer sends them |
| Deno | `Deno.env.get()`, with `--env-file` | The SDK's timer sends them |
| Cloudflare Workers | `env` from `cloudflare:workers`; `.dev.vars` locally | `c.executionCtx.waitUntil(leverprice.flush())` |
| Vercel, AWS Lambda | `process.env` from the platform | `await leverprice.flush()` before the handler returns |

On Workers, `waitUntil` keeps the isolate working for up to 30 seconds after the response ([context](https://developers.cloudflare.com/workers/runtime-apis/context/)). When nothing is queued, `flush()` returns without a network call, so calling it on every priced request costs nothing.

## How does verified revenue work?

Stripe sends signed webhooks straight to Leverprice, so the Hono app doesn't need a webhook route for the test. 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.

The signing secret confirms events but can't move money, so an API key never goes there. Refunds reduce the revenue of the price that sold, and Stripe verification covers one-time `payment` sessions like the one above.

*Figure: Diagram: a visitor requests the page, the server asks for a price, the visitor checks out, traffic moves to the better price. The middleware prices the visitor, the checkout route charges that price, and Stripe confirms the sale.*

## How do regional prices work in Hono?

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. Name the header your platform sets: `cf-ipcountry` on Cloudflare, `x-vercel-ip-country` on Vercel.

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

There's no default header, because one the visitor could send would let them pick their own price. `c.req.raw` carries every request header, so the middleware reads the country with no other change, and the checkout already sends `quote.currency` to Stripe. Bots, unknown countries and currencies you didn't list get the standard price. [Regional pricing](https://leverprice.com/blog/regional-pricing) explains how each country's price is chosen.

## How do you test it locally?

1. Start the app (`npx tsx --env-file=.env src/index.ts` on Node, `bun run src/index.ts` on Bun, `npx wrangler dev` on Workers) and open `/pricing` in Chrome or Firefox. A `__pp` cookie should appear, with a price inside your range.
2. Reload: the price holds. A private window is a new visitor and may get a different price.
3. Run `curl -i` against `/pricing`. Command-line clients count as bots, so you get the standard price and no `Set-Cookie`; add `-A "Mozilla/5.0"` to see the raw cookie header.
4. Click Buy and pay on Stripe's test page with `4242 4242 4242 4242` ([Stripe testing](https://docs.stripe.com/testing)). The amount matches the page, and the order appears in Leverprice as verified test revenue.
5. Restart with `LEVERPRICE_DISABLED=1` in the environment: fallback price, no cookie, no network calls.

The dashboard's Install page shows Connected after your server's first request, labeled test mode only until a live key is used. For production, swap in the live keys (`pp_sk_live_…` and Stripe's live key) and connect a Live-mode webhook endpoint; test and live data never mix.

## Troubleshooting

| Symptom | Likely cause | Fix |
|---|---|---|
| Only one of two cookies reaches the browser | `c.header("Set-Cookie", …)` without `{ append: true }` replaced the first | Pass `{ append: true }` for every `Set-Cookie` value |
| No cookie arrives at all | The handler returns `new Response(...)`, which skips headers set with `c.header()` | Return `c.html()`, `c.json()`, `c.body()` or `c.redirect()` |
| "This context has no ExecutionContext" on Node or Bun | `c.executionCtx` is called outside Workers | Guard it with `getRuntimeKey() === "workerd"` |
| Everyone gets the fallback price on Workers | The key was read from `process.env` without `nodejs_compat`, or it sits in `.env` while a `.dev.vars` file exists | Read it from `env` in `cloudflare:workers` and keep local secrets in one file |
| Exposures never show up on Workers or Lambda | The runtime stops before the SDK's queue is sent | Use `waitUntil` on Workers, `await leverprice.flush()` on Lambda |
| Every visitor sees the same price | Hono's `cache()` middleware, or a CDN rule, covers `/pricing` | Keep caching off priced routes and send `Cache-Control: private, no-store` |
| The price changes on every reload, but only in Safari | The cookie is `Secure`, and Safari has a long-open bug that drops Secure cookies on `http://localhost` ([WebKit bug 232088](https://bugs.webkit.org/show_bug.cgi?id=232088)) | Test in Chrome or Firefox, or set `cookieSecure: false` in development |

## Frequently asked questions

### Should the middleware run on every route?

No. Attach it only to routes that show or charge the price. `app.use("*", priced)` would count every page view anywhere on the site as a view of your price.

### Can I render with Hono JSX instead of the html helper?

Yes. `c.html()` accepts JSX as well, and `c.render()` with `jsxRenderer` works too; both build the response through the context, so the queued cookies are included.

### 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.

### Is there a guide for Workers without Hono?

Yes. The [Workers guide](https://leverprice.com/guides/cloudflare-workers) covers a plain `fetch` handler, including how to fill a static pricing page with HTMLRewriter.
