# How to A/B test prices in React Router v7 (framework mode)

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

> Call getPrice() in the route's server loader with the request, return the price with data() and its Set-Cookie values as headers, and export headers() so React Router actually sends them. Create the Stripe Checkout session in an action that prices the visitor again, passes quote.metadata whole and redirects with the same cookies.

React Router's framework mode, the project that used to be Remix, hands every loader a standard `Request`, which is exactly what the Leverprice SDK reads. The trouble is on the way out. Headers a loader returns are dropped unless the route also exports a `headers` function, so a price test can render prices correctly while the cookie that keeps each visitor's price never reaches the browser.

This guide sets up a pricing route and a checkout action on React Router v7 with Stripe Checkout. The same code runs on React Router v8, [released in June 2026](https://remix.run/blog/react-router-v8): none of the breaking changes in its [upgrade guide](https://reactrouter.com/upgrading/v7) affect the loader, action, `data()` or `headers` code below. For why the price has to come from your server in the first place, see [server-side price testing](https://leverprice.com/blog/server-side-price-testing).

## How do you install Leverprice in React Router?

Add the SDK and Stripe's library, then put the keys in `.env` at the project root:

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

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

In development, React Router's Vite plugin copies every variable in `.env` into `process.env`, not only the `VITE_` ones, so server code can read them. Nothing loads `.env` for you in production, so set the same variables in your host's environment. The test key comes from the dashboard when you create a project, and the [docs](https://leverprice.com/docs) list every SDK option.

Create both clients in `.server` modules:

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

export const leverprice = new Leverprice({
  secretKey: process.env.LEVERPRICE_SECRET_KEY,
  products: {
    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);
}
```

```ts title="app/lib/stripe.server.ts"
import Stripe from "stripe";

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

The `.server` suffix keeps these files out of the browser bundle, and the build fails if one of them leaks into client code ([server modules](https://reactrouter.com/api/framework-conventions/server-modules)). Route modules can still import them, as long as only `loader` and `action` use what they import. Module scope gives you one client per server process, which keeps the signed config in memory between requests.

`fallbackPrice` is what every visitor gets when Leverprice is off, slow (no config within 500 ms) or unreachable. `minPrice` and `maxPrice` are hard bounds the SDK enforces on your server, and every amount is in minor units: 1900 is $19.00.

## How do you price visitors in a loader?

Call `getPrice()` with the loader's `request`, attach the cookies to the result with `data()`, and export `headers` so React Router sends them:

```tsx title="app/routes/pricing.tsx"
import { data, Form } from "react-router";
import { formatPrice, leverprice } from "~/lib/leverprice.server";
import type { Route } from "./+types/pricing";

export async function loader({ request }: Route.LoaderArgs) {
  const quote = await leverprice.getPrice("pro", { request });
  const headers = new Headers({ "Cache-Control": "private, no-store" });
  for (const cookie of quote.setCookie) headers.append("Set-Cookie", cookie);
  return data({ price: formatPrice(quote) }, { headers });
}

// Loader headers only reach the browser if the route returns them here.
export function headers({ loaderHeaders }: Route.HeadersArgs) {
  return loaderHeaders;
}

export default function Pricing({ loaderData }: Route.ComponentProps) {
  return (
    <main>
      <h1>Pro</h1>
      <p>{loaderData.price}</p>
      <Form method="post" action="/checkout" reloadDocument>
        <button type="submit">Buy Pro</button>
      </Form>
    </main>
  );
}
```

Register it, along with the checkout route used below, in `app/routes.ts`:

```ts title="app/routes.ts"
import { type RouteConfig, index, route } from "@react-router/dev/routes";

export default [
  index("routes/home.tsx"),
  route("pricing", "routes/pricing.tsx"),
  route("checkout", "routes/checkout.ts"),
] satisfies RouteConfig;
```

The [headers guide](https://reactrouter.com/how-to/headers) is explicit that loader and action headers are not sent automatically: you return them from the route's `headers` export. Its one exception, `Set-Cookie` from parent routes, doesn't cover the route's own loader, so the pricing route keeps the export. If a parent route also sets headers, the deepest route wins; merge with `parentHeaders` when you need both.

Client-side transitions work the same way. When a visitor clicks through to `/pricing` from another page, React Router calls the loader with a fetch to your server, the browser sends the visitor's cookie along, and the `headers` export covers that data response too (the behavior Remix introduced as [single fetch](https://remix.run/docs/guides/single-fetch)). The visitor keeps their price and isn't counted twice, because the SDK logs one exposure per visitor and experiment.

`Cache-Control: private, no-store` keeps CDNs and browsers from reusing one visitor's price for another. The component only receives a formatted string, so neither the SDK nor a key ends up in the client bundle.

*Figure: Diagram: a visitor requests the page, the server asks for a price, the visitor checks out, traffic moves to the better price. The loader asks for the price on your server; the action charges the same one.*

## How do you charge that price at checkout?

The buy button posts to a resource route whose action prices the visitor again and creates the Stripe session:

```ts title="app/routes/checkout.ts"
import { redirect } from "react-router";
import { leverprice } from "~/lib/leverprice.server";
import { stripe } from "~/lib/stripe.server";
import type { Route } from "./+types/checkout";

export async function action({ request }: Route.ActionArgs) {
  const quote = await leverprice.getPrice("pro", { request }); // never trust a price from the form
  const { origin } = new URL(request.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`,
  });

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

`reloadDocument` on the `<Form>` makes it a plain browser POST, so the browser follows the 303 to Stripe like any other redirect and stores any cookie on the way. React Router's `redirect()` takes a status code or a full `ResponseInit`, headers included ([redirect](https://reactrouter.com/api/utils/redirect)).

The amount on Stripe's page matches the pricing page because the cookie maps the visitor to the same variant, and the action never reads a price from the form. `price_data` puts that amount on a one-off 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 the price this visitor saw, and Leverprice ties the purchase to it.

Other providers take the same quote through their own custom-price field. Polar accepts ad-hoc `prices` on a checkout session, Lemon Squeezy a `custom_price` in cents with the metadata in `checkout_data.custom`, and Dodo Payments an `amount` for pay-what-you-want products. 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)), so it's a poor choice for a new project.

## How does Stripe revenue reach Leverprice?

Through Stripe's own signed webhooks, sent straight to Leverprice, so the app needs no webhook route for this. In the dashboard, open Payments, connect Stripe in Test mode, and add the URL it gives you as an endpoint in Stripe for `checkout.session.completed`, `checkout.session.async_payment_succeeded` and `charge.refunded`. Then paste that endpoint's signing secret back into Leverprice.

The signing secret can confirm events but can't move money, so an API key never goes in that field. Refunds reduce the revenue of the price that sold. Stripe verification covers one-time `payment` sessions like the one above; a subscription's first payment has to be reported with `leverprice.trackPurchase()` from your own webhook handler, and it shows as unverified.

## How do regional prices work in React Router?

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. React Router doesn't know where a visitor is; your host does, through a header it sets on every request:

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

Name only a header your host overwrites; there's no default, because a header visitors can send would let them choose their own price. The loader passes the full `request`, so the country comes along with no other change, and the action already sends `quote.currency` to Stripe. A bot, an unknown country or a currency missing from `regional` gets 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. Run `npm run dev` and open `http://localhost:5173/pricing` in Chrome or Firefox. The document response should carry a `Set-Cookie: __pp=…` header, which proves the `headers` export works.
2. Reload: the price stays the same. A private window counts as a new visitor and may draw another price.
3. Start on the home page and click a link to `/pricing`. The Network tab shows a `/pricing.data` request, and the price matches what you saw before.
4. Run `curl -i http://localhost:5173/pricing`. Command-line clients count as bots, so you get the standard price and no cookie.
5. Click Buy and pay on Stripe's test page with `4242 4242 4242 4242` ([Stripe testing](https://docs.stripe.com/testing)). The amount should equal the page's, and the order lands in Leverprice as verified test revenue.
6. Start the dev server with `LEVERPRICE_DISABLED=1`. Every visitor gets the fallback price, with no cookie and no network calls.

The Install page in the dashboard switches to Connected after your server's first request, labeled test mode only until a live key is in use.

## What changes when you deploy?

Swap in the live keys (`pp_sk_live_…` and Stripe's live key) and connect a Live-mode webhook endpoint, since test and live data stay separate. Beyond that, it depends on where React Router runs:

| Host | Sending queued events |
|---|---|
| Node server (`react-router-serve`, Docker, the Express template) | The SDK's timer sends them; call `leverprice.preload()` at startup to fetch the config before the first visitor |
| Vercel or Netlify functions | `await leverprice.flush()` in the loader and the action before returning; with nothing queued it makes no network call |
| Cloudflare Workers | `waitUntil(leverprice.flush())`, with `waitUntil` imported from `cloudflare:workers` ([changelog](https://developers.cloudflare.com/changelog/2025-08-08-add-waituntil-cloudflare-workers)) |

On Workers, read the keys with `import { env } from "cloudflare:workers"` so the client can still be built at module scope, and use `@cloudflare/vite-plugin`, since v8 removed React Router's own Cloudflare dev proxy. The [Workers guide](https://leverprice.com/guides/cloudflare-workers) covers the isolate details.

Keep `/pricing` out of `prerender` in `react-router.config.ts`: a prerendered loader runs once during the build, and that one price ships to everyone. SPA mode (`ssr: false`) has no server at request time: only the root route and prerendered pages may have a loader there, and those run during the build ([SPA mode](https://reactrouter.com/how-to/spa)).

## Troubleshooting

| Symptom | Likely cause | Fix |
|---|---|---|
| No `__pp` cookie, and the price changes on reload | The route has no `headers` export, so its loader headers are dropped | Export `headers` and return `loaderHeaders` |
| Every visitor sees the same price | `/pricing` is listed in `prerender`, or a CDN caches the HTML | Remove it from `prerender` and send `Cache-Control: private, no-store` |
| The build fails over a server-only module | The SDK or Stripe is imported outside a `.server` module, or used inside the component | Keep both in `.server` modules and call them only from `loader` and `action` |
| Everyone gets the fallback price in production | `.env` isn't read in production, so the key is missing | Set `LEVERPRICE_SECRET_KEY` in the host's environment |
| 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, or pass `cookieSecure: false` in development |
| Exposures never show up on Vercel or Workers | The function ends before the SDK's queue is sent | `await leverprice.flush()` or `waitUntil(leverprice.flush())` |
| Stripe charges a different amount than the page showed | The action read a price from the form or used another product key | Call `getPrice()` in the action with the same key |

## Frequently asked questions

### Does this work on Remix v2?

The `getPrice()` call is the same, because Remix v2 loaders also receive a Fetch `Request`. How you return headers depends on your Remix version, though, which is one more reason to move to React Router v7 first.

### Can I price several plans on one page?

Yes. Add each plan to `products`, call `getPrice()` once per plan in the same loader with the same `request` object, and append every quote's cookies. The quotes share one visitor cookie, and the last value carries all the assignments.

### Can I test a subscription price?

Yes, with one difference in tracking. Use `mode: "subscription"`, add `recurring: { interval: "month" }` to `price_data` and drop `payment_intent_data`, which Stripe accepts only in payment mode. Then report the first payment with `leverprice.trackPurchase()` from your own Stripe webhook handler; it's labeled unverified, and renewals never count toward the test.

### Does a client-side link click count as a new visitor?

No. The loader's fetch carries the visitor's cookie, so they keep their variant, and the exposure logged on their first view isn't repeated.
