Web
Read entitlements, record experiment exposures and start Stripe checkouts from a browser.
Before you install: allow your origin
A Rovenue API key is not usable from a browser until you list the origins your
app is served from. This is the first thing to do: every request from an origin
that is not on the key's list is refused with 403
ORIGIN_NOT_ALLOWED before it
does anything. The SDK throws it as a RovenueApiError with that code, so the
cause is readable in your app rather than a bare CORS failure.
In the dashboard, open SDK & API → API keys, and add each origin to the key
you will ship — for example https://app.example.com and, for local work,
http://localhost:3000. Origins are matched exactly: scheme, host and port.
There are no wildcards, because a https://*.example.com entry would turn a
subdomain takeover into a working API key.
Install
npm install @rovenue/web-sdkConfigure
import { configure, createStorage } from "@rovenue/web-sdk";
export const rovenue = configure({
apiKey: "rov_pk_test_...", // your PUBLIC key — visible in the browser by design
apiUrl: "https://api.rovenue.io",
storage: createStorage(), // localStorage where available, memory where not
});Create the client once and share it. Constructing it per render rebuilds the identity, the entitlement cache and the event queue each time.
Choosing an app user id
The SDK generates its own identifier and uses it on every request. If you call
identify() with an id of your own, the server only binds it when you pass an
identity token your backend minted for that exact id, so a stranger holding your
public key cannot claim it.
Opaque ids are still advised: some read-only lookups (for example placements) resolve by app user id without a token, so a guessable id leaks what they return. Never use an email address, a sequential number, or anything else a stranger could construct. Use an opaque id your backend maps to the user. The SDK warns in the console when it sees an email-shaped id.
Identifying a signed-in user
identify() is a server call and needs an identity token your backend
mints for that user with the secret key (POST /v1/identity-tokens, valid for
15 minutes). Your page asks your own backend for it after sign-in, then passes it
along. App user ids are not secrets, so without the token anyone could bind a
browser to someone else's id.
const { identityToken } = await fetch("/api/rovenue/identity-token").then((r) => r.json());
await rovenue.identify("u_9f3a1c7e", { identityToken }); // opaque id
// rovenue.identify("ada@example.com", …) // warns — guessableThe local identity changes only after the server accepts the token. If it
refuses, identify() rejects with a RovenueApiError and the previous identity
stays as it was: 400 when the token is missing, 401 with code === IDENTITY_TOKEN_INVALID (exported from the SDK) when it is expired, tampered or
minted for another user, project or environment. Fetch a fresh token and
identify again.
import { IDENTITY_TOKEN_INVALID, RovenueApiError } from "@rovenue/web-sdk";
try {
await rovenue.identify(userId, { identityToken });
} catch (err) {
if (err instanceof RovenueApiError && err.code === IDENTITY_TOKEN_INVALID) {
// mint a new token and retry
}
}Merging two subscribers by transfer is still a server-side operation with your secret key.
Entitlements
const entitlements = await rovenue.getEntitlements();The SDK caches the last answer, so a returning subscriber does not see a flash of the paywall they already paid to remove:
const cached = rovenue.getCachedEntitlements(); // synchronous, no networknull and {} mean different things and the SDK keeps them apart: {} is a
real answer meaning this person has no entitlements, null means we have not
found out. When the network is unreachable or the API returns a 5xx,
getEntitlements() answers from cache. When it returns a 4xx — a revoked key, a
rejected origin — it throws instead, so a misconfiguration surfaces rather than
hiding behind stale data.
Change events
addChangeListener tells you when what you read is out of date. It returns the
function that unsubscribes:
const stop = rovenue.addChangeListener((event) => {
if (event === "IDENTITY_CHANGED") {
// Whose data this is changed. Drop what you show and read again.
void rovenue.getEntitlements().then(render);
} else if (event === "ENTITLEMENTS_CHANGED") {
render(rovenue.getCachedEntitlements());
}
});| Event | Fired when |
|---|---|
IDENTITY_CHANGED | logOut() rotated the identity, or identify() merged this browser into an existing subscriber or replaced the app user bound earlier in this page. The first identify() of a page load that keeps the browser's own subscriber does not fire it: nothing it owns changed. |
ENTITLEMENTS_CHANGED | getEntitlements() got an answer for the current identity that differs from the last one. getCachedEntitlements() already returns it. |
The names and meanings are the React Native SDK's
addChangeListener. A listener runs
synchronously inside the call that made the change, and one that throws is
ignored. On ENTITLEMENTS_CHANGED read getCachedEntitlements() rather than
calling getEntitlements(), which can fire the event again. An answer that was
still on its way for the previous identity is returned to whoever asked for it
but is never cached and never announced.
The React hooks below subscribe for you.
React
import { RovenueProvider, useEntitlements } from "@rovenue/web-sdk/react";
function App() {
return (
<RovenueProvider client={rovenue}>
<Content />
</RovenueProvider>
);
}
function Content() {
const { entitlements, isLoading, error } = useEntitlements();
if (entitlements?.pro) return <Pro />;
return <Upsell loading={isLoading} error={error} />;
}Pass the client you created with configure(). Create it once, outside your
components.
How hooks stay current
useEntitlements() returns { entitlements, isLoading, error, refresh } and
usePlacement(identifier) returns { placement, isLoading, error, refresh }.
You do not refetch after identify() or logOut(); the hooks do:
- First paint.
entitlementsstarts as the cached value (nullwhen there is none) withisLoading: true, and the network answer replaces it. identify()/logOut(). When the identity changes, the previous identity's value is dropped at once and fetched again. Until the answer arrives the hook returns what is cached for the new identity —nullafter alogOut()or a merge — withisLoading: true. A paying subscriber who signs in sees their access without a reload, and nobody sees the previous person's. Treatnullas "not known yet", not as "has nothing".- Late answers. An answer that was in flight for the previous identity, or
for an earlier
refresh(), is ignored. A stalled read does not delay the next identity's: in a browser the SDK'sGETrequests skip the HTTP cache (cache: "no-store"), which Chromium would otherwise queue them behind. usePlacementidentifier. Each identifier has its own value. Changing it shows that placement's value (nullwithisLoading: truethe first time), never the previous identifier's, whichever answer arrives last.- Errors. A failed request sets
errorand keeps the value already shown for this identity (and identifier). A transient failure does not blank a paying subscriber's access. refresh(). Fetches again and resolves when that request settles; it does not reject. Call it when you know something changed on the server, such as after your own backend granted access. A buyer coming back from Stripe Checkout lands on a fresh page load, which fetches by itself.
Every component using the same hook shares one request and one value, so a
refresh() in one updates all of them, and so does a newer answer to
rovenue.getEntitlements() called anywhere in your app. Under <StrictMode>
the double mount makes one request. On the server the hooks render
isLoading: true with null and do not fetch.
Checkout
The web SDK has no purchase() — there is no native store sheet in a
browser. checkout() is where a web purchase flow ends: it starts a Stripe
Checkout session and hands you the URL to redirect to. This is the one
place the web quickstart genuinely diverges from the native SDKs' flow
(getOfferings() → purchase()).
const { offerings } = await rovenue.getOfferings();
const offering = offerings.find((o) => o.isDefault) ?? offerings[0];
const session = await rovenue.checkout({
offeringIdentifier: offering.identifier,
packageIdentifier: offering.packages[0].packageIdentifier,
successUrl: "https://app.example.com/welcome",
cancelUrl: "https://app.example.com/pricing",
});
window.location.assign(session.url);packageIdentifier is the package slot (packages[i].packageIdentifier), not
the product identifier.
Each package also carries virtualCurrencyGrants ({ code, amount, grantOn, intervalDays, trialAmount, expiresAtPeriodEnd }[], [] when none): the credits
its product pays, read from the product's grant rule, so a pricing page can say
"500 GOLD" without hard-coding it. trialAmount is paid once when a trial
starts (0 = none); expiresAtPeriodEnd means the rule's credits expire at the
end of the period they were granted for (the billing period, the N-day period of
a periodic rule, or the trial).
Each package also carries price: the Stripe price checkout() charges,
read on the server from the Price on your connected Stripe account (cached
for five minutes), so a pricing page can show the amount without
hard-coding it.
type WebPackagePrice = {
amount: number; // minor units: 999 = $9.99, 1200 = ¥1200
currency: string; // lowercase ISO-4217, e.g. "usd"
interval: "day" | "week" | "month" | "year" | null; // null = one-time
intervalCount: number | null; // 3 with "month" = every three months
trialDays: number | null; // the trial checkout() would start for this subscriber now, else null
};
function label(p: WebPackagePrice): string {
const fmt = new Intl.NumberFormat(undefined, {
style: "currency",
currency: p.currency.toUpperCase(),
});
const digits = fmt.resolvedOptions().maximumFractionDigits ?? 2;
const money = fmt.format(p.amount / 10 ** digits);
if (!p.interval) return money;
const every = p.intervalCount && p.intervalCount > 1 ? `${p.intervalCount} ${p.interval}s` : p.interval;
return `${money} / ${every}`;
}price is null when the product has no Stripe price id, the price has no
flat amount (tiered or metered prices), Stripe could not be read in time, or
the server predates this field. Never fall back to a made-up amount; hide or
disable the package instead. Only the price's default currency is served.
trialDays is the Price's recurring.trial_period_days, and it is shown
only when checkout() would start that trial for this caller right now.
Stripe Checkout ignores a Price-level trial, so the server passes the trial
to Checkout itself (subscription_data.trial_period_days).
The trial is given once per identified app user in a project, separately in sandbox and live:
- Identified means the subscriber has an app user id bound on the
server, through
POST /v1/identify, the secret-key transfer endpoint or an import. The web SDK's ownrovenueIdis a random id kept in browser storage, andlogOut(), a private window or another browser make a new one. So an anonymous buyer never gets a trial, and seestrialDays: null. Bind your signed-in user before you show prices and callcheckout(). - Once means the user has never held a subscription product of the project, on any store and in any status. That covers an earlier trial, a paid, lapsed or refunded subscription, or an imported one. A funnel package click without a card does not count.
- One trial per user, whatever the timing. If several trial checkouts are
opened while the user is still eligible, only the subscription that started
first keeps its trial (same second: the smaller subscription id). The
server ends the trial on the others (
trial_end: "now"), which bills them straight away. This holds in whichever order Stripe's events arrive. Only trials thatcheckout()started are ever ended: the session marks its subscription withrovenue_checkout_trialmetadata. A trial you set on a subscription yourself (a Dashboardtrial_end, a free month) is left alone.
How strong this is depends on your sign-in. POST /v1/identify needs an
identity token your backend minted, so a browser can only bind app user ids
your backend vouches for. A fresh rovenueId identified under a fresh account
is still a new user, and gets the trial. Abuse resistance is therefore only as
strong as your own sign-up: if your backend vouches for whoever signs in, a
trial costs one account sign-up. For a stronger guarantee, bind the user from
your backend instead (the secret-key transfer endpoint, or an import), and
only call checkout() for users bound that way.
Limits:
- A person can get a trial again under a different app user id, and also when their purchases are transferred to another user. Neither cards nor emails are compared.
- The answer can go stale: the user may subscribe in another tab, and a change to the Price's trial can take up to five minutes to show.
- If the server cannot check eligibility, offerings show no trial, while checkout fails with an error instead.
- Trials sold through web funnels follow their own rule (once per normalized email and card fingerprint, see Funnels → Web → Checkout) and are not counted here.
Show a trial only when trialDays is set.
successUrl and cancelUrl must be on one of the API key's allowed
origins, an exact match of scheme, host and port. That includes
http://localhost:<port> while developing, if it is listed. Otherwise they
must be on a verified custom domain over https.
You name a package, never a price. The amount is resolved on the server from
the offering that package belongs to, so a tampered page cannot change what is
charged. Pass an idempotencyKey if a double-submit is possible. It is sent as
the Idempotency-Key header, and the server hashes it together with your
project and the subscriber before using the digest as Stripe's idempotency key,
so the same key from two different buyers never returns the same session.
Repeating the call with the same key for the same buyer returns the session
already created. Without a key, the server derives one from the buyer, the
package, the price and a 5-minute window, so rapid re-posts still converge on
one session.
A returning buyer keeps one Stripe customer: when the subscriber already has one on the connected account (from an earlier web checkout, a funnel purchase or an imported Stripe subscription), the Checkout Session is opened for that customer, so the billing portal shows all of their subscriptions in one place.
Billing portal
billingPortal() opens Stripe's customer portal for the current subscriber
(cancel or change the plan, update the card, download invoices) and hands
you the URL to redirect to.
import { RovenueApiError, STRIPE_CUSTOMER_NOT_FOUND } from "@rovenue/web-sdk";
try {
const { url } = await rovenue.billingPortal({
returnUrl: "https://app.example.com/account",
});
window.location.assign(url);
} catch (err) {
if (err instanceof RovenueApiError && err.code === STRIPE_CUSTOMER_NOT_FOUND) {
// No Stripe billing for this subscriber (an Apple/Google-only buyer):
// hide "Manage billing" rather than showing an error.
} else {
throw err;
}
}Signature: billingPortal(input: { returnUrl: string }): Promise<{ url: string }>.
The URL is short-lived; redirect right away and do not store it.
You never name the customer. The server finds the Stripe customer of the subscriber this browser is identified as: the one behind its web checkouts, its funnel purchases, or its Stripe subscriptions imported from another platform, on the project's currently connected Stripe account. A subscriber merged into another one through a transfer is reached through the survivor.
returnUrl follows the checkout rule: one of the key's allowed origins or a
verified custom domain over https. Errors arrive as RovenueApiError:
| Status | code | Meaning |
|---|---|---|
404 | STRIPE_CUSTOMER_NOT_FOUND | No Stripe customer for this subscriber on the connected account. |
409 | STRIPE_PORTAL_NOT_CONFIGURED | The connected Stripe account never saved its customer portal settings in this mode (see below). Exported as STRIPE_PORTAL_NOT_CONFIGURED. |
400 | RETURN_URL_NOT_ALLOWED | returnUrl is not an allowed origin or verified domain. |
503 | STRIPE_NOT_CONNECTED | The project has no Stripe connection. Checked before the customer, so a project without Stripe answers this, not 404; hide "Manage billing" for it too. |
The portal opens with the connected Stripe account's default customer
portal configuration, so what customers can do there (cancel, switch plans,
update payment methods) is set in that account's Stripe Dashboard under
Settings → Billing → Customer portal. Save it once in each mode you use;
until then billingPortal() rejects with 409 STRIPE_PORTAL_NOT_CONFIGURED.
Events
rovenue.track({ eventType: "pricing_viewed" });Queued and delivered at least once: an event is dropped only after the server acknowledges it, unsent events survive a page reload, and the queue flushes when the tab is hidden or closing. Each event carries a stable id so a replay is deduplicated rather than double-counted.
logOut() sends the queued events under the identity that is leaving and waits
up to 3 seconds for them (LOGOUT_FLUSH_TIMEOUT_MS). Events not delivered by
then are dropped: they are never sent under the next identity.
Under React the provider starts and stops the queue for you. Elsewhere, call
rovenue.startEventQueue() once after configuring.
Server-side rendering
The SDK is safe to import and construct on a server — Next.js, Remix and similar
frameworks run this code where there is no window and no localStorage.
Nothing touches the DOM at import time, and storage falls back to memory when it
is unavailable or blocked.
Network calls still belong on the client. Construct on the server if it suits your app's shape; fetch when you have a viewer.
Supported browsers
Any browser with fetch, localStorage and WebCrypto. WebCrypto is only exposed
on secure origins, so experiment assignment needs https (or
http://localhost); the SDK says so explicitly rather than silently bucketing
everyone into one variant.
Funnels
Web funnels are hosted at a URL and embedded — the web SDK's surface is
client, storage, cache and events (packages/sdk-web/src/index.ts:7-11), so it draws no funnel. Embed the project id and slug: Hosting.
const frame = document.createElement("iframe");
frame.src = "https://funnels.example.com/f/prj_demo1/summer-quiz";
document.body.appendChild(frame);What's next
- Entitlements — read and gate on active subscriptions.
- Placements — how a placement resolves to a funnel or an A/B experiment variant.
- SDK API Reference — the generated TypeDoc reference for every exported type and method, at
/api/sdk-web/. Reference: Methods and Reference: Types cover the React Native/Swift/Kotlin SDKs only — the web SDK's surface differs too much (nopurchase(), no StoreKit/Play Billing bridge) to share those tables, so/api/sdk-web/is the accurate reference here.