How to run a price test with PostHog feature flags (and where it breaks)

Set up a PostHog pricing experiment: price payloads on a multivariate flag, posthog-node on the server, Stripe revenue, stopping rules and where it breaks.

Short answer

PostHog can run a price test: store each price in the payload of a multivariate feature flag, evaluate it on your server with posthog-node so the page and Stripe Checkout use the same amount, send purchases back as events, and judge the experiment on revenue per user. The split stays fixed, and refunds and crawlers are your job.

  • Read the price with evaluateFlags() on your server: getFlag() logs the $feature_flag_called exposure and getFlagPayload() returns the amount.
  • Create one distinct_id on the server before the first flag call, keep it in a cookie, and bootstrap posthog-js with that ID.
  • A mean metric that sums revenue per user gives revenue per exposed visitor, because users without a purchase count as zero.
  • PostHog keeps the split you set until you end the experiment; its docs describe fixed splits and no bandit allocation.
  • As of November 2026, flags and experiments share one meter with 1,000,000 free requests a month.

PostHog can run a real price test. A multivariate feature flag holds each price in its payload, your server reads it with posthog-node, Stripe Checkout charges that amount, and a PostHog experiment compares revenue per user across the variants. If you already send events to PostHog, the setup below takes an afternoon. The second half covers where a pricing experiment strains a tool built for product features, so you can judge whether those gaps matter at your traffic.

Can PostHog run a pricing experiment?

Yes. PostHog Experiments run on feature flags: each person is assigned a variant by distinct_id and keeps it across sessions and devices as long as the ID stays the same (traffic allocation). A price is a variant like any other. You put the amount in the flag's payload and use it both for the price you display and for the amount you charge.

PostHog doesn't see money on its own. It sees the purchase events you send, or the Stripe tables you sync into its data warehouse, and it keeps the split you set until you end the experiment. As of November 2026, flags and experiments share one meter: the first 1,000,000 requests a month are free, then $0.0001 per request for the next million, less at higher volume (PostHog pricing).

How do you set up the flag for a price test?

Create a multivariate feature flag, for example pro-price, with one variant per price and a JSON payload on each; multivariate flags can carry a different payload per variant (flag payloads).

VariantSplitPayload
control50%{"amount": 2900, "currency": "usd"}
test50%{"amount": 3900, "currency": "usd"}

Store amounts in minor units, the way Stripe expects them, and create the experiment on this flag with the rollout at 100%. PostHog allows a baseline plus up to 19 test variants and recommends equal splits, because smaller arms take longer to reach significance (traffic allocation).

Keep the payload to the amount and currency. Copy, layout and plan names belong in other experiments, or you won't know which change moved revenue.

How do you read the price on the server with posthog-node?

Evaluate the flag on your server where the pricing page renders, and again where you create the checkout, with the same distinct_id. In current posthog-node releases, evaluateFlags() is the recommended API; getFeatureFlag() and getFeatureFlagPayload() still work but are deprecated (Node SDK).

price.ts
import { PostHog } from "posthog-node";
import type { Request } from "express";

export const posthog = new PostHog(process.env.POSTHOG_PROJECT_TOKEN!, {
  host: "https://us.i.posthog.com",
  secretKey: process.env.POSTHOG_SECRET_KEY, // phs_… key, enables local evaluation
});

const STANDARD = { variant: "control", amount: 2900, currency: "usd" };
const BOTS = /bot|crawl|spider|slurp|preview|facebookexternalhit|headless|lighthouse|curl|wget/i;

export async function priceFor(req: Request, distinctId: string) {
  if (BOTS.test(req.get("user-agent") ?? "")) return STANDARD; // never enroll crawlers

  const flags = await posthog.evaluateFlags(distinctId, { flagKeys: ["pro-price"] }).catch(() => null);
  if (!flags) return STANDARD; // PostHog unreachable: show your current price

  const variant = flags.getFlag("pro-price"); // sends $feature_flag_called, the exposure
  const payload = flags.getFlagPayload("pro-price") as { amount?: unknown; currency?: unknown } | undefined;
  const amount = payload?.amount;

  // Your own guardrails: a typo in a dashboard must never reach Stripe.
  if (typeof variant !== "string" || typeof amount !== "number" || !Number.isInteger(amount)) return STANDARD;
  if (amount < 1900 || amount > 4900 || payload?.currency !== "usd") return STANDARD;
  return { variant, amount, currency: "usd" };
}

