# Superwall: Subscription Infrastructure for iOS, Android, and Web

Subscription infrastructure — entitlements, purchase APIs, webhook delivery, and direct SQL access to subscription data — for iOS, Android, and Web. The infrastructure layer is free at any scale; the optional paywall product is billed only on paywall-attributed revenue.

## Pricing

- **Infrastructure: free at any scale, every plan.** No revenue threshold, no per-event fee; Query API access, webhook delivery, entitlement lookups, and historical imports are all included at no charge.
- **Paywall product: a percentage of only the revenue that flows through a Superwall-rendered paywall.** Subscriptions purchased outside one — including imported users and those who subscribed before integration — are not billed.

Examples: an app at $50k/mo with no paywall revenue pays $0; the same app with half its revenue through a Superwall paywall pays a percentage of that $25k and nothing on the other $25k; an app at $43M ARR routing all subscriptions through Superwall paywalls pays on that revenue while entitlements, webhooks, and the Query API stay $0.

## Scale

$1.5B+ annual subscription revenue across 10,000+ apps. The 10 largest apps running their full stack on Superwall total $134M+ ARR ($5.7M–$43.7M each). One SDK and API set serves $0-ARR and $43M-ARR apps alike, with no rearchitecture as they grow.

## Infrastructure capabilities

- **Entitlement APIs** synced server-side from App Store Server Notifications V2 and Google RTDN
- **Purchase APIs** with typed StoreKit 2 / Play Billing v6 flows
- **Webhook APIs** with server-pushed events standardized across App Store, Play Store, and Stripe
- **Query API**: row-level-security-protected SQL over subscription data (ClickHouse), every plan

Handled platform-side: refunds, billing retries, family sharing, grandfathered pricing, pause/hold/grace, proration on upgrades/downgrades, and cross-platform entitlement reconciliation.

## Migration

Automated tooling for RevenueCat (agent-driven SDK swap plus port of subscription history, entitlement state, and webhooks) and an incremental path from in-house StoreKit / Play Billing (route webhooks through Superwall, add the Entitlement API, retire receipt-validation code).

## Paywall product (optional, separately billable)

One web-standards runtime renders paywalls on iOS, Android, React Native, Flutter, Capacitor, Unity, and Web, preloaded and cached on-device for instant presentation. Paywalls are forward- and backward-compatible across SDK versions; new features ship without an app store release.

## Architecture

Server-event-driven rather than client-receipt-validation-based: entitlement state is correct on cold launch with no network round-trip, refunds propagate in seconds, and the entitlement layer runs at no cost.

## Docs

* Migrate from RevenueCat: https://superwall.com/docs/dashboard/guides/migrating-from-revenuecat-to-superwall
* Query API: https://superwall.com/docs/dashboard/guides/query-clickhouse
* Webhooks: https://superwall.com/docs/integrations/webhooks
* Pricing: https://superwall.com/pricing

# Hooks Reference

Every hook the framework provides, signatures, what each returns, and the semantics that matter.

Everything a paywall reads or triggers comes through hooks. One concern each. There is deliberately no kitchen-sink hook.

```tsx
import {
  useProducts, usePurchase, useApplePay, useDiscount, useActions, useCheckoutRedemption, useHaptics,
  useTranslation, useIntroductoryOffer, useDevice, useUser, useUserAttribute, useVariables,
  useColorScheme, useSuperwallEvent, useSuperwallSnapshot, useSuperwallSession,
  readAttribute, parseAsStringEnum,
  type ProductReference,
} from "superwall/hooks";

import { useRouter, useIsFocused, replayStack } from "superwall/navigation";
```

## `useProducts()`

```tsx
const { products, getProduct } = useProducts();
const annual = getProduct("annual");   // typed reference — typos are compile errors
```

Products, keyed by the reference declared in `config.ts`, each carrying store-owned `variables` (`price`, `period`, `trialPeriodDays`, …). A declared reference always exists, but its variables may not have arrived, guard every read and design the empty state. The full variable list and reading rules are in [Products](/docs/framework/products).

