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.
import {
useProducts, usePurchase, useApplePay, useDiscount, useActions, useCheckoutRedemption, useHaptics,
useTranslation, useIntroductoryOffer, useDevice, useUser, useUserAttribute, useVariables,
useColorScheme, useSuperwallEvent, useSuperwallSnapshot, useSuperwallSession,
readAttribute, parseAsStringEnum, checkApplePay,
type ProductReference,
} from "superwall/hooks";
import { useRouter, useIsFocused, replayStack } from "superwall/navigation";useProducts()
const { products, getProduct } = useProducts();
const annual = getProduct("annual"); // typed reference — typos are compile errorsProducts, 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.
usePurchase()
const { purchase, prefetch, isPurchasing, transaction, failure } = usePurchase({
onStart, onSubmit, onComplete, onAbandon, onFailure, // each optional
});
const result = await purchase("annual", { onFailure }); // callbacks for this purchase only
// { status: "completed" | "abandoned" | "failed", product, failure? } — never throws for flow outcomesThe whole purchase flow (outcomes, the no-loading-state rule, web checkout, and prefetch) is in Purchases.
failure (PurchaseFailure | undefined) is the last purchase that failed, cleared when the next one starts. A failed Stripe purchase is a WebCheckoutFailure: a CheckoutFailure (reason, store: "stripe", and Stripe's raw code, declineCode and message when it gave them) with status: "failed" and the product. A failed store purchase is a SuperwallPurchaseFailure with reason: "unknown" or "superseded" and no store, so check "store" in failure before reading the Stripe fields. On the result of purchase(), a failed Stripe purchase carries the same CheckoutFailure as result.failure.
The callbacks, passed to usePurchase(), fire for every purchase on the paywall from any component; passed to purchase(), only for that purchase while it is in flight:
| Callback | Fires when |
|---|---|
onStart(product) | The purchase started. |
onSubmit(product) | The shopper submitted payment in the sheet or authorized it in Apple Pay. Web checkout only. |
onComplete(product) | The purchase was paid. |
onAbandon(product) | The shopper left the checkout or the store's sheet without paying. |
onFailure(failure) | A purchase failed; failure is a PurchaseFailure. |
They fire for App Store, Play Store and Stripe products, not for custom store products. Every reason and what each platform reports is in Payment failure reasons.
superwall/hooks exports the types CheckoutFailure, CheckoutFailureReason, WebCheckoutFailure, WebCheckoutResult, PurchaseFailure, PurchaseCallbacks, UsePurchaseOptions and PurchaseOptions.
useApplePay(product?)
const applePay = useApplePay(); // this device's answer
const forAnnual = useApplePay("annual"); // plus the product's
applePay.available; // true | false
forAnnual.product.status; // "preparing" | "ready" | "unavailable"Whether Apple Pay is available on this device: set up with a card to pay with. It answers the same way on every host: inside the iOS SDK, on the Web SDK, on a hosted web paywall, on a teleport page and in a plain browser. useApplePay() always returns a result.
The answer comes from Apple's ApplePaySession.canMakePaymentsWithActiveCard(), asked for the page's own Stripe merchant, merchant.<hostname>.stripe. It follows the cards in Wallet, not the domain's registration with Stripe. Any usable card counts, Apple Cash with no balance too, so available means Apple Pay is set up, not that a payment will go through.
It is { available: true }, or { available: false, reason, message, error? }:
reason (ApplePayUnavailableReason) | Meaning |
|---|---|
"checking" | Apple has not answered yet. It answers in a moment, at most 1.5 seconds later. Treat it as not available. |
"no_active_card" | Apple answered that Apple Pay has no card to pay with here: Wallet holds none, or the device cannot use Apple Pay. |
"unsupported_browser" | The page has no ApplePaySession.canMakePaymentsWithActiveCard, as inside the Android SDK, in Chrome, Firefox or Edge on a desktop, and in Studio in those browsers. 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. |
"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. |
"timed_out" | Apple did not answer within 1.5 seconds. Its late answer still replaces this one, and the next check asks Apple again. |
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.
When the answer is known
- Apple is asked once per page, and every
useApplePay()on the page shares the answer and re-renders when it arrives. - An answer that needs no question, such as no Apple Pay at all on Android or a page that is not HTTPS, is there on the first render. So is an answer the page already got.
- Otherwise
availableisfalsewith reason"checking"until Apple answers, usually right after the first render. - A paywall with
teleportin its config asks Apple as soon as it opens, so the answer is usually there before the first tap. See Teleport. - Apple's answer is kept for the page. A check that threw, or that is still
"timed_out", asks Apple again on the nextuseApplePay()mount orcheckApplePay()call.
checkApplePay()
The same answer as a promise, for code outside React:
import { checkApplePay } from "superwall/hooks";
const { available } = await checkApplePay();It shares the page's answer with useApplePay(), never rejects and never resolves "checking": it waits for Apple, or resolves "timed_out" after 1.5 seconds.
With a product
useApplePay(product) adds product: whether the wallet is ready to open for that product. Only Stripe's check, made when it prepares the product, also sees whether the domain is registered for Apple Pay with Stripe. It re-renders as the checkout prepares the product:
{ status: "preparing" }: Apple has not answered yet, or Stripe is loading and checking the wallet for the product.{ status: "ready" }: apurchase()of the product withcheckout: "applePay"opens the wallet at once.{ status: "unavailable", reason, message, error? }: apurchase()of the product withcheckout: "applePay"opens the sheet instead.
Inside the iOS and Android SDKs and in Studio, where a purchase never opens the Apple Pay wallet, product.reason is "unsupported_host". On a web host where Apple Pay is not available, it is the device'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 has the button example.
What it returns, case by case
// iOS SDK or Safari, with a card in Wallet
{ available: true }
// iOS SDK or Safari, Wallet empty
{
available: false,
reason: "no_active_card",
message: "Apple Pay has no card to pay with here: Wallet holds none.",
}
// iOS SDK or Safari, before Apple answers
{
available: false,
reason: "checking",
message: "Apple has not answered the Apple Pay check yet.",
}
// Android SDK, or desktop Chrome
{
available: false,
reason: "unsupported_browser",
message: "This page has no ApplePaySession.canMakePaymentsWithActiveCard, so it cannot check for a card.",
}
// 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.",
},
}
// useApplePay("annual") in Safari with a card, config checkout: "applePay"
{ available: true, product: { status: "ready" } }
// useApplePay("annual") in Safari with a card, checkout: "sheet" paywall, no prefetch yet
{
available: true,
product: {
status: "unavailable",
reason: "not_prepared",
message: "Nothing prepared the wallet for this product yet.",
},
}
// useApplePay("annual") in the iOS SDK with a card
{
available: true,
product: {
status: "unavailable",
reason: "unsupported_host",
message: "Inside the iOS or Android SDK and in Studio a purchase never opens the Apple Pay wallet.",
},
}superwall/hooks exports checkApplePay and the types: UseApplePayResult, UseApplePayProductResult, ApplePayProductStatus, ApplePayUnavailableReason, ApplePayWalletReason, ApplePayProductReason (any reason a product can report) and ApplePayError.
device.isApplePayAvailable is deprecated: the native SDK always reports true, so it says nothing about Apple Pay. Use useApplePay().available.
useDiscount(options?)
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 undefinedStripe 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 has the flow.
useActions()
const { close, restore, openUrl, requestPermission, requestCallback } = useActions();Also on the object: openExternalUrl, openDeepLink, customPlacement, customAction, requestStoreReview, and the deprecated setUserAttributes (write attributes with useUserAttribute instead). Everything a paywall asks its host to do. On a teleport web page, close() returns to the app and resolves "opened", "cancelled" or "no_app"; everywhere else it returns undefined. Actions has the full table, the permission types, and the callback pattern.
useCheckoutRedemption()
const { completed, redemptionUrl, appLink, redeem, redirect, finish, openApp } = useCheckoutRedemption();Finishes a web checkout the paywall chose to keep with postPurchase: "stay". 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()
const teleport = useTeleport({ onOpen, onReturn, onCancel, onComplete, onReturnData });
// teleport.status: "idle" | "waiting" | "arrived" | "completed"
// teleport.prefetch(route?), teleport.open(), teleport.cancel()
// teleport.returnToApp({ data }?): Promise<"opened" | "cancelled" | "no_app">, teleport.returningWhere a 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: it resolves "opened", "cancelled" (the shopper tapped Cancel on iOS's "Open in…?" prompt) or "no_app", and returning is true while it is under way, see Returning to the app. After a failed payment the page leaves the app its failure, and returnToApp({ data }) passes up to 16 KB of plain JSON with it; once the shopper is back, "waiting" carries failure and data, see Return to the app after a failed payment. The optional callbacks fire as the teleport opens, the shopper returns, the shopper taps Cancel, it is paid, and the app reads the page's data (onReturnData). Types: TeleportReturnOptions, TeleportData, TeleportDataValue. Only meaningful with teleport in the config.
useHaptics()
const haptics = useHaptics();
haptics.light(); // navigation, CTAs
haptics.selection(); // changing a choice
haptics.success(); // purchase landedAlso 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()
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.
useIntroductoryOffer()
const { eligible } = useIntroductoryOffer(); // boolean | undefined — the store decidesIntroductory-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.
useVariables()
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.
useUser()
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?)
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 valueOne 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, andnullleaves the type. A number or boolean the app set reads as its string form, soparseAsIntegerreads an app's30as30. - 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 takenull; 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?)
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 and anywhere outside a component. It shares the hook's parsing, so the two can never disagree about a value.
useDevice()
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 rather than cutout. See Variables & personalization.
useLocalResource(id, fallback)
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.
useColorScheme()
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.
useSuperwallEvent(name, handler)
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. For anything a dedicated hook covers (products, trial, variables), use the hook. It cannot miss data that arrived before your component subscribed.
useSuperwallSnapshot()
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). It also carries experiment (the A/B assignment), locale, and the current purchase and transaction state.
useSuperwallSession()
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()
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), which is how an onboarding resumes where the user left off. Page names autocomplete and reject typos via the generated superwall.d.ts. Pages & navigation covers the stack model, state between pages, and shared chrome.
useIsFocused()
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.
replayStack(start, next, answered)
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.
useQueryState(key, parser?)
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 removeduseState 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. 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.
ProductReference
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.
How is this guide?
Migrating native screens
Turn a SwiftUI, UIKit, Jetpack Compose, Android Views, React Native or Flutter screen into a Superwall surface the app can change without a release: what the CLI reads from the source, what an agent rebuilds, how you review it against a simulator screenshot, and how the app is wired afterwards.
CLI Reference
Every superwall command (create, dev, push, promote, publish) with flags, auth, and the checks that run before anything ships.