What each part of that function is for:

  • getFlag() sends the $feature_flag_called event that experiments count as the exposure, the first time a value is read for a user; getFlagPayload() never sends events (exposures). Read the variant only where the price is shown or charged.
  • The secretKey turns on local evaluation. The SDK polls flag definitions every 30 seconds and evaluates in-process, and you're billed for the polls, 1 request each or 10 when definitions changed, not for every check (local evaluation).
  • The bot check runs before any flag call. In the browser, posthog-js drops events from known bot user agents by default (JS config), but a server flag call only sees the ID you pass, so a crawler with a fresh cookie looks like a new visitor. Crawlers should get your standard price and never enter the test (price tests and SEO).
  • The payload is JSON someone typed in a dashboard. A stray zero should land on your fallback price, not in Stripe.

How do you keep one distinct_id from first visit to checkout?

Create the ID on your server before the first flag evaluation, keep it in a first-party cookie, and hand the same ID to posthog-js through bootstrap. PostHog's own advice is to assign a durable ID before any flag is evaluated and to use the same distinct_id string on the backend and in client SDKs (stable identity for flags).

pricing-route.ts
import { randomUUID } from "node:crypto";
import { priceFor } from "./price";

app.get("/pricing", async (req, res) => {
  let distinctId: string | undefined = req.cookies.ph_vid; // cookie-parser
  if (!distinctId) {
    distinctId = randomUUID();
    res.cookie("ph_vid", distinctId, { maxAge: 180 * 86_400_000, httpOnly: true, secure: true, sameSite: "lax" });
  }
  const price = await priceFor(req, distinctId);
  res.render("pricing", { price, distinctId }); // the page prints price.amount, rendered on the server
});
pricing page
posthog.init("<ph_project_token>", {
  api_host: "https://us.i.posthog.com",
  bootstrap: { distinctID: "{{ distinctId }}", isIdentifiedID: false },
});

Set isIdentifiedID to false, or leave it out, for an anonymous ID; PostHog reserves true for signed-in IDs such as a database ID (bootstrapping). Don't read the price flag in posthog-js at all. The page already has the number from the server, and a browser read adds a second exposure source and a moment where the page can show the wrong price.

Logins are where IDs usually split. When a visitor signs up, save the same ID on their account and keep using it for flag calls, so a checkout from a second device gets the same variant. PostHog also offers device bucketing, which hashes on $device_id and stays stable through login on one device (device bucketing), and a "persist flag across authentication steps" option, which can't be combined with local evaluation or bootstrapping and slows flag responses (creating flags). If someone still ends up seeing both prices, PostHog's recommended setting removes them from the analysis (exposures).

How do you charge the flagged price in Stripe?

Call priceFor() again in the checkout route and send the amount to Stripe as inline price_data. The same distinct_id returns the same variant, so the charge matches the page. Store the ID in Stripe metadata under posthog_person_distinct_id, the key PostHog's revenue analytics uses to link Stripe data to people (connect to customers).

checkout-route.ts
app.post("/checkout", async (req, res) => {
  const distinctId: string | undefined = req.cookies.ph_vid;
  if (!distinctId) {
    res.redirect(303, "/pricing");
    return;
  }
  const price = await priceFor(req, distinctId); // never trust an amount sent by the browser
  const tags = { posthog_person_distinct_id: distinctId, price_variant: price.variant, price_amount: String(price.amount) };

  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: [{ quantity: 1, price_data: { currency: price.currency, unit_amount: price.amount, product_data: { name: "Pro" } } }],
    client_reference_id: distinctId,
    metadata: tags,
    payment_intent_data: { metadata: tags },
    success_url: "https://example.com/thanks",
    cancel_url: "https://example.com/pricing",
  });
  res.redirect(303, session.url!);
});

payment_intent_data.metadata matters later: Stripe copies a PaymentIntent's metadata onto its Charge, so a charge.refunded event arrives with the PostHog ID (Stripe metadata). For subscriptions, tax and local currencies on the Stripe side, see how to A/B test prices on Stripe.

How do you get revenue into a PostHog experiment?

