Short answer
Pass Express's req straight to getPrice(), append quote.setCookie with res.append before rendering, and send Cache-Control: private, no-store. In the checkout route, price the visitor again, create a Stripe Checkout session with price_data and quote.metadata, and redirect with 303. Preload the config at startup and flush queued events on shutdown.
- Express hands getPrice() a Node IncomingMessage, which the SDK reads as is; no adapter is needed.
- res.append accepts the whole setCookie array, but a later res.set('Set-Cookie') would replace it.
- A pricing page served by express.static shows one price to everyone: render it from a route instead.
- On a long-lived server, call leverprice.preload() at startup and await leverprice.flush() when the process gets SIGTERM.
Express is the easiest place to run a price test, because nothing renders before your handler decides: you get the request, set headers, then send HTML. The Leverprice SDK reads Express's req as it is, and res.append() takes its whole cookie array in one call. What breaks in Express apps sits around the route instead: a static pricing.html that answers first, a cache in front, or a deploy that kills the process before queued events go out.
This guide uses Express 5 with the Leverprice SDK and Stripe Checkout. Server-side price testing explains why the price has to be decided on your server rather than in the browser.
How do you install Leverprice in an Express app?
Install Express, the SDK and Stripe's library:
npm install express @leverprice/sdk stripeLEVERPRICE_SECRET_KEY=pp_sk_test_…
STRIPE_SECRET_KEY=sk_test_…
APP_URL=http://localhost:3000Express doesn't read .env itself. Node 20.6 and later can load it with node --env-file=.env server.js, and in production your host's environment takes its place. The test key comes from the dashboard when you create a project, and the docs list the SDK's options.
Create the client once per process:
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 },
},
});
leverprice.preload(); // long-lived server: fetch the signed config at startup
export function formatPrice({ price, currency }) {
const format = new Intl.NumberFormat("en-US", { style: "currency", currency });
const digits = format.resolvedOptions().maximumFractionDigits ?? 2;
return format.format(price / 10 ** digits);
}preload() fetches the signed config when the server boots, so the first visitor after a deploy doesn't wait for it. If Leverprice is off, slow (no config within 500 ms) or down, getPrice() returns fallbackPrice and never throws for those reasons. minPrice and maxPrice are hard bounds the SDK checks on your server, in minor units: 1900 is $19.00.
How do you render the price in a route?
Pass req to getPrice(), append the cookies, and render:
import express from "express";
import Stripe from "stripe";
import { formatPrice, leverprice } from "./leverprice.js";
const app = express();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
app.get("/pricing", async (req, res) => {
const quote = await leverprice.getPrice("pro", { request: req });
res.append("Set-Cookie", quote.setCookie); // an array, usually empty
res.set("Cache-Control", "private, no-store");
res.send(`<!doctype html>
<h1>Pro</h1>
<p>${formatPrice(quote)}</p>
<form method="post" action="/checkout"><button>Buy Pro</button></form>`);
});The SDK accepts a Node IncomingMessage, so req goes in unchanged, and it reads the visitor's cookie and user agent from it. res.append() accepts an array and adds to any Set-Cookie values already on the response (response API). The same page notes that calling res.set() on that header afterwards resets it, so any middleware that runs later has to use res.append() or res.cookie() too.
Swap the template string for res.render() and your view engine of choice; the order is what matters. The cookies must be appended before the response is sent, which a handler that decides everything up front makes easy.
Express 5 also forwards a rejected promise from an async handler to your error middleware, so an exception in this route ends in a proper error response instead of a hung request (migrating to Express 5). getPrice() won't be the cause: it falls back instead of throwing.
Cache-Control: private, no-store matters more in Express than in most frameworks, because Express sends no caching header of its own. If a CDN or a cache rule stores the HTML, every visitor gets the first visitor's price.
How do you charge the same price with Stripe Checkout?
The buy form posts to a second route, which prices the visitor again and redirects to Stripe:
app.post("/checkout", async (req, res) => {
const quote = await leverprice.getPrice("pro", { request: req }); // 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: `${process.env.APP_URL}/thanks`,
cancel_url: `${process.env.APP_URL}/pricing`,
});
res.append("Set-Cookie", quote.setCookie);
res.redirect(303, session.url);
});
const server = app.listen(3000);
// Send queued exposures before the process exits on deploys and restarts.
process.on("SIGTERM", () => {
server.close(async () => {
await leverprice.flush();
process.exit(0);
});
});The route needs no body parser, since it reads nothing from the form. The visitor's cookie maps them to the same variant, so Stripe shows the amount the page showed. Express 5 takes the status first in res.redirect(303, url); the old res.redirect(url, status) order is gone.
price_data turns quote.price into a one-off price, with unit_amount in minor units (Checkout Sessions API). Pass quote.metadata whole, on the session and the payment intent; it's the signed record of what this visitor was shown. Polar, Lemon Squeezy and Dodo Payments take the same quote through their own custom-price fields: ad-hoc prices on a Polar checkout session, custom_price on a Lemon Squeezy checkout (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 each call. Lemon Squeezy stops processing payments on March 31, 2027 (announcement).
How does verified revenue work with Express?
Stripe sends its signed webhooks straight to Leverprice, so you don't add a webhook route for the test. In the dashboard, open Payments and connect Stripe in Test mode. Add the URL it gives you as a Stripe webhook endpoint for checkout.session.completed, checkout.session.async_payment_succeeded and charge.refunded, then paste that endpoint's signing secret back into Leverprice.
If you already verify Stripe webhooks in Express for fulfillment, keep that route and its express.raw() body parser exactly as they are. Leverprice gets its own endpoint in Stripe, with its own signing secret, so the two never interfere.
The signing secret can confirm events but can't move money; an API key never goes there. Refunds reduce the revenue of the price that sold, and Stripe verification covers one-time payment sessions like this one.
How do regional prices work behind a CDN?
Regional prices (SDK 0.4 or later) give each country its own price, and during a test each visitor keeps one variant at that variant's price for their country. Express doesn't know the country, but the CDN in front of it does: Cloudflare sends cf-ipcountry (Cloudflare headers), and CloudFront sends cloudfront-viewer-country once you add it to an origin request policy (CloudFront headers).
export const leverprice = new Leverprice({
secretKey: process.env.LEVERPRICE_SECRET_KEY,
countryHeader: "cf-ipcountry", // set by Cloudflare, 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 a visitor can send would let them pick their own price. That's an Express-specific risk: if your server also accepts traffic that skips the CDN, anyone can send cf-ipcountry themselves. Only name the header when the origin is reachable through the CDN alone. Both routes pass req, so they read the country with no other change, and the checkout already sends quote.currency to Stripe. Bots, unknown countries and currencies you didn't list get the standard price; regional pricing has the details.
How do you test it locally?
- Start the server with
node --env-file=.env server.jsand openhttp://localhost:3000/pricingin Chrome or Firefox. A__ppcookie should appear, with a price inside your range. - Reload a few times: the price holds. A private window is a new visitor and may get another one.
- Run
curl -i http://localhost:3000/pricing. curl counts as a bot, so you get the standard price and noSet-Cookie. Add-A "Mozilla/5.0"and the cookie appears, which is a quick way to read the raw header. - Click Buy and pay on Stripe's test page with
4242 4242 4242 4242(Stripe testing). The amount matches the page, and the order shows up in Leverprice as verified test revenue. - Restart with
LEVERPRICE_DISABLED=1in the environment. Every visitor gets the fallback price, with no cookie and 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 used.
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 stay separate. Under a process manager, Docker or systemd, the SIGTERM handler above lets each deploy send its last queued exposures before the old process exits. The SDK's timers don't keep the process alive by themselves, so without that handler the last couple of seconds of events can be lost.
If you run Express as a serverless function instead, the process can freeze right after the response. Call await leverprice.flush() before res.send() and res.redirect(); when nothing is queued it returns without a network call. To switch the test off in an emergency, set LEVERPRICE_DISABLED=1 and restart: every visitor gets your fallback price.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Everyone sees the same price and no __pp cookie appears | A static file, such as public/pricing/index.html, answers before your route | Delete the static copy and render /pricing from the route |
| The cookie vanishes from some responses | Middleware later calls res.set("Set-Cookie", …), which replaces appended values | Use res.append() or res.cookie() everywhere |
curl never shows a Set-Cookie header | Command-line clients are treated as bots | Send a browser user agent with -A "Mozilla/5.0" |
| Everyone gets the fallback price | The process started without the key, for example without --env-file | Load the environment before Express starts |
| Exposures from just before a deploy are missing | The process exits before the SDK sends its queue | Keep the SIGTERM handler that awaits leverprice.flush() |
| Visitors in one country can choose their regional price | The origin accepts requests that skip the CDN, so the country header can be forged | Lock the origin to CDN traffic, or drop countryHeader |
| The price changes on every reload, but only in Safari | The 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
Does this work with Fastify, Koa or NestJS?
Yes. The SDK reads any Node IncomingMessage: pass request.raw in Fastify, ctx.req in Koa and req in NestJS on the Express adapter, then append quote.setCookie with the framework's own header method.
Should I use res.cookie() instead of appending the header?
No need. quote.setCookie already holds finished header values with the SDK's attributes, and res.append() sends them unchanged; rebuilding them through res.cookie() only adds a chance to drop an attribute.
Can I test a subscription price?
Yes. Use mode: "subscription", add recurring: { interval: "month" } to price_data and drop payment_intent_data, which only payment mode accepts. Leverprice's Stripe webhook verifies one-time sessions only, so report the first payment with leverprice.trackPurchase() from your existing Stripe webhook route; it shows as unverified, and renewals never count toward the test.
What happens to the page if Leverprice is down?
The page keeps working. With no signed config within 500 ms, getPrice() returns your fallback price, and that browser keeps the fallback for the rest of its session, so nobody sees the price flip mid-visit.