# How to A/B test prices in Next.js (App Router)

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

> Assign the price in proxy.ts, because React Server Components can read cookies but cannot set them. The proxy calls getPrice(), sets the signed cookie and forwards it to the page, which reads the same price. A route handler charges quote.price with Stripe price_data and passes quote.metadata whole. Keep the page uncached.

Put `getPrice()` in a Next.js Server Component and the test looks fine on your machine: a price renders. Then the next request draws a new one, because the cookie that should have pinned the first price never left the server. Server Components can read cookies but can't set them, and a price test depends on a cookie written during the first visit.

The fix is to give each job to the part of Next.js 16 that is allowed to do it. This guide wires the Leverprice SDK and Stripe Checkout into an App Router project, and every step runs on `next dev` with a test key before production sees any of it.

## Why can't a Server Component set the price cookie?

Because the response is already streaming when it renders, and HTTP can't add a cookie after that point. The [`cookies` reference](https://nextjs.org/docs/app/api-reference/functions/cookies) allows reading cookies in Server Components and setting them only in Server Functions and Route Handlers.

For a price test, that rule decides where the code goes. Call `getPrice()` in the page for a first-time visitor and the SDK assigns a price, then returns a `Set-Cookie` value the browser never receives. The next request looks like a new visitor, so it can draw a different price and count a second exposure. Checkout then charges whatever that request drew.

Split the work across files instead:

| File | Job |
|---|---|
| `proxy.ts` | Assigns new visitors, sets the cookie, counts the exposure |
| `app/pricing/page.tsx` | Reads the visitor's price from the forwarded cookie |
| `app/api/checkout/route.ts` | Prices the visitor again and creates the Stripe session |