Send it yourself as an event from your Stripe webhook, or sync Stripe into PostHog's data warehouse. The event route is quicker to build and shows results sooner; the warehouse route reads Stripe's own records.

Option A: send revenue events from your Stripe webhook

webhook.ts
// Inside your Stripe webhook handler, after stripe.webhooks.constructEvent() succeeds.
if (event.type === "checkout.session.completed" || event.type === "checkout.session.async_payment_succeeded") {
  const s = event.data.object;
  const distinctId = s.metadata?.posthog_person_distinct_id;
  if (s.mode === "payment" && s.payment_status === "paid" && distinctId) {
    posthog.capture({
      distinctId,
      event: "price_test_revenue",
      properties: {
        amount: ((s.amount_total ?? 0) - (s.total_details?.amount_tax ?? 0)) / 100, // before tax
        kind: "purchase",
        order_id: s.payment_intent,
        price_variant: s.metadata?.price_variant,
      },
    });
  }
}

if (event.type === "charge.refunded" && event.data.object.refunded) {
  const charge = event.data.object; // refunded === true only once the charge is fully refunded
  const distinctId = charge.metadata?.posthog_person_distinct_id;
  if (distinctId) {
    posthog.capture({
      distinctId,
      event: "price_test_revenue",
      properties: { amount: -Number(charge.metadata.price_amount) / 100, kind: "refund", order_id: charge.payment_intent },
    });
  }
}

await posthog.flush(); // serverless: send before the function returns

One event name carries money in and money out, so a single sum nets refunds out. The refund branch runs only when the charge's refunded field is true, which Stripe sets once a charge is fully refunded; after a partial refund it stays false (Charge object). It also assumes tax-exclusive prices without discounts, so the listed price equals the pre-tax revenue. Partial refunds need the difference from your own order records, and since Stripe can run your handler more than once for the same payment (fulfillment guide), record processed event IDs and skip repeats.

In the experiment, set the primary metric to a mean metric on price_test_revenue with the sum of amount. PostHog totals each user's values and then averages across users, and participants without the event count as 0 (experiment metrics), so the result is revenue per visitor with refunds netted out. Add a funnel from exposure to price_test_revenue with kind = purchase as a secondary metric to see conversion next to revenue.

Two settings on that metric need care:

  • Leave the conversion window empty, or make it longer than your refund window. Without one, PostHog counts events until the experiment ends (experiment metrics).
  • If you turn on outlier handling, check that the upper bound sits above your highest test price, or the cap trims exactly the revenue you're testing. PostHog lets you ignore zeros when it computes that bound (experiment metrics).

Option B: sync Stripe through the data warehouse

PostHog's Stripe source syncs tables including charges, invoices, refunds and subscriptions into its data warehouse (Stripe source), and an experiment can use a warehouse table for mean, ratio, retention or funnel metrics. You map a timestamp column, a warehouse join key and an events join key such as distinct_id, and PostHog counts only rows after the user's first exposure, inside the conversion window and the experiment dates (warehouse metrics).

The join key decides whether this works. Stripe rows contain your PostHog ID only if you put it there, and the docs' examples join on a plain column holding the ID. Confirm in the metric editor that your synced table exposes the ID you stored as a joinable column before you rely on this path. Expect a lag as well: in webhook sync mode, PostHog caches Stripe's events and applies them at the next scheduled sync (Stripe source).

PostHog's revenue analytics reads the same Stripe source, defers revenue across the months a charge covers, and links customers to people through posthog_person_distinct_id (Stripe in revenue analytics). It's a good place to watch revenue after the test; for the experiment itself, Option A gives you numbers as soon as the events are ingested.

How do you set up the experiment and decide when to stop?

