How to A/B test prices in Nuxt

Price testing in Nuxt 4: price visitors in a Nitro server route, pass its cookie through server rendering, and charge the same price with Stripe Checkout.

Short answer

Call getPrice() in a Nitro server route with event.node.req and append each Set-Cookie value. During server rendering, Nuxt doesn't pass cookies from internal API calls to the browser, so copy them in useFetch's onResponse onto the page response. Charge quote.price from a POST route with Stripe price_data and pass quote.metadata whole.

  • During server rendering, Nuxt doesn't pass cookies from internal API calls back to the browser; copy them onto the page response in useFetch's onResponse.
  • Use useFetch rather than a bare $fetch in the page: it forwards the visitor's cookie and user agent to the internal call, so the server sees the real visitor.
  • Keep /pricing out of prerender, swr and isr route rules, and send Cache-Control: private, no-store.
  • Nuxt reads .env only for dev, build and generate; set LEVERPRICE_SECRET_KEY in the production environment yourself.

In Nuxt, the price belongs in a Nitro server route, and the page asks that route for it. During server rendering, that request never leaves the server, and the cookie it sets doesn't reach the browser unless you pass it on: the data fetching docs leave that step to you. Skip it and every first visit draws a price the visitor can't keep.

This guide covers Nuxt 4, which runs on Nitro 2 and h3 v1, with the Leverprice SDK and Stripe Checkout. Server-side price testing explains why the price has to come from your server rather than the browser.

How do you install Leverprice in Nuxt?

Install the SDK and Stripe's library, and put the keys in .env:

Terminal
npm install @leverprice/sdk stripe
.env
LEVERPRICE_SECRET_KEY=pp_sk_test_…
STRIPE_SECRET_KEY=sk_test_…

Nuxt loads .env for nuxt dev, nuxt build and nuxt generate, but not when the built server runs; production needs the variables in its own environment (.env). The test key comes from the dashboard when you create a project, and the docs cover the SDK's options.

Put the clients in server/utils, so they only ever run inside Nitro:

server/utils/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);
}

One client per server process keeps the signed config in memory between requests. fallbackPrice is what every visitor sees when Leverprice is off, slow (no config within 500 ms) or unreachable; minPrice and maxPrice are hard bounds checked on your server. Amounts are minor units: 1900 is $19.00.

How do you price visitors in a server route?

Give the price its own GET route. h3 v1 exposes Node's request as event.node.req, which the SDK reads as it is:

server/api/price.get.ts
import { formatPrice, leverprice } from "../utils/leverprice";

export default defineEventHandler(async (event) => {
  const quote = await leverprice.getPrice("pro", { request: event.node.req });
  for (const cookie of quote.setCookie) appendResponseHeader(event, "Set-Cookie", cookie);
  setResponseHeader(event, "Cache-Control", "private, no-store");
  event.waitUntil(leverprice.flush());
  return { price: formatPrice(quote) };
});

appendResponseHeader adds each cookie without replacing the others, and Cache-Control: private, no-store keeps one visitor's price out of shared caches. event.waitUntil() lets queued exposures go out after the response without delaying it (server directory). The route returns a formatted string only, so neither the SDK nor any key is needed in the browser.

The page fetches the price with useFetch and copies the route's cookies onto the page response while it renders on the server:

app/pages/pricing.vue
<script setup lang="ts">
import { appendResponseHeader } from "h3";

const event = useRequestEvent();

// During server rendering this call stays inside Nitro, so pass its cookies on to the browser.
const { data } = await useFetch("/api/price", {
  onResponse({ response }) {
    if (!event) return;
    for (const cookie of response.headers.getSetCookie()) appendResponseHeader(event, "Set-Cookie", cookie);
  },
});
</script>

<template>
  <main>
    <h1>Pro</h1>
    <p>{{ data?.price }}</p>
    <form method="post" action="/api/checkout">
      <button type="submit">Buy Pro</button>
    </form>
  </main>
</template>

Two things happen during server rendering. First, useFetch with a relative URL forwards the visitor's headers, cookie and user agent included, to the internal call through useRequestFetch. That's why the route sees a returning visitor's cookie and still recognizes crawlers. A bare $fetch in <script setup> leaves the visitor's cookies behind during server rendering, so every render would look like a brand-new visitor.

Second, the route's Set-Cookie headers come back to the renderer instead of the browser. onResponse copies them onto the page response through the event from useRequestEvent(). Without that copy, the first visit sets no cookie, and sticky assignment fails exactly where it matters most: on a visitor's first page view.

After hydration, Nuxt reuses the server's result instead of fetching again. When a visitor reaches /pricing through a client-side link, useFetch runs in the browser, which sends the cookie and stores the new one itself; event is undefined there, so the copy is skipped.

Then make sure nothing caches the page itself:

nuxt.config.ts
export default defineNuxtConfig({
  routeRules: {
    "/pricing": { headers: { "cache-control": "private, no-store" } },
  },
});

Don't give /pricing a prerender, swr or isr rule, which would cache one visitor's price for everyone, or ssr: false, which leaves the price blank until the browser fetches it (hybrid rendering).

How do you charge that price with Stripe?

The buy form posts to a second server route, which prices the visitor again and redirects to Stripe:

server/api/checkout.post.ts
import { leverprice, stripe } from "../utils/leverprice";

export default defineEventHandler(async (event) => {
  const quote = await leverprice.getPrice("pro", { request: event.node.req }); // never trust a price from the form
  for (const cookie of quote.setCookie) appendResponseHeader(event, "Set-Cookie", cookie);

  const { origin } = getRequestURL(event);
  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`,
  });

  event.waitUntil(leverprice.flush());
  return sendRedirect(event, session.url!, 303);
});

The visitor's cookie maps them to the same variant, so Stripe shows the amount the page showed. The form sends no price, and the route wouldn't read one if it did. price_data makes a one-off price from quote.price, with unit_amount in minor units (Checkout Sessions API), and quote.metadata goes in 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 follow the same pattern with their own custom-price fields: ad-hoc prices when you create a Polar checkout, custom_price in cents on a Lemon Squeezy checkout (with the 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 the exact calls. Lemon Squeezy stops processing payments on March 31, 2027 (announcement).

How does verified revenue work?

Stripe's signed webhooks go to Leverprice, not to your Nuxt app, so there's no webhook route to write. In the dashboard, open Payments and connect Stripe in Test mode. Add the URL it gives you as a webhook 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.

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

Stripe confirms each purchase to Leverprice; your Nuxt app only creates the checkout.

How do regional prices work in Nuxt?

Regional prices (SDK 0.4 or later) give each country its own price, and in a running test each visitor keeps one variant at that variant's price for their country. Name the header your host sets: x-vercel-ip-country on Vercel, cf-ipcountry on Cloudflare.

server/utils/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 },
      },
    },
  },
});

The option has no default, because a header the visitor controls would let them choose their own price. useFetch forwards the visitor's request headers to /api/price during server rendering, country header included, and the checkout already sends quote.currency to Stripe. Bots, unknown countries and currencies missing from regional 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, open http://localhost:3000/pricing in Chrome or Firefox, and select the document request in the Network tab. Its response should carry Set-Cookie: __pp=…, which proves the server-rendering copy works.
  2. Reload a few times: same price. A private window is a new visitor and may get another one.
  3. Go to the home page and follow a link to /pricing. The browser calls /api/price itself and shows the same price.
  4. Run curl -i http://localhost:3000/pricing. Command-line clients count as bots, so you get the standard price and no cookie.
  5. Click Buy and pay with 4242 4242 4242 4242 on Stripe's test page (Stripe testing). The amount matches the page, and the order appears in Leverprice as verified test revenue.
  6. Restart with LEVERPRICE_DISABLED=1 npm run dev to see the kill switch: fallback price, no cookie, no network calls.

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

What changes in production?

Use the live keys (pp_sk_live_… and Stripe's live key) and connect a Live-mode webhook endpoint; test and live data never mix. Because the built server doesn't read .env, set both variables in your host's environment, or pass them on the command line that starts .output/server/index.mjs.

On serverless presets such as Vercel, Netlify or Cloudflare, event.waitUntil() already keeps each invocation alive until its events are sent, so the routes above need no change. On a long-lived Node server, the SDK's timer would send them anyway. To switch the test off in an emergency, set LEVERPRICE_DISABLED=1 and restart or redeploy: everyone gets your fallback price.

Troubleshooting

SymptomLikely causeFix
No __pp cookie on the first page load, but one appears after a client-side visitThe internal call's Set-Cookie never reaches the browser during server renderingCopy the cookies in onResponse as shown
The price changes on every reloadThe page calls $fetch directly, which leaves the visitor's cookie behind during server renderingUse useFetch, or pass useRequestHeaders(["cookie", "user-agent"]) as headers
Every visitor sees the same price/pricing has a prerender, swr or isr rule, or the site is built with nuxt generateRemove the rule and serve /pricing from Nitro with Cache-Control: private, no-store
The price appears only after the page loadsAn ssr: false route rule renders /pricing in the browserTurn server rendering back on for /pricing
Everyone gets the fallback price in productionThe built server doesn't read .envSet LEVERPRICE_SECRET_KEY in the production environment
Exposures never show up on a serverless hostThe function stops before the SDK's queue is sentKeep event.waitUntil(leverprice.flush()) in both routes
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

Frequently asked questions

Can the rest of the site be prerendered?

Yes. Route rules apply per path, so marketing pages can use prerender: true while /pricing and the two API routes stay server-rendered. A site built entirely with nuxt generate has no server to price visitors.

Why can't the page call the SDK directly?

Code in app/ is bundled for the browser as well as the server, and the secret key must never reach a browser bundle. Keeping the SDK in server/ and asking a route for the price keeps it on your side.

Can I test a subscription price?

Yes, with a tracking caveat that depends on the provider. Polar's webhook verifies the first payment of a subscription. With Stripe, use mode: "subscription" with recurring in price_data and no payment_intent_data, then report the first payment with leverprice.trackPurchase() from your own webhook handler; it shows as unverified. Renewals never count toward a test.

Will Nuxt 5 change this?

Nuxt 5, unreleased as of November 2026, moves to Nitro v3 and h3 v2, which is built on standard Request and Response objects and renames several helpers (Nitro v3 beta). The SDK accepts a standard Request too, so only the h3 helper calls around getPrice() should need updating.