Why the price has to come from your server at all is covered in [server-side price testing](https://leverprice.com/blog/server-side-price-testing). This guide is the Next.js wiring.

## How do you install Leverprice in a Next.js app?

Install the SDK and Stripe's library, then add both secret keys to `.env.local`:

```bash
npm install @leverprice/sdk stripe
```

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

Your test key (`pp_sk_test_…`) appears when you create a project in the dashboard, and the [docs](https://leverprice.com/docs) cover the rest of the setup. Don't give it a `NEXT_PUBLIC_` prefix: Next.js inlines those variables into the browser bundle at build time ([environment variables](https://nextjs.org/docs/app/guides/environment-variables)).

Create the client once, in a module that the proxy, the page and the route handler all import:

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

export const leverprice = new Leverprice({
  secretKey: process.env.LEVERPRICE_SECRET_KEY, // server-only, never NEXT_PUBLIC_
  products: {
    // Hard bounds in minor units: 1900 is $19.00.
    pro: { currency: "usd", fallbackPrice: 1900, minPrice: 1500, maxPrice: 3900 },
  },
});

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

`minPrice` and `maxPrice` are hard limits checked on your server, so a bad experiment config can't put $1 on the page. `fallbackPrice` is what everyone gets when Leverprice is switched off, slow (no signed config within 500 ms) or down, and `getPrice()` never throws for those reasons. Prices are integers in minor units, which is why `formatPrice` divides by the currency's decimal places instead of a hard-coded 100.

## How does proxy.ts assign the price?

`proxy.ts` is what Next.js 16 calls middleware ([proxy reference](https://nextjs.org/docs/app/api-reference/file-conventions/proxy)). It runs before the route renders, so it's the one place in a page request that can both price a new visitor and set the cookie.

```ts title="proxy.ts"
import { type NextFetchEvent, type NextRequest, NextResponse } from "next/server";
import { leverprice } from "@/lib/leverprice";

export async function proxy(request: NextRequest, event: NextFetchEvent) {
  const quote = await leverprice.getPrice("pro", { request });

  // Hand a new cookie to the page rendered for this same request.
  for (const cookie of quote.setCookie) {
    const [name, value] = cookie.split(";")[0].split("=");
    request.cookies.set(name, value);
  }

  const response = NextResponse.next({ request: { headers: request.headers } });
  for (const cookie of quote.setCookie) response.headers.append("Set-Cookie", cookie);

  event.waitUntil(leverprice.flush()); // send the exposure after the response
  return response;
}

export const config = {
  matcher: [
    {
      source: "/pricing",
      missing: [
        { type: "header", key: "next-router-prefetch" },
        { type: "header", key: "purpose", value: "prefetch" },
      ],
    },
  ],
};
```

The loop writes each `Set-Cookie` value twice: onto the response for the browser, and into the request headers Next.js hands to the page. Without the second write, the page rendered during this same request still sees a visitor with no cookie and draws its own price.

`event.waitUntil(leverprice.flush())` sends the exposure without holding up the response. The SDK queues events instead of blocking the request, and a serverless function can freeze before the SDK's own timer fires.

The matcher keeps the proxy on `/pricing` and away from prefetches. Inside proxy code, Next.js strips the `next-router-prefetch` header from `request.headers`, so the SDK can't recognize a `<Link>` prefetch on its own. The matcher sees the raw request, so it can. Without the `missing` rules, every visitor with a pricing link on screen would count as having seen a price.

Proxy runs on the Node.js runtime by default in Next.js 16, and the `runtime` option isn't allowed in proxy files; the SDK needs no configuration for it. The proxy docs also warn against relying on modules or globals shared with your render code, so assume each side loads the signed config on its own. They still agree on the price, because both read the same cookie.

## How do you show the price in a Server Component?

Read it in an async component inside a `<Suspense>` boundary:

```tsx title="app/pricing/page.tsx"
import { headers } from "next/headers";
import { Suspense } from "react";
import { formatPrice, leverprice } from "@/lib/leverprice";

export default function PricingPage() {
  return (
    <main>
      <h1>Pro</h1>
      <Suspense fallback={<p>&nbsp;</p>}>
        <ProPrice />
      </Suspense>
      <form action="/api/checkout" method="post">
        <button type="submit">Buy Pro</button>
      </form>
    </main>
  );
}

async function ProPrice() {
  const quote = await leverprice.getPrice("pro", {
    request: { headers: await headers() }, // carries the cookie proxy.ts forwarded
    exposure: "manual", // proxy.ts already counted this visitor
  });
  return <p>{formatPrice(quote)}</p>;
}
```

`{ headers: await headers() }` works as the request because the SDK accepts any object with headers. It finds the cookie the proxy forwarded and returns the same variant.

`exposure: "manual"` with no `logExposure()` call means the page never counts anyone, since the proxy already did. If the page ever renders without the proxy's cookie, during a prefetch or on a path the matcher missed, it won't log a visitor who doesn't exist.

The `<Suspense>` boundary matters once you enable Cache Components, the opt-in caching model in Next.js 16. With it on, reading `headers()` outside a boundary stops the route from prerendering ([error reference](https://nextjs.org/docs/messages/blocking-prerender-runtime)). With the boundary, the heading and button prerender as a static shell and only the price renders per request. Without Cache Components, `headers()` makes the whole route dynamic.

Keep the price away from anything that caches it for everyone: a `"use cache"` function, `revalidate`, or `export const dynamic = "force-static"`, which makes `headers()` return empty values so the build draws one price for all visitors.

## How do you charge the same price in Stripe Checkout?

Price the visitor again in a route handler and pass the quote straight into the session:

```ts title="app/api/checkout/route.ts"
import { after, type NextRequest, NextResponse } from "next/server";
import Stripe from "stripe";
import { leverprice } from "@/lib/leverprice";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(request: NextRequest) {
  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: new URL("/thanks", request.url).toString(),
    cancel_url: new URL("/pricing", request.url).toString(),
  });

  const response = NextResponse.redirect(session.url!, 303);
  for (const cookie of quote.setCookie) response.headers.append("Set-Cookie", cookie);
  after(() => leverprice.flush());
  return response;
}
```

The cookie brings back the same variant, so Stripe shows the amount the pricing page showed. Never read a price from the form body; anyone can edit it.

`price_data` creates a one-off price inside the session, with `unit_amount` as an integer in minor units ([Checkout Sessions API](https://docs.stripe.com/api/checkout/sessions/create)). `quote.metadata` is the signed record of which price this visitor saw. Pass it whole on the session and on the payment intent, so a refund carries it too, and don't rename or drop keys.

The 303 turns the form POST into a GET of Stripe's page, and [`after()`](https://nextjs.org/docs/app/api-reference/functions/after) runs the flush once the response is sent. A Server Action can create the session as well, but it sets cookies through `cookies().set()`, which takes a name and options rather than a raw `Set-Cookie` header. The route handler appends the SDK's values as they are.

Polar, Lemon Squeezy and Dodo Payments work the same way, each with its own custom-price field: ad-hoc `prices` on a Polar checkout session, `custom_price` in cents on a Lemon Squeezy checkout, and `amount` on a Dodo Payments pay-what-you-want product. `quote.metadata` goes into each provider's metadata (Lemon Squeezy calls it `checkout_data.custom`). The [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) pages show the exact calls. Lemon Squeezy stops processing payments on March 31, 2027 ([announcement](https://www.lemonsqueezy.com/blog/saying-goodbye-to-lemon-squeezy)), so new projects should pick one of the others.

## How does revenue get verified?

Stripe sends its signed webhooks to Leverprice directly, so your Next.js app needs no webhook route for the test:

1. In the dashboard, open Payments, choose Connect provider and pick Stripe in Test mode.
2. In Stripe, add the URL Leverprice gives you as a webhook endpoint for `checkout.session.completed`, `checkout.session.async_payment_succeeded` and `charge.refunded`.
3. Paste that endpoint's signing secret, which starts with `whsec_`, back into Leverprice.

A signing secret lets Leverprice confirm that an event came from Stripe. It can't charge, refund or read customers, and an API key never belongs in that field. Refunds come off the revenue of the price that sold, and [verified revenue](https://leverprice.com/blog/verified-revenue-webhooks) explains what the signature check protects against.

*Figure: Diagram: the checkout, the provider's signed webhook and the verified purchase. Stripe confirms each purchase to Leverprice directly; your app only creates the checkout.*

Verification covers Checkout Sessions in `payment` mode, which is what this guide creates. Subscriptions need one extra step, described in the FAQ below.

## How do regional prices work on Vercel?

Regional prices give each country its own price (SDK 0.4 or later). During a test, every visitor keeps one variant at that variant's price for their country. Turn them on for the product in the dashboard, then tell the SDK which header carries the country and which currencies you can charge:

```ts title="lib/leverprice.ts"
export const leverprice = new Leverprice({
  secretKey: process.env.LEVERPRICE_SECRET_KEY,
  countryHeader: "x-vercel-ip-country", // set by Vercel, 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 },
      },
    },
  },
});
```

Vercel sets `x-vercel-ip-country` itself; behind Cloudflare, use `cf-ipcountry`. The option has no default on purpose, because a header visitors can send themselves would let them pick their own price. The page already passes its whole headers object, so it sees the country with no other change, and the checkout sends `quote.currency` to Stripe. Bots, visitors from unknown countries and currencies you didn't list get the standard price. [Regional pricing](https://leverprice.com/blog/regional-pricing) covers how the per-country prices are set.

## How do you test it locally?

With the test key in `.env.local` and a Test-mode webhook connected:

1. Run `npm run dev` and open `http://localhost:3000/pricing` in Chrome or Firefox. DevTools should list a `__pp` cookie, and the price should sit inside your range.
2. Reload a few times and the price stays put. A private window is a new visitor and may get a different one.
3. Open the Install page in the dashboard. It reads Connected after your server's first request, marked test mode only until a live key is used.
4. Run `curl -i http://localhost:3000/pricing`. You get the standard price and no `Set-Cookie`, because command-line clients count as bots.
5. Click Buy. Stripe's test checkout shows the same amount. Pay with card `4242 4242 4242 4242` ([Stripe testing](https://docs.stripe.com/testing)) and the order appears as verified test revenue.
6. Restart with `LEVERPRICE_DISABLED=1 npm run dev`. Every visitor now gets the fallback price, with no cookie and no network calls.

## What changes in production?

Mostly keys. Set `LEVERPRICE_SECRET_KEY` to your live key (`pp_sk_live_…`) and Stripe's live key in the host's environment, then connect a second webhook endpoint in Live mode. Test and live data never mix.

On Vercel, the proxy and the route handler run as functions, and `event.waitUntil` and `after` keep each one alive until its events are sent. `next start` on your own server supports both as well ([self-hosting guide](https://nextjs.org/docs/app/guides/self-hosting)).

Leave the caching headers alone. Next.js sends `Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate` for dynamic pages, which keeps one visitor's price out of shared caches. Don't override it with `headers()` in `next.config`, and don't put `/pricing` behind a CDN rule that caches HTML.

Stay on the default Node.js runtime, since current Next.js docs mark `runtime = "edge"` as deprecated ([runtime option](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/runtime)). If something goes wrong in production, set `LEVERPRICE_DISABLED=1` and redeploy: every visitor gets your fallback price until you remove it.

## Troubleshooting

| Symptom | Likely cause | Fix |
|---|---|---|
| The price changes on every reload | The proxy didn't run for this path, often because of a locale prefix or a trailing slash | Make the matcher cover the real path, for example `/:locale/pricing` |
| The price changes on every reload, but only in Safari | The SDK's 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, run dev over https, or pass `cookieSecure: false` in development |
| Every visitor sees the same price | Something caches the price: `"use cache"`, `force-static`, ISR or a CDN rule | Render the price per request and keep the `private` cache header |
| The build reports runtime data read during prerendering | Cache Components is on and `headers()` runs outside `<Suspense>` | Wrap the price component in `<Suspense>` |
| Exposures far outnumber pricing page views | Prefetches reach the proxy | Add the `missing` conditions to the matcher |
| Everyone gets the fallback price with reason `disabled` | `LEVERPRICE_SECRET_KEY` isn't set in that environment | Add it to the host's environment and redeploy |
| Playwright tests always see the standard price | Headless browsers count as bots | Pass `bot: false` to every `getPrice()` call in your test environment only |

## Frequently asked questions

### Can the pricing page stay static?

Most of it can. With Cache Components on, everything outside the `<Suspense>` boundary prerenders into a static shell and only the price renders per request. The price itself can't be static, because two visitors may be in different variants.

### Does this work with the Pages Router?

Yes, and it's simpler there, because `getServerSideProps` runs before any HTML is sent. Pass its Node `req` to `getPrice()` directly and add the cookies with `res.appendHeader("Set-Cookie", quote.setCookie)` before returning props.

### Can I test a subscription price?

Yes. Switch to `mode: "subscription"`, add `recurring: { interval: "month" }` to `price_data` and drop `payment_intent_data`, which Stripe only accepts in payment mode. Leverprice's Stripe webhook verifies one-time Checkout 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 search engines see a test price?

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