Write the stopping rule into the experiment description before launch, and don't move it once numbers appear.

  1. Make revenue per user, from Option A or B, the primary metric. Keep conversion as a secondary metric.
  2. Size it. PostHog's calculator defaults the minimum detectable effect to 30% and shows estimates after 1 day and 100 exposures (running time). Required sample size grows with 1 ÷ (effect)², so detecting a 10% difference in revenue per visitor takes about nine times the traffic of a 30% one. Plan with your real baseline in the sample size calculator.
  3. Run whole weeks, so weekday and weekend buyers reach both arms.
  4. Pick the statistics up front. In Bayesian mode a result is significant when the chance to win passes 95% or drops below 5% by default (Bayesian statistics). If you'll check the dashboard daily, use the frequentist engine with sequential testing, which PostHog recommends for continuous monitoring (frequentist statistics).
  5. Set a floor of purchases per variant. PostHog shows results once each variant has 50 exposures (Bayesian statistics), far too few for a price decision.
  6. Turn on test-account filtering in the exposure criteria, so your own test checkouts don't count (exposures).
  7. When enrollment is enough but refunds haven't landed, freeze exposure: enrolled users keep their variants and new users stop entering (lifecycle).
  8. End by shipping the winner, which serves it at 100% within the flag's release conditions (lifecycle), then replace the flag with a constant price in code.

Where does PostHog break for pricing?

PostHog handles the experiment math well. The friction comes from the ways a price differs from a feature flag.

Client-side flags flicker

If you read the price flag with posthog-js, the page can render before flags arrive and then swap the number. PostHog's fix is bootstrapping flags from the server (bootstrapping flags). For prices, rendering on the server is simpler and also removes the risk that the page and the checkout disagree.

Revenue isn't verified by Stripe

A capture() call is whatever your code sends. A bug, a replayed request or a sandbox payment counts the same as a real sale unless your handler filters it. The warehouse route reads Stripe's records, at the cost of a sync lag and a join key you have to get right.

Refunds don't net out on their own

Nothing subtracts a refund from a purchase unless you send it as negative revenue or import refunds. Partial refunds need your own bookkeeping, and refunds that arrive after you end the experiment never reach the result.

The split stays even until you stop

PostHog's traffic allocation is a split you set, even by default, and its docs describe no bandit allocation (traffic allocation). If $39 is losing, half your visitors keep seeing it until you end the test, and at a few hundred sales a month that can mean weeks of lost revenue. Bandits versus fixed A/B tests compares the two.

Simulation of the Leverprice engine at 300 sales a month, next to an even split.

Crawlers count unless you stop them

posthog-js filters known bots in the browser, but a server flag call enrolls whoever you pass it. PostHog lists bot traffic as one cause of sample ratio mismatch, since bots may trigger exposures unevenly across variants (exposures).

What does Leverprice do differently?

Leverprice does only the price part. Your server calls getPrice(), which keeps each visitor on one price with a signed first-party cookie (and the same bucket on every device with userId), gives crawlers, link previews and monitors your standard price without enrolling them, and returns your own fallback price within 500 ms if anything fails. No Leverprice JavaScript runs in the browser, so there is nothing to flicker.

Revenue comes from your payment provider's signed webhooks, refunds reduce the revenue of the price that made the sale, and on Pro a Thompson-sampling bandit moves traffic toward the price with the highest revenue per visitor while keeping at least 5% on each. PostHog remains the stronger tool for product analytics and for every experiment that isn't a price. The side-by-side comparison covers when to use each.

Frequently asked questions

Can I run a PostHog price test without a backend?

Partly. Give each variant its own Stripe Payment Link, read the flag with posthog-js, hide the price until flags load, and send the Buy button to that variant's link. The browser chooses the link, so treat it as a quick experiment rather than a tamper-proof one.

Does PostHog count a visitor who saw both prices?

Not with the recommended setting: users exposed to multiple variants are removed from the analysis. The alternative setting analyzes them by the first variant they saw (exposures).

Should the experiment goal be conversion or revenue?

Revenue per user. A cheaper price almost always converts better, so a conversion goal picks the lowest price even when a higher one earns more per visitor. Keep conversion as a secondary metric to explain the result.

Can PostHog test subscription prices?

Yes, with the same flag. Create the Stripe session in subscription mode, put the PostHog ID in subscription_data.metadata, and send renewals from invoice.paid as extra revenue events. Freeze exposure once enrollment is done so 60 or 90 days of renewals can accumulate before you decide.

What happens to the price if PostHog is unreachable?

That depends on your code. In priceFor() above, a failed flag call, a missing variant or an invalid payload all return the standard price, so visitors see your current price instead of an error. With local evaluation, flags are computed in-process from definitions the SDK has already fetched, so the pricing page doesn't wait on a network call for each visitor.