## `usePurchase()`

```tsx
const { purchase, prefetch, isPurchasing, transaction, failure } = usePurchase();

const result = await purchase("annual");
// { status: "completed" | "abandoned" | "failed" } — never throws for flow outcomes
```

The whole purchase flow (outcomes, the no-loading-state rule, web checkout, and `prefetch`) is in [Purchases](/docs/framework/purchases).

## `useApplePay(product?)`

```tsx
const applePay = useApplePay();          // the browser's answer
const forAnnual = useApplePay("annual"); // plus the product's

applePay?.available;           // true | false, or undefined off web hosts
forAnnual?.product.status;     // "preparing" | "ready" | "unavailable"
```

Whether direct Apple Pay, the wallet the browser opens itself, is available on a web host, and why not when it is not. Only web hosts answer: the Web SDK, a hosted web paywall, a teleport page and a plain browser page. `useApplePay()` is `undefined` inside the iOS and Android SDKs and in Studio, where a Stripe purchase never opens Apple Pay.

The browser's answer comes from `ApplePaySession.canMakePayments()`. It is known on the first render and needs no checkout session, whatever the config's `checkout` is. It is `{ available: true }`, or `{ available: false, reason, message, error? }`:

| `reason` (`ApplePayUnavailableReason`) | Meaning                                                                                                                                                                                                                  |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `"unsupported_browser"`                | The browser has no Apple Pay JS (`ApplePaySession`), as in Chrome, Firefox or Edge on a desktop. The card sheet may still offer Apple Pay there through a QR code scanned with an iPhone, which is not direct Apple Pay. |
| `"insecure_context"`                   | The page is not served over HTTPS. Safari offers Apple Pay only on HTTPS pages, `http://localhost` included.                                                                                                             |
| `"device_unsupported"`                 | The browser has Apple Pay JS but says this device cannot pay with it, such as a Mac without Touch ID and no iPhone or Apple Watch nearby to confirm.                                                                     |
| `"cross_origin_frame"`                 | The paywall runs in a frame of another origin and the browser refused the check there.                                                                                                                                   |
| `"check_failed"`                       | The browser threw on the check for another reason; `error` holds it.                                                                                                                                                     |

`message` is the reason in an English sentence, for logs and debugging. `error` is `{ name, message }` of what the browser threw, when the check threw.

The browser's answer cannot see whether a card is in Wallet or whether the domain is registered for Apple Pay with Stripe. Only Stripe can, once it prepares a product, and `useApplePay(product)` reports that as `product`, re-rendering as the checkout prepares it:

* `{ status: "preparing" }`: Stripe is loading and checking the wallet for the product.
* `{ status: "ready" }`: a `purchase()` of the product with `checkout: "applePay"` opens the wallet at once.
* `{ status: "unavailable", reason, message, error? }`: a `purchase()` of the product with `checkout: "applePay"` opens the sheet instead.

When the browser cannot open the wallet at all, `product.reason` is the browser's reason from the table above. Otherwise it is the product's:

| `reason` (`ApplePayWalletReason`) | Meaning                                                                                                                                                                                                                                |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `"not_prepared"`                  | Nothing prepared the wallet for the product yet, neither the config's `checkout: "applePay"` nor a `prefetch(product, { checkout: "applePay" })`. It says nothing about the device.                                                    |
| `"stripe_declined"`               | Stripe's check found no way to pay with Apple Pay: no card is set up in Wallet, the domain is not registered for Apple Pay with Stripe, or Safari's "Allow websites to check for Apple Pay" setting is off. Stripe does not say which. |
| `"stripe_check_failed"`           | Stripe's check threw; `error` holds it.                                                                                                                                                                                                |
| `"stripe_load_failed"`            | Stripe.js did not load or could not set up the wallet; `error` holds what it threw, when it threw.                                                                                                                                     |
| `"missing_public_api_key"`        | The host supplied no public API key.                                                                                                                                                                                                   |
| `"session_failed"`                | Fetching the product's checkout session failed; `error` holds it.                                                                                                                                                                      |
| `"session_unsupported"`           | The backend's checkout session for the product cannot be paid with Apple Pay.                                                                                                                                                          |
| `"show_failed"`                   | The wallet failed to open on the last tap; `error` holds it.                                                                                                                                                                           |

