Server-side price testing: why your price should never be decided in the browser

Server-side price testing explained: why browser scripts flicker, get blocked and charge the wrong price, and how to bucket, cache and price bots correctly.

Short answer

Server-side price testing means your server picks each visitor's price before the page is sent, renders it into the HTML and charges the same price at checkout. Scripts that swap the price in the browser flicker, stop working when blocked, can be edited by the visitor and leak test prices into caches and search results.

  • Chrome's guidance says anti-flicker snippets hide the page until the test script runs or a timeout, typically 4 seconds, passes.
  • When an ad blocker blocks a client-side testing script, no experiment runs for that visitor and the tool can't tell.
  • Bucket visitors by a hash of a stable id, and store the assignment so later weight changes only move new visitors.
  • Any response that renders a tested price needs Cache-Control: private, even when it sets no cookie.
  • Give crawlers and link previews the standard price, and price prefetch requests without counting them as views.

A price test asks one question per visitor: which number do we show? Answer it in the browser and visitors either glimpse your default price or stare at a blank page while a script decides, visitors with blockers never join the test, and anyone with developer tools can pick their own price. Answer it on your server and the page arrives with the right price already in the HTML, the checkout charges that same price, and the browser has nothing to decide.

How does client-side price testing work?

A script in the page head downloads the experiment setup, picks a variant for the visitor and rewrites the price on a page that was rendered with your default price. The choice is stored in a cookie or localStorage, events are sent from the browser, and the checkout learns the price from the browser or from a price ID the script passes along.

The appeal is that nothing changes on your backend: paste a snippet, edit prices in a dashboard. For headlines and button colors that trade-off is often acceptable. For prices, almost every step has a failure mode.

What goes wrong when the browser decides the price?

Six things, and each one either corrupts your data or reaches a customer.

Flicker

The page arrives showing your default price, and the script swaps it a moment later. To hide the swap, many tools ship an anti-flicker snippet that sets the whole page to opacity 0 until the experiment script finishes or a timeout passes. Chrome's guide to client-side testing puts that timeout at typically 4 seconds, notes that the trick gives up progressive rendering, and recommends server-side testing for performance-critical pages because it removes flicker without any render-blocking cost (Chrome for Developers). Its preferred client-side fix, a small script marked blocking="render", removes the flicker by delaying the first paint instead.

On a pricing page the flicker is worse than cosmetic. A visitor who glimpses $29 before the script shows $39 has seen both prices.

Ad blockers and script blockers

Testing scripts load from third-party domains that ad and script blockers can block. Optimizely's documentation says that if its assets are on a visitor's block list, no experiments run for that visitor, there is no workaround, and the tool has no way to know (Optimizely).

For a price test, that means a slice of your visitors always sees the default price and never appears in the results. Because blocker users aren't a random group, the test measures everyone except them, while their purchases at the default price stay invisible to it.

The price on the page differs from the price at checkout

The script changed text on a page. Nothing forces the checkout to agree. A Buy button that points at a fixed payment link, a price ID cached from an earlier visit or a localStorage entry cleared between sessions can each produce a checkout at a different price than the one shown, which means charging a customer an amount the page never promised.

Visitors can edit the price

Anything the browser decides, the visitor can change: edit the stored variant, rewrite the displayed number, or change a hidden field that carries the amount or price ID to your checkout. If the checkout trusts any of it, the visitor picks their own price. OWASP's input validation guidance says to validate on the server even when the browser checks the same fields (OWASP).

Caching

Client-side tests fight caches from both sides. Your HTML is cached with the default price baked in, which is why the swap has to happen after the page loads. And if the test configuration ships as a cached script, stopping a test or changing prices doesn't reach everyone at once: some visitors keep running the old setup until their copy expires.

SEO

Google queues every page that returns 200 for rendering and runs its JavaScript in an evergreen Chromium (Google), so it can index whatever price the script chose for that render. Googlebot generally doesn't support cookies (Google), so each render can draw a new variant. If the page also carries structured data with your standard price, the markup and the visible price disagree, and Google requires structured data to truly represent the page (Google). Does A/B testing prices hurt SEO? covers the search side in full.

Price decided in the browserPrice decided on the server
First paintDefault price, then a swap or a hidden pageThe assigned price
Visitors with blockersNever enter the testEnter the test like everyone else
Checkout amountWhatever the browser passes alongRecomputed from the stored assignment
Editing the pricePossibleThe amount never comes from the browser
CrawlersA random variant per render, or the defaultThe standard price, by rule
CachingHTML caches fine; the swap happens after loadNeeds private caching or edge rendering

