Short answer
Call getPrice() in +page.server.ts with event.request, then pass each Set-Cookie value to cookies.set(), because SvelteKit rejects set-cookie in setHeaders. Return a formatted price to the page and create the Stripe Checkout session in a form action that prices the visitor again, passes quote.metadata whole and redirects with external: true.
- setHeaders can't set cookies in SvelteKit, so the price cookie goes through cookies.set() with the attributes the SDK chose.
- SvelteKit 3 refuses redirects to another origin unless you pass external: true, and the redirect to Stripe Checkout is one.
- The default template preloads page data on hover, which runs the server load; set preloading to tap on links to /pricing so a hover isn't counted as a view.
- A priced page must not be prerendered: export prerender = false from /pricing, even if the root layout prerenders everything else.
SvelteKit's server load receives the visitor's Request and a cookies object, which covers everything a server-side price test needs. Two of its rules trip up a first attempt. setHeaders refuses set-cookie, so the SDK's cookie has to go through cookies.set(). And SvelteKit 3 throws on a redirect to another origin unless you opt in, which is exactly what sending a buyer to Stripe Checkout is.
This guide targets SvelteKit 3 and notes the lines that differ on SvelteKit 2. 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 SvelteKit?
Install the SDK and Stripe's library:
npm install @leverprice/sdk stripeSvelteKit 3 declares environment variables in src/env.ts. Every variable is private unless you mark it public, and $app/env/private can't be imported into code that runs in the browser (environment variables):
import { defineEnvVars } from "@sveltejs/kit/env";
export const variables = defineEnvVars({
LEVERPRICE_SECRET_KEY: {},
STRIPE_SECRET_KEY: {},
});LEVERPRICE_SECRET_KEY=pp_sk_test_…
STRIPE_SECRET_KEY=sk_test_…SvelteKit reads .env during development and builds. On SvelteKit 2, skip src/env.ts and import the same names from $env/dynamic/private. The test key comes from the dashboard when you create a project, and the docs cover every SDK option.
Create the clients in src/lib/server, which SvelteKit treats as server-only:
import { Leverprice } from "@leverprice/sdk";
import { LEVERPRICE_SECRET_KEY } from "$app/env/private";
export const leverprice = new Leverprice({
secretKey: 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);
}import Stripe from "stripe";
import { STRIPE_SECRET_KEY } from "$app/env/private";
export const stripe = new Stripe(STRIPE_SECRET_KEY!);Module scope means one client per server process, holding the signed config in memory between requests. fallbackPrice is what everyone gets when Leverprice is off, slow (no config within 500 ms) or down, and minPrice and maxPrice are hard bounds the SDK checks before any price reaches the page. Amounts are minor units, so 1900 is $19.00.
Why does the cookie go through cookies.set()?
Because SvelteKit won't let setHeaders touch set-cookie. The load docs send you to cookies.set() instead, and setting the same header twice through setHeaders, even from separate load functions, is an error as well.
The SDK hands you finished Set-Cookie strings. This helper replays each one through cookies.set() with the same name, value and attributes. Add it to the same module:
import type { Cookies } from "@sveltejs/kit";
// setHeaders() refuses set-cookie, so replay the SDK's cookies through cookies.set().
export function setQuoteCookies(cookies: Cookies, setCookie: string[]) {
for (const header of setCookie) {
const [pair, ...attributes] = header.split("; ");
const [name, value] = pair.split("=");
const attribute = (key: string) => attributes.find((a) => a.startsWith(`${key}=`))?.slice(key.length + 1);
cookies.set(name, value, {
path: "/",
maxAge: Number(attribute("Max-Age")),
domain: attribute("Domain"),
httpOnly: true,
sameSite: "lax",
secure: attributes.includes("Secure"),
});
}
}The SDK's cookie is HttpOnly, SameSite=Lax and scoped to /, and it's Secure unless you set cookieSecure: false; the helper copies all of that. Its values use only URL-safe characters, so SvelteKit's default encoding leaves them untouched. A cookie set this way also lands on the __data.json responses SvelteKit uses for client-side transitions, so a visitor who clicks through from another page is assigned just like one who loads /pricing directly.
How do you show the price on the page?
Ask for the price in the page's server load, set the cookie, and return only the formatted string:
import { formatPrice, leverprice, setQuoteCookies } from "#lib/server/leverprice.js";
import type { PageServerLoad } from "./$types";
export const prerender = false;
export const load: PageServerLoad = async ({ request, cookies, setHeaders }) => {
const quote = await leverprice.getPrice("pro", { request });
setQuoteCookies(cookies, quote.setCookie);
setHeaders({ "cache-control": "private, no-store" });
return { price: formatPrice(quote) };
};<script lang="ts">
import type { PageProps } from "./$types";
let { data }: PageProps = $props();
</script>
<h1>Pro</h1>
<p>{data.price}</p>
<form method="POST">
<button>Buy Pro</button>
</form>SvelteKit 3 replaced $lib with a #lib alias that needs explicit .js extensions; on SvelteKit 2, import from $lib/server/leverprice. prerender = false matters if your root layout prerenders the site. A prerendered page is built once, and SvelteKit's own rule is that a prerenderable page must look the same to every user (page options). Pages with form actions can't be prerendered anyway.
One more default works against you. The project template sets data-sveltekit-preload-data="hover" on <body>, so hovering a link starts fetching the target page's data, which runs this load (link options). Every hover over a pricing link would count as an exposure, even when nobody clicks. Change it on the links that point at /pricing:
<a href="/pricing" data-sveltekit-preload-data="tap">Pricing</a>With tap, preloading starts on mousedown or touchstart, when the visitor is already clicking, so you keep most of the speed and stop counting hovers.
How do you charge the price in a form action?
Add a default action to the same +page.server.ts. It prices the visitor again, creates the session and redirects:
import { redirect } from "@sveltejs/kit";
import { stripe } from "#lib/server/stripe.js";
import type { Actions } from "./$types";
export const actions: Actions = {
default: async ({ request, cookies, url }) => {
const quote = await leverprice.getPrice("pro", { request }); // never trust a price from the form
setQuoteCookies(cookies, quote.setCookie);
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: `${url.origin}/thanks`,
cancel_url: `${url.origin}/pricing`,
});
redirect(303, session.url!, { external: true });
},
};SvelteKit 3's redirect() throws for an external URL unless you pass external: true or an allowlist of origins (redirect reference). On SvelteKit 2, drop the third argument. The cookie maps the visitor to the same variant, so the amount on Stripe's page equals the one in load, and the action never reads a price from the form.
Leave use:enhance off this form. An enhanced form follows a redirect with goto(), and SvelteKit's own docs say external URLs need window.location instead (form actions). A plain POST lets the browser follow the 303 to Stripe.
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 values through their own custom-price fields: ad-hoc prices on a Polar checkout, 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 the calls. Lemon Squeezy stops processing payments on March 31, 2027 (announcement).
How does verified revenue work?
Stripe reports each purchase to Leverprice with a signed webhook, so your SvelteKit app needs no webhook endpoint for the test. In the dashboard, open Payments and connect Stripe in Test mode. Add the URL it shows as a Stripe webhook endpoint for checkout.session.completed, checkout.session.async_payment_succeeded and charge.refunded, then paste the endpoint's signing secret back.
The signing secret only lets Leverprice confirm events; it can't charge or refund, and an API key never goes there. Refunds reduce the revenue of the price that sold. Stripe verification covers one-time payment sessions like this one.
How do regional prices work in SvelteKit?
Regional prices (SDK 0.4 or later) charge each country its own price, and during a test each visitor keeps one variant at that variant's price for their country. The country comes from a header your adapter's platform sets: x-vercel-ip-country with adapter-vercel, cf-ipcountry with adapter-cloudflare.
export const leverprice = new Leverprice({
secretKey: 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 },
},
},
},
});There's no default header, on purpose: one a visitor could send would let them choose their own price. load and the action both pass request, so they read the country without other changes, and the action already sends quote.currency to Stripe. Bots, unknown countries and currencies you didn't list get the standard price. Regional pricing explains how each country's price is set.
How do you test it locally?
- Run
npm run devand openhttp://localhost:5173/pricingin Chrome or Firefox. The response should set a__ppcookie, and the price should fall inside your range. - Reload a few times and the price holds. A private window is a new visitor and may draw a different price.
- Hover a link to
/pricingwithout clicking. With preloading set totap, the Network tab shows no__data.jsonrequest. - Run
curl -i http://localhost:5173/pricing. Command-line clients count as bots, so the response has the standard price and no cookie. - 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=1 npm run dev: the fallback price, no cookie, no network calls.
The Install page in the dashboard turns to Connected after your server's first request, marked test mode only until a live key is used.
What changes when you deploy?
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. What else changes depends on the adapter:
| Adapter | Keys in production | Sending queued events |
|---|---|---|
adapter-node | The environment node build runs in | The SDK's timer sends them |
adapter-vercel | Project environment variables | waitUntil(leverprice.flush()), with waitUntil from @vercel/functions (reference) |
adapter-cloudflare | Wrangler secrets | waitUntil(leverprice.flush()), with waitUntil from cloudflare:workers |
Call the flush in both load and the action. In SvelteKit 3, the Cloudflare adapter no longer exposes Cloudflare APIs on platform, so env and waitUntil come from cloudflare:workers, and adapter-vercel no longer supports the edge runtime (migration guide).
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
An error says to use cookies.set instead of setHeaders | quote.setCookie was passed to setHeaders | Use setQuoteCookies() |
| The redirect to Stripe throws instead of redirecting | SvelteKit 3 blocks external redirects by default | Add { external: true } to redirect() |
| Exposures far exceed pricing page views | Hover preloading runs load for visitors who never click | Set data-sveltekit-preload-data="tap" on pricing links |
The build fails to prerender /pricing, or every visitor sees the same price | A root layout sets prerender = true, or the site uses adapter-static | Export prerender = false from /pricing and deploy with an adapter that runs a server |
The Buy button fails with a goto error | use:enhance tries to follow the external redirect with goto() | Remove use:enhance from the buy form |
| Everyone gets the fallback price in production | The key never reached the production environment | Set LEVERPRICE_SECRET_KEY where the server runs |
| 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 on SvelteKit 2?
Yes, with small edits: read the keys from $env/dynamic/private, import from $lib instead of #lib, drop the external option from redirect(), and use "off" rather than "false" if you disable preloading outright. The load, the action and the cookie helper stay the same.
Why not append the cookie in hooks.server.ts?
You could append raw headers to the response in handle, but SvelteKit warns that some responses have immutable headers and modifying them throws (hooks). cookies.set() works on page, data and redirect responses alike.
Can I test a subscription price?
Yes. Use mode: "subscription", add recurring: { interval: "month" } to price_data and remove 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 own webhook handler; it shows as unverified, and renewals never count.
Do crawlers see the test price?
No. Crawlers, link previews, headless browsers and monitors get your standard price and no cookie, and they never count as visitors.