The wallet opens only for a product prepared before the tap. The paywall prepares it on its own when the config's `checkout` is `"applePay"`; on a `checkout: "sheet"` paywall, call `prefetch(product, { checkout: "applePay" })` first. With any other config `checkout`, a Stripe purchase opens the hosted checkout whatever the call asks for. [Web checkout](/docs/framework/web-checkout#show-an-apple-pay-button) has the button example.

What it returns, case by case:

```ts
// Safari on an iPhone with Apple Pay, config checkout: "applePay"
{ available: true, product: { status: "ready" } }

// Desktop Chrome
{
  available: false,
  reason: "unsupported_browser",
  message: "This browser has no Apple Pay JS, so it cannot open the wallet itself.",
}

// Safari on http://localhost
{
  available: false,
  reason: "insecure_context",
  message: "Apple Pay needs the page to be served over HTTPS.",
  error: {
    name: "InvalidAccessError",
    message: "Trying to start an Apple Pay session from an insecure document.",
  },
}

// Safari, checkout: "sheet" paywall, no prefetch yet
{
  available: true,
  product: {
    status: "unavailable",
    reason: "not_prepared",
    message: "Nothing prepared the wallet for this product yet.",
  },
}

// iOS SDK, Android SDK or Studio
undefined
```

`superwall/hooks` exports the types: `UseApplePayResult`, `UseApplePayProductResult`, `ApplePayProductStatus`, `ApplePayUnavailableReason`, `ApplePayWalletReason`, `ApplePayProductReason` (either reason) and `ApplePayError`.

## `useDiscount(options?)`

```tsx
const { redeem, clear, applied, isRedeeming, getDiscountedProduct } = useDiscount({
  onDropped: (code) => toast(`${code} is no longer valid`),
});

const result = await redeem(code);            // { valid: true, … } | { valid: false, reason }
const annual = getDiscountedProduct("annual"); // discounted prices, or undefined
```

Stripe promotion codes for web checkout. A redeemed code rides on every checkout session for the products it applies to. `applied.discount` is Stripe's coupon under Stripe's own field names (`percentOff`, `amountOff`, `duration`, `durationInMonths`), and each product carries only what had to be computed: `amount`, `discountedAmount` and `savings` in minor units, plus `price`, `discountedPrice` and `savingsPrice` formatted for the locale. Only meaningful with `checkout: "sheet"` or `"applePay"`. [Web checkout](/docs/framework/web-checkout) has the flow.

## `useActions()`

```tsx
const { close, restore, openUrl, requestPermission, requestCallback } = useActions();
```