The last row is the honest cost of the server-side approach, and the caching section below deals with it.

How does server-side price assignment work?

The server picks the price inside the request that renders the page, remembers the choice, and repeats it at checkout.

The price is decided once per visitor, on your server, and the checkout reuses the decision.
  1. Find a stable id. For a signed-in user, the account id. For everyone else, a random id from a first-party cookie, signed with an HMAC so it can't be forged. If the cookie is missing or its signature fails, mint a new id from a secure random source.
  2. Hash the id into a bucket: SHA-256 of a per-experiment salt plus the id, first four bytes as an unsigned integer, modulo 10,000. The same id always lands in the same bucket, and the salt keeps one experiment's buckets independent of another's.
  3. Map the bucket to a price by walking the prices in order and adding up their traffic weights. With a 50/50 split, buckets 0 to 4,999 get the first price.
  4. Store the assignment in the signed cookie. This matters for bandits: when weights move, a recomputed bucket could point at a different price, so the stored assignment is what keeps a returning visitor on theirs.
  5. Render the price into the HTML and send the Set-Cookie header with the response.
  6. At checkout, run the same lookup on the same request. It reads the cookie, gets the same price, and the server creates the checkout session with that amount and a signed record of the assignment.

Steps 2 and 3 fit in a dozen lines:

bucket.ts
import { createHash } from "node:crypto";

// weights in basis points: [5000, 5000] is a 50/50 split
export function pickVariant(salt: string, visitorId: string, weights: number[]): number {
  const digest = createHash("sha256").update(`${salt}:${visitorId}`).digest();
  const bucket = digest.readUInt32BE(0) % 10_000;
  let total = 0;
  for (const [index, weight] of weights.entries()) {
    total += weight;
    if (bucket < total) return index;
  }
  return weights.length - 1;
}

The Leverprice SDKs implement all six steps, with visitor and user ids HMAC-hashed on your server so Leverprice only sees the hash, and every price checked against the minimum and maximum you set in your own code.

What about the same person on two devices?

A cookie lives in one browser, so an anonymous visitor on a laptop and a phone counts as two visitors. Once they sign in, key them by account: pass the user id (userId in the SDK) and the account, rather than the browser, is bucketed. If they first saw a price while signed out, the assignment stored in that browser's cookie still wins there, so signing in doesn't flip their price mid-visit.

With a fixed split, the same bucket means the same price on every device. With a bandit, weights move over time, so a device that first shows up weeks later can map the same bucket to a different price. If a buyer's price must match across devices for the life of a test, use a fixed split for that test.

What happens when the price service is slow or down?

Your page must never wait on it for long. Give the lookup a hard timeout, fall back to your current price on any failure, and never let an error from the testing layer throw into your request handler.

The SDK works this way: if no signed config arrives within 500 ms, the service is down, the config is invalid or the kill switch LEVERPRICE_DISABLED=1 is set, getPrice() returns the fallbackPrice from your own code with a reason (no_config, disabled and so on) instead of throwing. A browser that got the fallback during an outage keeps it until it has been inactive for 30 minutes, through a small __pp_f cookie, so its price doesn't flip back and forth while the service recovers. In normal operation the signed config is cached in memory and refreshed in the background every 30 seconds, so a typical lookup never waits on the network.

Two more guards belong in any server-side setup. Check every price against a minimum and maximum in your own code, so nothing outside the range you chose can reach a checkout. And accept configuration only if it is signed: the SDK verifies a chain from an offline root key to a signed keyset to the config, versions only move forward, and configs expire. Signed price configs explains why each link exists.

A config is used only if every signature in the chain checks out on your server.

How do you cache pages that show per-visitor prices?

Keep them out of shared caches. Any response that contains a tested price should send Cache-Control: private or no-store. MDN's reference recommends private for personalized content and warns that without it, the response can be stored in a shared cache and reused for other users (MDN).

Vary: Cookie doesn't rescue shared caching either. Vary keys stored copies on the request headers it names (MDN), and every visitor's signed cookie is unique, so each visitor ends up with a private copy anyway.

ApproachHow it worksTrade-off
Don't cache the pageCache-Control: private, no-store on every response that shows a test priceEach view renders on your server; fine for a handful of pages
Render the price at the edgeThe CDN caches the HTML with a placeholder; an edge function fills in the visitor's priceNeeds an edge runtime; the shell stays fast and cacheable
Keep the price off the pageThe page links to checkout, and the tested price first appears on the provider's checkout pageVisitors don't see the price until checkout