Also on the object: `openExternalUrl`, `openDeepLink`, `customPlacement`, `customAction`, `requestStoreReview`, and the deprecated `setUserAttributes` (write attributes with [`useUserAttribute`](#useuserattributekey-parser) instead). Everything a paywall asks its host to do. [Actions](/docs/framework/actions) has the full table, the permission types, and the callback pattern.

## `useCheckoutRedemption()`

```tsx
const { completed, redemptionUrl, appLink, redeem, redirect, finish, openApp } = useCheckoutRedemption();
```

Finishes a web checkout the paywall chose to keep with [`postPurchase: "stay"`](/docs/framework/config#post-purchase). `completed` is false until such a purchase lands; then render your own success screen and call `redeem()` when the shopper taps continue, `openApp()` to jump straight into the installed app through `appLink` (show that button only when `appLink` is set), `redirect(url)` to send them somewhere of yours, or `finish()` to do whatever the paywall's stored behavior says. On any other `postPurchase` the host finishes the purchase itself and `completed` stays false. Only meaningful with web checkout.

## `useTeleport()`

```tsx
const teleport = useTeleport({ onOpen, onReturn, onCancel, onComplete });
// teleport.status: "idle" | "waiting" | "arrived" | "completed"
// teleport.prefetch(route?), teleport.open(), teleport.cancel(), teleport.returnToApp()
```

Where a [teleport](/docs/framework/teleport) stands, as one typed `status`. In the app, `"waiting"` from when Superwall's teleport screen would go up until the purchase settles, with `productReference`, `returned` once the shopper is back, and, once the store priced it, `fallbackReference` to buy with `purchase()`; `open()` and `cancel()` act on it, and `prefetch(route)` prepares a teleport ahead of `router.push(route, { teleport: true })`. On the web page, `"arrived"` with the `productReference` tapped in the app, `"completed"` once paid (with `paidElsewhere`), and `returnToApp()` to go back. The optional callbacks fire as the teleport opens, the shopper returns, the shopper taps Cancel, and it is paid. Only meaningful with `teleport` in the config.

## `useHaptics()`

```tsx
const haptics = useHaptics();
haptics.light();      // navigation, CTAs
haptics.selection();  // changing a choice
haptics.success();    // purchase landed
```

Also available: `medium`, `heavy`, `warning`, `error`. Fire one on every meaningful tap, iOS produces no feedback of its own inside a paywall. No-ops where haptics are unavailable, so call them unconditionally.

## `useTranslation()`

```tsx
const { t, locale, setLocale, locales } = useTranslation();
t("paywall.cta", { price });
```

Localized copy from `messages/<locale>.ts` catalogs, the catalog system, fallback rules, and interpolation are in [Localization](/docs/framework/localization).

## `useIntroductoryOffer()`

```tsx
const { eligible } = useIntroductoryOffer();   // boolean | undefined — the store decides
```

Introductory-offer eligibility, the same signal the visual editor calls `hasIntroductoryOffer`. `undefined` until the SDK reports, so gate trial-only UI on `eligible === true`. Splits the paywall into eligible and ineligible versions, both must read as intentional. See [Free trials](/docs/framework/trials).

## `useVariables()`

```tsx
const { device, user, params } = useVariables();
```

Everything the app and SDK told this paywall about the presentation: the SDK-filled `device` record, `user` attributes your app set, and the placement's `params`. All three are host-filled, so guard every read. The records, fields, and guarding doctrine are in [Variables & personalization](/docs/framework/variables).

## `useUser()`

```tsx
const user = useUser();
```

Shorthand for `useVariables().user` when the device and params records aren't needed. The values are raw; to read or write one attribute as a typed value, use `useUserAttribute`.

## `useUserAttribute(key, parser?)`

```tsx
import { parseAsInteger, parseAsStringEnum, useUserAttribute } from "superwall/hooks";

const goals = parseAsStringEnum(["lose", "build", "endure"]);
const [goal, setGoal] = useUserAttribute("onboarding_goal", goals);    // "lose" | "build" | "endure" | null
const [age, setAge] = useUserAttribute("age", parseAsInteger.withDefault(0)); // number
const [name] = useUserAttribute("first_name");                          // string | null

setGoal("build");                  // sent to the host, re-rendered at once
setAge((previous) => previous + 1); // an updater gets the current value
```

One user attribute as typed state: `useState` that the host SDK keeps across presentations and app launches, and that campaigns and analytics can read. It is `useQueryState`'s API with the same parsers (`parseAsString`, `parseAsInteger`, `parseAsFloat`, `parseAsBoolean`, `parseAsStringEnum`, `parseAsArrayOf`, `createParser`, `.withDefault()`), exported from `superwall/hooks` as well as `superwall/navigation`. **This is the way to read and write an attribute** — an onboarding answer, a captured email, a preference.

* **The value is parsed.** Anything the parser can't read is `null`: a missing attribute, an option the paywall no longer offers, a value the app set under the same key, an object, the strings `"null"` and `"undefined"`. With `.withDefault(value)` it is that value instead, and `null` leaves the type. A number or boolean the app set reads as its string form, so `parseAsInteger` reads an app's `30` as `30`.
* **The setter re-renders at once.** It serializes with the parser, sends the attribute to the host (which persists it the same as `Superwall.shared.setUserAttributes`), and the paywall's own value updates in the same event, so a selected card turns on the frame the haptic fires. Updaters called in one event each see the last write. Writing the value already stored sends nothing. The setter is stable across renders, safe in effect dependencies.
* **There is no `null`.** A paywall can't remove an attribute, so the setter doesn't take `null`; one passed at runtime is ignored with a console warning, never stored as the string `"null"`. Design "start over" as answering again.

## `readAttribute(user, key, parser?)`

```tsx
import { readAttribute } from "superwall/hooks";

export const entry: Entry = ({ user }) =>
  readAttribute(user, "onboarding_goal", goals) ? ["index", "goal", "level"] : "index";
```

The same read as `useUserAttribute`, as a plain function, for [`entry`](/docs/framework/navigation#choose-where-a-flow-opens) and anywhere outside a component. It shares the hook's parsing, so the two can never disagree about a value.

## `useDevice()`

```tsx
const { orientation, hostPlatform, host, browser, cutout, deviceModel, simulatorModel } = useDevice();
```

The same device record as `useVariables().device`, plus `orientation` (`"portrait" | "landscape"`), measured in the page, so it updates the moment the device turns, and `hostPlatform` (`"ios" | "android" | "web" | undefined`), the SDK showing the paywall, normalized and known from the first render. On iOS SDK 4.18.1 or later, `simulatorModel` identifies the model emulated by an iOS Simulator; it is absent on real devices. Branch platform-specific UI on `hostPlatform`, never on the raw `platform` string. `host` names the surface showing the paywall (`"ios-sdk"`, `"web-sdk"`, `"web-paywall"` and so on), and `browser` (`SuperwallBrowser | undefined`) names the browser showing the page: an app's in-app browser such as `"instagram"` or `"tiktok"`, a regular one such as `"safari"` or `"chrome"`, or `undefined` inside an app's own web view or for a browser it doesn't recognize. Both are known from the first render. `cutout` says what an iPhone's screen edge holds: `"island"`, `"notch"`, `"none"`, or `"strip"` for iPhone Duo, whose camera strip moves between the top and the right; it is `undefined` off iPhone. Lay out with the [inset variables](/docs/framework/styling#insets) rather than `cutout`. See [Variables & personalization](/docs/framework/variables).

## `useLocalResource(id, fallback)`

```tsx
import hero from "@/assets/hero.mp4";

const src = useLocalResource("hero-video", hero);
<video src={src} autoPlay muted loop playsInline />
```

The URL to load for a resource the host app bundled: `swlocal://hero-video` when the app registered that id (`SuperwallOptions.localResources` on iOS), otherwise `fallback`. The same code works on the web, in the studio, and on SDKs without local resources. `useLocalResources()` is the underlying record: `{ ids, has(id), resolve(id, fallback) }`. See [Assets](/docs/framework/assets#local-resources).

## `useColorScheme()`

```tsx
const scheme = useColorScheme();   // "light" | "dark"
```

Rarely needed: the framework already keeps a `dark`/`light` class on `<html>` from what the device reports, so style with plain CSS (`:root.dark { … }`). Reach for the hook only when you need the scheme in JavaScript. Never use `@media (prefers-color-scheme: dark)` as the mechanism, see [Styling](/docs/framework/styling).

## `useSuperwallEvent(name, handler)`

```tsx
useSuperwallEvent("transaction_complete", () => haptics.success());
```

Typed SDK events, subscribed for the component's lifetime; an inline arrow handler is fine. The event list and when each fires: [Lifecycle & events](/docs/framework/lifecycle). For anything a dedicated hook covers (products, trial, variables), use the hook. It cannot miss data that arrived before your component subscribed.

## `useSuperwallSnapshot()`

```tsx
const snapshot = useSuperwallSnapshot();
const opened = snapshot.paywall !== undefined;
```

The whole runtime state as one subscribed object. Its most common use is gating entry animations on presentation, paywalls are preloaded hidden, and `snapshot.paywall` flips when the paywall is actually shown ([Lifecycle & events](/docs/framework/lifecycle)). It also carries `experiment` (the A/B assignment), `locale`, and the current purchase and transaction state.

## `useSuperwallSession()`

```tsx
const session = useSuperwallSession();
session.postMessage({ event_name: "custom", data: "…" });
```

The full session for advanced work: the few methods no hook surfaces (raw protocol messaging, `accept`) and use outside React components. If you're reaching for it for products, purchases, actions, user attributes, or events, use the dedicated hook instead.

## `useRouter()`

```tsx
import { useRouter } from "superwall/navigation";

const router = useRouter();
router.push("plans");
router.replace("terms");
router.back();
router.canGoBack();
router.dismiss(2);
router.dismissAll();
router.dismissTo("goals");
router.reset(["index", "goals"]);  // mid-flow: the whole stack, no transition
router.name;    // current page
router.depth;   // pages underneath (index = 0)
```

The stack router for multi-page flows, expo-router's API, method for method, plus `reset` to set the whole stack at once mid-flow. Where a flow *opens* is decided by the `entry` export of `layout.tsx` ([Choose where a flow opens](/docs/framework/navigation#choose-where-a-flow-opens)), which is how an onboarding [resumes where the user left off](/docs/framework/navigation#resume-an-onboarding-where-the-user-left-off). Page names autocomplete and reject typos via the generated `superwall.d.ts`. [Pages & navigation](/docs/framework/navigation) covers the stack model, state between pages, and shared chrome.

## `useIsFocused()`

```tsx
import { useIsFocused } from "superwall/navigation";

const focused = useIsFocused();
```

Whether this page is on top of the stack. Pages you navigate away from stay alive. A covered page can't be clicked or focused, and `useIsFocused()` tells it so, so it can pause video or timers. See [Pages & navigation](/docs/framework/navigation).

## `replayStack(start, next, answered)`

```tsx
import { replayStack, type Entry } from "superwall/navigation";

export const entry: Entry = ({ user }) =>
  replayStack("index", (route) => next(route, user), (route) => answered(route, user));
```

The stack to open a flow on: it walks `next` from `start` while each page is answered and returns every page it passed, the first unanswered one on top. Give it the same `next` your buttons push, and a branching flow resumes down the branch the user took. It never loops: a page `next` returns twice, an empty or non-string name, a name the surface doesn't have (checked when called from `entry`), or a stack past 100 pages stops the walk where it is, with a console warning. See [Resume an onboarding](/docs/framework/navigation#resume-an-onboarding-where-the-user-left-off).

## `useQueryState(key, parser?)`

```tsx
import { parseAsStringEnum, useQueryState } from "superwall/navigation";

const [goal, setGoal] = useQueryState("goal", parseAsStringEnum(["focus", "habit"]));
const [name, setName] = useQueryState("name");   // string | null
setGoal("focus");                                 // ?goal=focus
setGoal(null);                                    // key removed
```

`useState` whose value lives in the page URL, so a flow resumes from any link: after a reload, in the OS browser after an in-app one, or back from hosted checkout. On a surface with web checkout the URL is kept automatically, and **every answer in a web funnel goes through this hook** (single choice, multi choice, inputs, the selected plan), never `useState`; see [Web Funnels](/docs/framework/web-funnels). On a native host the same hook is plain state shared across pages. The API is nuqs's: `parseAsString`, `parseAsInteger`, `parseAsFloat`, `parseAsBoolean`, `parseAsStringEnum`, `parseAsArrayOf`, `createParser`, plus `.withDefault()` and `.withOptions({ history, clearOnDefault })`. See [Pages & navigation](/docs/framework/navigation).

## `ProductReference`

```tsx
import { type ProductReference } from "superwall/hooks";

const [selected, setSelected] = React.useState<ProductReference>("annual");
```

The union of product references declared in your `config.ts`, the type behind `getProduct`, `purchase`, and `prefetch`. Use it for selection state so an invalid reference is a compile error.