Edge rendering on Cloudflare Workers looks like this. The page comes from the cache with your standard price inside a data-price element, and HTMLRewriter replaces it as the page streams through (Cloudflare):

worker.ts
import { Leverprice } from "@leverprice/sdk";

let leverprice: Leverprice | undefined; // one client per isolate

export default {
  async fetch(request: Request, env: { LEVERPRICE_SECRET_KEY: string }, ctx: ExecutionContext) {
    leverprice ??= new Leverprice({
      secretKey: env.LEVERPRICE_SECRET_KEY,
      products: { pro: { currency: "usd", fallbackPrice: 2900, minPrice: 1900, maxPrice: 4900 } },
    });
    const [page, quote] = await Promise.all([fetch(request), leverprice.getPrice("pro", { request })]);
    const shown = new Intl.NumberFormat("en-US", { style: "currency", currency: quote.currency }).format(quote.price / 100);
    const rewritten = new HTMLRewriter()
      .on("[data-price]", { element(el) { el.setInnerContent(shown); } })
      .transform(page);
    const response = new Response(rewritten.body, rewritten);
    response.headers.set("Cache-Control", "private, no-store"); // the cached copy is the shell, not this
    for (const cookie of quote.setCookie) response.headers.append("Set-Cookie", cookie);
    ctx.waitUntil(leverprice.flush());
    return response;
  },
};

In Next.js, reading cookies in a page makes the route render per request; with Cache Components, only the part inside the Suspense boundary that reads them does (Next.js). That protects you from accidental static prerendering, but not from a CDN rule you add in front of it.

Give bots your standard price, don't assign them and don't count them. Crawlers generally don't keep cookies, so an enrolled crawler would draw a new price on many visits; Google says Googlebot generally doesn't support cookies and sees what a cookieless visitor sees (Google). Link previews multiply a single fetch: when someone pastes your pricing page into Slack, its preview bot (it identifies as Slackbot-LinkExpanding, per Slack) fetches the page once and shows the result to the whole channel. And bots never buy, so every bot counted as a visitor drags down the revenue per visitor of whichever price it landed on.

If your current price is one of the test prices, as it should be, a crawler sees exactly what your control group sees: a price real visitors are paying that day.

The SDK gives crawlers, link previewers, headless browsers, uptime monitors and command-line clients the standard price with reason bot, sets no cookie and logs no exposure. If you run your own bot detection, pass bot: true or bot: false and it wins.

Prefetches are the opposite case: real browsers, but nobody may ever look. A <link rel="prefetch"> request carries Sec-Purpose: prefetch, and MDN notes that servers can use the header to treat such requests differently when counting page visits (MDN). Pages fetched by the Speculation Rules API send Sec-Purpose: prefetch or prefetch;prerender (MDN). Price these requests normally, so the page is right if the visitor opens it, but don't count them as exposures. The SDK does both for Sec-Purpose, Purpose, X-Moz and Next.js's Next-Router-Prefetch header. If a price renders before it is visible, in a hidden tab or a closed modal, switch to manual exposures and log one when the price is actually on screen.

How do you send events from serverless functions?

Flush them before the function is frozen. AWS Lambda freezes the execution environment when your handler returns, and background work that hasn't finished only resumes if that environment is reused later (AWS). An exposure still queued in memory can wait indefinitely or disappear with the instance.

PlatformFlush with
AWS Lambda, Netlify Functions, other short-lived functionsawait leverprice.flush() before returning
Cloudflare Workersctx.waitUntil(leverprice.flush())
Next.js 15.1 or laterafter(() => leverprice.flush()) from next/server
Vercel, other frameworkswaitUntil(leverprice.flush()) from @vercel/functions

Vercel recommends after() for Next.js 15.1 and later and documents waitUntil() for other frameworks; either way the work keeps the function's own timeout (Vercel). On long-lived servers you don't need any of this: the SDK sends queued exposures every two seconds, and purchases and refunds reported from your server are retried and kept until they are delivered.

What does server-side price testing look like in code?

Every runtime does the same two things: ask for the price with the incoming request, and append every Set-Cookie value the SDK returns. Here are three.

Next.js route handler

Server Components can read cookies but can't set them (Next.js), so new visitors get priced in a route handler, a server action or proxy.ts. The checkout is a natural route handler:

app/api/checkout/route.ts
import { after } from "next/server";
import Stripe from "stripe";
import { getUserId } from "@/lib/auth"; // yours: the signed-in user's id, or undefined
import { leverprice } from "@/lib/leverprice";

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

export async function POST(request: Request) {
  const quote = await leverprice.getPrice("pro", { request, userId: await getUserId() });
  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: `${process.env.SITE_URL}/welcome`,
    cancel_url: `${process.env.SITE_URL}/pricing`,
  });

  const response = new Response(null, { status: 303, headers: { Location: session.url ?? "/pricing" } });
  for (const cookie of quote.setCookie) response.headers.append("Set-Cookie", cookie);
  after(() => leverprice.flush()); // send queued exposures after the response
  return response;
}

Express

A Node IncomingMessage works as the request, and res.append takes the whole cookie array:

server.ts
import express from "express";
import { getUserId } from "./auth.js"; // yours: the signed-in user's id, or undefined
import { leverprice } from "./leverprice.js";

const app = express();

app.get("/pricing", async (req, res) => {
  const quote = await leverprice.getPrice("pro", { request: req, userId: await getUserId(req) });
  res.append("Set-Cookie", quote.setCookie);
  res.set("Cache-Control", "private, no-store");
  res.render("pricing", { price: quote.price, currency: quote.currency }); // price in minor units
});

Django

The Python SDK takes Django's HttpRequest, and apply_cookies writes the cookies onto the response. Django's never_cache decorator adds Cache-Control: max-age=0, no-cache, no-store, must-revalidate, private (Django):

pricing/views.py
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from leverprice import apply_cookies

from .leverprice_client import leverprice  # one shared client per process


@never_cache
def pricing(request):
    user_id = request.user.pk if request.user.is_authenticated else None
    quote = leverprice.get_price("pro", request, user_id=user_id)
    return apply_cookies(render(request, "pricing.html", {"quote": quote}), quote)

All five SDKs (JavaScript, Python, PHP, Ruby and Go) pass the same conformance vectors, so a Next.js front end and a Django checkout give the same visitor the same price. The docs cover install, keys and the full reference.

Guides by framework

Pick your framework for a full walkthrough with the request object and cookie handling it needs.

FrameworkWhat you pass to getPriceGuide
Next.jsThe Fetch Request in route handlers and server actionsPrice testing in Next.js
React RouterThe loader's Fetch RequestPrice testing in React Router
SvelteKitThe Fetch RequestPrice testing in SvelteKit
Nuxtevent.node.req, cookies via appendResponseHeaderPrice testing in Nuxt
AstroThe Fetch RequestPrice testing in Astro
ExpressThe Node req, cookies via res.appendPrice testing in Express
Honoc.req.rawPrice testing in Hono
Cloudflare WorkersThe Fetch Request, plus ctx.waitUntil(leverprice.flush())Price testing on Cloudflare Workers
DjangoHttpRequest, cookies via apply_cookiesPrice testing in Django
FlaskFlask's requestPrice testing in Flask
FastAPIStarlette's Request, with get_price_asyncPrice testing in FastAPI
LaravelThe request, with leverprice/leverprice-phpPrice testing in Laravel
Railsrequest, with the leverprice gemPrice testing in Rails
Go*http.Request, cookies via WriteCookiesPrice testing in Go

For the testing method itself (choosing prices, deciding a winner, rolling it out), read how to A/B test prices, and for the bigger picture, the complete guide to price testing.

Frequently asked questions

Is server-side price testing slower than client-side testing?

Not for the visitor: the price arrives with the first HTML instead of after a script loads. Your server does one extra lookup, which the SDK answers from a signed config cached in memory, and which never waits longer than 500 ms when no config is loaded yet.

Can I run a server-side price test on a static site?

Not with the price in the page, because one static file can't differ per visitor. Either fill the price in at the edge, or send the Buy button through a link that assigns the visitor and redirects to a checkout for their price, so the tested price first appears on the checkout page.

Does server-side testing work with a single-page app?

Yes. Render the first price on the server, or have the app fetch it from an endpoint that calls the SDK with the incoming request, so the cookie is read and set. Price the checkout the same way, and never let the app send the price back.

Yes. The cookie is only set when a visitor is first assigned. Their later visits carry no Set-Cookie, and a CDN set up to cache HTML will store those pages and serve them to other people.

How do I check that my setup works?

Open the pricing page in two private windows and compare the prices, reload each to confirm the price sticks, request the page with a crawler user agent to confirm the standard price, and make sure the checkout amount matches the page in every case.