React.js SDK
This guide will get you all set up with our React SDK, ready to integrate pricing, payments, authentication and more into your storefront.
The Moonbase React SDK comes with hooks for products and pricing, cart and authentication, customer inventory and more. It is made using TypeScript, so you have typed models everywhere, but you can just as easily use it in your JavaScript projects. It works with React 18 and 19.
Add your site's development, test and production addresses under Account settings > Storefront > "Domain configuration", so Moonbase can answer requests from them. The examples below use version 1.2.0 or later of @moonbase.sh/react.
To see the SDK in use end to end, our open-source Corino reference site is a complete Next.js 16 storefront wired to the public Corino demo Moonbase account. Build a custom website with React walks through its code: products and prices, the cart, sign-in and sign-up, downloads and trials, license activation, and the account area.
Next.js 16 reference storefront wired end to end to Moonbase: server-rendered prices, checkout overlay, account area, downloads and license activation.
Getting started
Start by adding the package to your project:
npm install @moonbase.sh/react
Then make a storefront once, outside your components, and pass it to StorefrontProvider:
src/main.tsx
import { createStorefront, StorefrontProvider } from '@moonbase.sh/react'
import { createRoot } from 'react-dom/client'
import App from './App'
const storefront = createStorefront('https://<account-id>.moonbase.sh')
createRoot(document.getElementById('root')!).render(
<StorefrontProvider storefront={storefront}>
<App />
</StorefrontProvider>,
)
Make the storefront before creating your router. A customer coming back from the hosted checkout brings mb_* parameters in the address, which the storefront reads and removes. A router made first can put them back. For Next.js, where the router already exists and the catalog comes from the server, use getStorefront as below; the provider also removes those parameters after hydration.
Next.js and server rendering
The SDK supports server rendering. On the server, the storefront has no visitor: no cart, nobody signed in, and no browser requests or storage. To render real product names and prices, fetch a public catalog on the server with fetchCatalog, then pass it as initialCatalog:
src/app/layout.tsx
import { fetchCatalog } from '@moonbase.sh/react'
import type { ReactNode } from 'react'
import { Providers } from '@/components/Providers'
export default async function RootLayout({ children }: { children: ReactNode }) {
const catalog = await fetchCatalog('https://<account-id>.moonbase.sh', {
fetch: { next: { revalidate: 3600 } },
})
return (
<html lang="en">
<body><Providers initialCatalog={catalog}>{children}</Providers></body>
</html>
)
}
The fetch options go to the catalog request, so Next can cache it on your schedule. Corino puts this call in src/lib/catalog.ts and catches failures there, letting its pages render fallback prices when Moonbase can't be reached.
The provider is a client component:
src/components/Providers.tsx
'use client'
import { getStorefront, type Storefront, StorefrontProvider } from '@moonbase.sh/react'
import type { ReactNode } from 'react'
export function Providers({ initialCatalog, children }: {
initialCatalog: Storefront | undefined
children: ReactNode
}) {
const storefront = getStorefront('https://<account-id>.moonbase.sh', {
initialCatalog,
persistUtm: true,
})
return <StorefrontProvider storefront={storefront}>{children}</StorefrontProvider>
}
getStorefront gives back the same storefront for that endpoint every time in the browser, and a new one for each render on the server. Its options only count when it is first made. Use it when the storefront has to be made in a component; createStorefront in a component, including a useState initializer, can leave two storefronts following the tab when Strict Mode renders twice.
The hooks hydrate against the same state the server rendered before switching to the browser's cart, signed-in customer and visitor-specific catalog. That keeps an earlier visit's cached catalog from causing a hydration mismatch. initialCatalog is public catalog data; it doesn't sign a customer in on the server. Without it, server-rendered product hooks start empty, so supply fallback copy and prices.
Cookie consent
When a visitor adds to their cart, checks out or signs up, the SDK sends the UTM tags, referring site and ad click IDs they arrived with. It only keeps the click IDs once the visitor has agreed to marketing cookies, and until you report a choice it follows your store's Ad and campaign tracking setting. UTM tracking covers how that turns into revenue attribution.
For your own cookie banner, use useAttributionConsent:
import { useAttributionConsent } from '@moonbase.sh/react'
function CookieBanner() {
const { required, answer, setAnswer } = useAttributionConsent()
if (required !== true || answer !== null)
return null
return (
<div role="dialog" aria-label="Marketing cookies">
<p>Can we remember which ad brought you here?</p>
<button type="button" onClick={() => setAnswer(false)}>Decline</button>
<button type="button" onClick={() => setAnswer(true)}>Accept</button>
</div>
)
}
required is undefined until the browser has loaded a catalog for this visitor, since a server-fetched catalog describes the server's location. answer is null until the visitor chooses. setAnswer reports the choice and remembers it across visits, and the storefront starts from it next time unless you pass an explicit attributionConsent option. Give visitors a way to reopen the banner and change their answer, as Corino does from its footer.
If your site already has a consent manager, call storefront.setAttributionConsent(granted) from its marketing-consent callback, or pass attributionConsent when making the storefront. That method leaves remembering the answer to your consent manager. A banner that asks for Google's signals separately can pass { adUserData, adPersonalization }; click IDs are kept when adUserData is granted.
If your consent manager remembers when the visitor answered, pass that time too: setAttributionConsent(granted, answeredAt), or attributionConsentAnsweredAt beside attributionConsent. Moonbase then counts the answer from when it was given, so an acceptance a browser kept never outweighs a refusal the customer made since, and records a signed-in customer's acceptance on their account as well as a refusal. setAnswer from useAttributionConsent passes the time for you.
persistUtm: true keeps consented attribution in local storage across visits instead of the default session storage. Without consent, the SDK keeps the UTM tags, referrer and ad platforms for the tab, without the click IDs.
A browser that sends Global Privacy Control counts as refusing tracking for each connected ad platform unless your store sets that platform to ignore it. attributionConsentStatusByPlatform in the storefront's state reports the status for meta and googleAnalytics; no browser IDs are sent for a platform that is refused. attributionConsentStatus reports the overall status as 'granted', 'refused' or 'unknown'.
Hooks
All hooks read the storefront passed to StorefrontProvider. They return plain values, and the component renders again when the part it reads changes. Every function a hook returns keeps its identity across renders, so it can go straight into an effect's dependency list. Call hooks at the top of a component, before any early returns.
useAuth
useAuth gives you the signed-in customer, whether the SDK has loaded them yet, and the functions around signing in and managing their account:
import { useAuth } from '@moonbase.sh/react'
const {
user,
loaded,
signIn,
signUp,
signOut,
update,
updateAddress,
setPassword,
forgotPassword,
resetPassword,
confirmAccount,
confirmEmail,
confirmEmailChange,
getAccessToken,
refreshUser,
} = useAuth()
user is null until someone is known to be signed in. Wait for loaded before showing "Sign in", so a returning customer doesn't see it while the SDK restores their session. Access-token renewal is handled for you.
signIn(email, password) signs a customer in. signUp(name, email, password, address, acceptedPrivacyPolicy, acceptedTermsAndConditions, communicationOptIn?, options?) creates their account. Pass { groupIds: ['beta-testers'] } in options to add the new customer to customer lists open to sign-ups. When the store requires email confirmation, it resolves with status: 'activation-pending'; show a "Check your email" message. An account that exists without a password can throw PasswordSetupRequiredError and receive the same confirmation link.
confirmAccount(email, code) normally signs the customer in. If its result has status: 'PasswordSetupRequired', ask for a password, call resetPassword(result.email, newPassword, result.resetPasswordToken!), then sign in. forgotPassword(email) sends a reset link, and resetPassword(email, newPassword, code) finishes it. confirmEmail(email, code) and confirmEmailChange(email, code) finish their respective links. The confirmation calls share duplicate in-flight calls and briefly keep the result, so an effect running twice in development doesn't redeem a one-use code twice.
update(name, email, emailConfirmationToken?, communicationPreferences?) changes the profile; needsEmailConfirmationToken in the result says whether the changed email is waiting on confirmation. updateAddress(address) saves the address for the next checkout, and setPassword(currentPassword, newPassword) changes the password. These calls, signOut and confirmEmailChange need a signed-in customer.
If you turn on Captcha under Account settings > Storefront > Features, draw the challenge and pass { captchaToken } in signUp's last argument, or it throws CaptchaRequiredError. See Sign up in the Storefront API.
To call your own API for the signed-in customer, send it the token from getAccessToken(), which is renewed first when it is about to run out, and verify it on your server as described in Verify access tokens. It resolves to null when nobody is signed in.
useInventory
useInventory exposes the calls behind owned products, licenses, activations, downloads and subscriptions. Use it for actions, or when you want to load the data yourself. The account data hooks below load the common account-page lists for you.
import { useInventory } from '@moonbase.sh/react'
const {
getLicenses,
getLicenseActivations,
getProduct,
getProducts,
getProductReleases,
getProductLicenses,
getProductActivations,
revokeActivation,
activateProduct,
downloadProduct,
getSubscription,
getSubscriptions,
cancelSubscription,
renewSubscription,
payOffSubscription,
updateSubscriptionPaymentMethod,
getSubscriptionPlanOptions,
changeSubscriptionPlan,
cancelSubscriptionPlanChange,
} = useInventory()
Customer inventory and subscription management need a signed-in customer. List calls return pages with items and next; pass next back for the next page until it is null. Single-item calls such as getProduct(id, version?) and getSubscription(id) return the detail directly.
getProduct returns downloads, licenses and metadata for a release. Its downloadsAllowed is the API's verdict on whether this visitor may download it. Gate restricted download UI on that flag; the neighboring downloadsNeedsUser, downloadsNeedsOwnership and downloadsNeedsGroupMembership flags explain a refusal. If all are false and access is still refused, downloads are closed to everyone. These policies can differ for past, current and prerelease versions.
Use downloadProduct(download) for files that need authentication; opening their path directly doesn't supply it. Public trial files can come from a catalog product's downloads, without loading signed-in inventory. visitorPlatform(), sortDownloads(downloads, platform) and describeDownload(download) help put the visitor's installers first and label their platform, architecture and size.
For a product sold with licenses that cover only some releases, owned products and licenses also carry releaseAccess, with an upgradeUrl to buy the upgrade. downloadProduct throws ReleaseNotCoveredError, a NotAuthorizedError carrying that URL, for a release they don't cover.
revokeActivation(activation) frees a seat for another computer. Offer it only where activation.revocable is true. It is false for offline activations, and for a product where you prevent customers from revoking activations, and revoking such an activation throws. For offline activation, activateProduct(deviceToken, ActivationMethod.Offline) returns a license and a url for its license file.
For subscriptions, cancelSubscription(id, feedback?) cancels, renewSubscription(id, options?) opens checkout for a lapsed subscription, and updateSubscriptionPaymentMethod(subscription) opens the card-update form. While a milestone subscription can be paid off early, its payoff says how many payments are left and their total, and payOffSubscription(id, options?) opens the checkout that pays them all at once. A paid-off subscription has paidOffAt. getSubscriptionPlanOptions(id) lists plans the subscription can switch to; changeSubscriptionPlan(id, variationId) schedules the change for the end of the paid period, and cancelSubscriptionPlanChange(id) cancels it.
Account data hooks
These hooks load for whoever is signed in, and load again when that changes:
| Hook | Data |
|---|---|
useOwnedProducts() | Owned products and trials, a page at a time |
useOwnedProduct(productId) | One owned product, with its downloads |
useProductActivations(productId) | The computers the product's licenses are activated on |
useProductLicenses(productId) | The customer's licenses for the product |
useOrderHistory() | Completed orders, newest first |
useSubscriptions() | The customer's subscriptions |
useSubscription(subscriptionId) | One subscription |
Each returns { data, loading, error, reload }. Lists add hasMore and loadMore, with data holding all the pages loaded so far. data is null while it first loads, when nobody is signed in, and when an ID is null or undefined. loading also covers the initial wait to find out who is signed in and any background refresh.
import { useOwnedProducts } from '@moonbase.sh/react'
function Products() {
const products = useOwnedProducts()
if (!products.data) {
if (products.error)
return <button type="button" onClick={products.reload}>Try again</button>
return <p>Loading…</p>
}
return (
<>
{products.data.length === 0 && <p>No products yet.</p>}
<ul>{products.data.map(product => <li key={product.id}>{product.name}</li>)}</ul>
{products.error && <p role="alert">{products.error.message}</p>}
{products.hasMore && (
<button type="button" disabled={products.loading} onClick={products.loadMore}>Show more</button>
)}
</>
)
}
Render this inside a page that first checks useAuth().loaded and user. The hooks keep what they loaded for the same customer: returning to a tab shows it immediately and refreshes it in the background, and components asking for the same data share a request. reload() goes back to the first page. Both reload and loadMore put failures in error rather than rejecting, and keep any data already shown.
After changing something, reload the data that shows it. Corino reloads both useProductActivations(id) and useOwnedProduct(id) after revoking an activation, because the product also holds the seat count.
useOrders
useOrders gives you completed orders and their PDF receipts. It needs a signed-in customer:
import { useOrders } from '@moonbase.sh/react'
const { getOrders, getReceipt, downloadReceipt } = useOrders()
const page = await getOrders()
// page.items: completed orders, newest first
// page.next: pass to getOrders() for the next page, until null
Rely on next, rather than how many items came back: a page can be short or empty with more after it. useOrderHistory() handles that pagination for a component. Write each total with formatMoney(order.total.due). getReceipt(order) returns a PDF Blob for your own viewer, and downloadReceipt(order) saves it as a browser download.
useActivationRequest
useActivationRequest follows the online activation request a plugin opens in the browser. Read its token from your activation page's address:
import { useActivationRequest } from '@moonbase.sh/react'
const {
activationRequest,
loading,
fulfilling,
completing,
error,
isInstalled,
fulfillLicense,
fulfillTrial,
cancel,
} = useActivationRequest(token, { autoFulfill: true })
The hook loads the request, again when the signed-in customer changes, and follows it until the plugin picks up its license. A null or undefined token loads nothing. fulfilling covers granting the license or trial; completing covers waiting for the plugin to pick it up; isInstalled says it has.
fulfillLicense() activates with a license the customer owns. With { autoFulfill: true }, the hook does that once per request as soon as licenseEligibility.eligible is true and the request is still Requested. A failure stays in error, and calling fulfillLicense tries again. Leave the option out to put activation behind your own button. Buying a license is a separate cart or checkout action; the hook then sees the updated eligibility.
fulfillTrial(newsletterOptIn?) starts a trial when trialEligibility.eligible. If trialEligibility.requiresAccount is true, ask the visitor to sign in first. If requiresNewsletterOptIn is true and they haven't already opted in, require a checkbox and pass true. cancel() abandons the request.
See activation/AutoActivation.tsx for the complete page, including buying, signing in and freeing a seat when all seats are in use.
useProduct and useProducts
useProduct(id) returns one catalog product, or null before the catalog has loaded or when the ID isn't found. A null or undefined ID also returns null, so you can call the hook on every render even when there is nothing to look up. A changed ID looks up the new product.
import { useProduct, useProducts } from '@moonbase.sh/react'
const product = useProduct('halo')
const products = useProducts()
useProducts() returns every available product, or an empty array before loading. useCatalog() returns the whole catalog. Use useStorefrontState(state => state.catalogLoaded) to distinguish loading from an empty catalog. The catalog is priced for the visitor and includes owned for the signed-in customer; it is refreshed after sign-in, sign-out and purchase.
A product's description is Markdown. To show it formatted, render its descriptionHtml, which is safe to insert as it is (see Rich text). Release notes and license fulfillment messages come the same way, as releaseDescriptionHtml and fulfillmentMessageHtml.
<div dangerouslySetInnerHTML={{ __html: product.descriptionHtml ?? '' }} />
useBundle and useBundles
These work the same way for bundles:
import { useBundle, useBundles } from '@moonbase.sh/react'
const bundle = useBundle('duo-bundle')
const bundles = useBundles()
Both products and bundles have a defaultVariation and variations for their pricing options. Pass the option the customer picks to addToCart(item, variation) or to useCheckout.
usePrice
usePrice(variation) writes a pricing option's price in the visitor's currency, the way the checkout does:
import { useCartActions, usePrice, useProduct } from '@moonbase.sh/react'
function ProductPrice({ productId }: { productId: string }) {
const product = useProduct(productId)
const { price, originalPrice, saving, amount, currency } = usePrice(product?.defaultVariation)
const { addToCart } = useCartActions()
return (
<button type="button" disabled={!product} onClick={() => product && addToCart(product)}>
{price ?? 'Loading price…'}
</button>
)
}
price is undefined until there is a price in that currency. originalPrice and saving are set when the option has a discount. amount is the numeric price for calculations, and currency is the currency the cart and checkout use. useCurrency() returns just that currency. For cart lines, totals and orders, use formatMoney(money) or formatMoney(amount, currency).
usePrice, useCurrency and useCartActions don't render the component again when the cart changes, which makes them a good fit for product cards.
useOffer and useOffers
useOffer(id) returns one offer or null, and useOffers() returns all available offers. The lists below help you decide which ones to show around the cart:
import { useEligibleOffers, useLockedOffers, useOffers } from '@moonbase.sh/react'
const offers = useOffers()
const eligibleOffers = useEligibleOffers()
const lockedOffers = useLockedOffers()
useEligibleOffers() gives offers the cart qualifies for on items it doesn't hold yet. To accept one, pass it as the third argument to addToCart(item, variation, offer). useLockedOffers() gives spend-based item offers the cart is short of, each with offer and progress, nearest first. Show how much more the customer has to spend to reach one. Before the catalog loads these lists are empty.
useCartOffer
A cart offer discounts the whole order once it clears a threshold. The SDK applies the best one automatically; useCartOffer() gives you what to show:
import { useCartOffer } from '@moonbase.sh/react'
const cartOffer = useCartOffer()
// cartOffer.applied: { offer, saving }, or null
// cartOffer.next: { offer, progress }, or null
// cartOffer.subtotal and cartOffer.currency
It returns null until there is a cart to reason about. applied and next can both be set for tiered offers; the next one is always worth more than the applied one. progress.remaining and progress.fraction let you write a "spend a little more" prompt and draw a progress bar.
usePromotions
usePromotions() returns the sales currently running across your catalog. Their dates and audience have already been evaluated by Moonbase, so show them as they are. The list changes when the customer signs in or out. A pricing variation only shows its best discount; check the variation's discount.promotionId to see which promotion is pricing it.
useCart
useCart gives you the lines, prices and actions for the cart:
import { useCart } from '@moonbase.sh/react'
const {
items,
soldOutItems,
currency,
total,
breakdown,
cartOffer,
addToCart,
setQuantity,
removeFromCart,
checkout,
} = useCart()
items are filled in with their catalog products or bundles and prices. total is { amount, currency }; breakdown explains it: original at list price, subtotal after product discounts and item offers, cartOffer on top of that, discount for every saving, and amount due. These are before taxes, which checkout works out from the billing address. Lines in soldOutItems must be removed before payment.
addToCart(item, variation?, offer?, options?) adds one product or bundle, or one more if it is already there, and returns its cart line. setQuantity(line, quantity) sets the quantity; zero removes it. removeFromCart(line) removes it directly. The SDK keeps the cart in browser storage and synchronized across tabs.
Pass { bundleBehaviour: 'replace' } as the fourth argument to take out included products sold on the bundle's terms, and put them back if it is removed. For release-access upgrades, pass { targetLicenseId: license.id } to extend that license at the price in the product's licenseUpgrades; each upgraded license is a separate line with quantity 1. Without it the purchase issues a new license.
Item offers normally reach a line when your UI passes one to addToCart. Set autoApplyItemOffers: true when making the storefront, or storefront.autoApplyItemOffers = true later, to let it attach eligible offers to existing lines itself. It never adds items or replaces an offer a line already holds. Cart offers always apply themselves.
useCartActions() returns the same actions without subscribing to cart changes. Use it where the component only needs to add or remove something.
Where checkout happens
checkout(options?), useCheckout(), renewSubscription() and payOffSubscription() accept the same redirect option:
| Value | Behavior |
|---|---|
'auto' (default) | Overlay iframe on desktop and tablet, full-page redirect on phones |
'always' / true | Always redirect to the Moonbase-hosted checkout |
'never' / false | Always use the overlay iframe |
Apple Pay and Google Pay need the hosted checkout as the top-level page, so 'auto' brings them back on phones while keeping the overlay on desktop. Corino always uses the overlay, with checkout({ redirect: false, returnUrl: pathname }).
The overlay's promise settles when it closes, which can be minutes later. Keep a checkout button's pending state in useState and clear it in finally; a pending transition can hold back other transitions, including router navigation. A redirect resolves with { completed: false, redirected: true }, since the outcome only arrives on the return page. Check redirected before treating completed: false as abandonment.
returnUrl defaults to the current page, query string and hash included, with Moonbase's mb_* parameters removed. The cart empties after payment. Use the checkoutCompleted event to thank the customer or close your drawer, including after a customer returns from the hosted checkout.
checkout({ groupIds }) adds the buyer to customer lists open to sign-ups once the order is paid.
useCheckout
useCheckout buys straight away without putting items in the cart:
const checkout = useCheckout()
// From a button, once product exists:
await checkout([{ item: product, variation: product.defaultVariation, quantity: 1 }], {
redirect: 'auto',
returnUrl: '/order-completed',
})
Each item also accepts targetLicenseId for a release-access upgrade. Options include couponCode, groupIds for customer lists the buyer joins once the order is paid, and onCouponRejected. A refused coupon calls that handler and opens checkout without it.
Starting another direct checkout as the same customer within 24 hours reuses the previous order while it is still open, keeping billing details with the new items. A coupon supplied by the previous call is removed unless supplied again; one the buyer typed stays. If another tab reopens the order, an overlay showing its old items closes and resolves with completed: false.
useCommunicationPreferences
This hook handles newsletter sign-ups for anyone, signed in or not, and the preference and unsubscribe links in marketing emails:
import { useCommunicationPreferences } from '@moonbase.sh/react'
const { subscribe, confirm, get, update, unsubscribe } = useCommunicationPreferences()
const result = await subscribe({ email, name, newsletter: true, productUpdates: true })
subscribe returns status: 'confirmation_sent' when the store asks subscribers to confirm by email, or 'subscribed' when preferences were recorded directly. Show the right message for both. newsletter and productUpdates default to true; groupIds joins customer lists open to sign-ups (a subscriber who has to confirm by email joins once they do), and captchaToken supplies a captcha solution when the store requires one.
confirm(email, token) finishes double opt-in. get(email, token) reads preferences, update(email, token, { newsletter, productUpdates }) changes them, and unsubscribe(email, token) turns both off. The latter three use the long-lived unsubscribe token from the email. See Communications in the Storefront API.
useVoucher
useVoucher has peek(code) to see what a voucher gives, and redeem(code) to claim it. Redemption needs a signed-in customer. The result describes the products and bundles granted, and carries gift when the code is a gift's.
useGift
On accounts with gift purchases turned on, a buyer can send their order to someone else, who claims it with the code from the gift email. peek(code) shows anyone with the code who the gift is from and what it holds. claim(code) adds it to the signed-in customer's account and reloads them, so their owned products include it:
import { GiftClaimStatus, useGift } from '@moonbase.sh/react'
const { peek, claim } = useGift()
const gift = await peek(code)
if (gift.status === GiftClaimStatus.Unclaimed)
await claim(code) // Needs a signed-in customer
status is Unclaimed, ClaimedByYou or ClaimedByOther. Both calls throw NotFoundError for an unknown code and GiftUnavailableError for a gift refunded before anyone claimed it; claim throws GiftAlreadyClaimedError when someone else claimed it first. Completed orders carry gift when the buyer sent one, including when a scheduled gift is emailed. See Gifts in the Storefront API.
useReviews
Only signed-in customers with a qualifying paid purchase may write; anyone can read published reviews. enabled reflects the catalog's reviewsEnabled flag. A product's mayReview and reviewed help choose whether to show a review action, but the form must read getMyReview for current edit eligibility. See the review API for the exact models, statuses and validation limits.
getReviews(productId, { sort, stars }) returns summary, items, hasMore and next. ProductReviewSort supplies Helpful, Newest, Highest and Lowest; stars is an optional number from 1 to 5. Follow next with getMoreReviews(next) and append its items. A star filter always sorts newest first. The summary still covers all published stars.
This component reads the first page and loads more on demand. hasRating hides a score until a review has been published. Mount it under your StorefrontProvider:
'use client'
import { hasRating, useReviews, type ProductReviewPage } from '@moonbase.sh/react'
import { useEffect, useRef, useState } from 'react'
export function ProductReviews({ productId }: { productId: string }) {
const { enabled, getReviews, getMoreReviews } = useReviews()
const [page, setPage] = useState<ProductReviewPage | null>(null)
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
// Counts list loads, so a response for a product no longer shown is dropped
const request = useRef(0)
useEffect(() => {
const id = ++request.current
setPage(null)
setError('')
if (enabled) {
getReviews(productId).then(
value => { if (request.current === id) setPage(value) },
() => { if (request.current === id) setError('Reviews could not be loaded.') },
)
}
}, [enabled, productId, getReviews])
async function loadMore() {
if (!page?.next || loading) return
const id = request.current
setLoading(true)
try {
const more = await getMoreReviews(page.next)
if (request.current === id)
setPage(previous => previous && { ...more, items: [...previous.items, ...more.items] })
}
catch { if (request.current === id) setError('More reviews could not be loaded.') }
finally { setLoading(false) }
}
if (!enabled) return null
return (
<section aria-label="Product reviews">
{page && hasRating(page.summary) && (
<p>{page.summary.average} / 5 from {page.summary.count} reviews</p>
)}
{page?.items.map(review => (
<article key={review.id}>
<h3>{review.title}</h3>
<p>{review.body}</p>
<p>{review.author.name ?? 'Verified owner'} · {review.rating} / 5</p>
</article>
))}
{page?.hasMore && <button disabled={loading} onClick={loadMore}>More reviews</button>}
{error && <p role="alert">{error}</p>}
</section>
)
}
The catalog product's rating uses the same model as page.summary, so product cards can use hasRating(product.rating) before loading a review list. To show English copy for another language, use the optional review.translation while keeping the original available. reply is the store's public reply.
Write, edit, withdraw and vote
Inside your signed-in form, read eligibility before saving. The third saveReview argument is whether a review already exists, including one previously withdrawn. The SDK chooses POST for a first submission and PUT for an edit:
const { getMyReview, saveReview, withdrawReview, voteOnReview } = useReviews()
async function submitReview() {
const mine = await getMyReview('helios')
if (!mine.eligibility.canReview)
return mine // Show reason and nextEditAllowedAt instead of submitting
return saveReview('helios', {
rating: 5,
title: 'Fits my workflow',
body: 'The controls make it easy to get the sound I want.',
displayName: 'Alex',
anonymous: false,
allowUse: true,
}, mine.review !== null)
}
// Call these from the corresponding customer actions:
await withdrawReview('helios')
await voteOnReview('helios', reviewId, 'up') // 'down' or 'none' also work
Before sending allowUse: true, show beside the submit button that the store may use the review, rating and name on its store and in marketing, with a link to your terms. For an anonymous review, use anonymous: true and displayName: null.
A successful save returns the author's document, usually with review.status: 'underReview'. It is accepted for moderation, not yet published. Updates leave the public list until checked again. Show eligibility.reason, nextEditAllowedAt and review.revisionsRemaining rather than guessing a cooldown. A needsSupport review should point the customer to supportEmail.
Withdrawal remains possible while the store has reviews disabled. A vote returns upVotes, downVotes and viewerVote, so you can update the card directly; none removes it. Customers cannot vote on their own reviews.
Other hooks
useGroups().join(groupId)joins a signed-in customer to a customer list opened to sign-ups. Joining twice is fine. A refused join throwsNotFoundErrorwithout distinguishing why, and nobody signed in throwsNotAuthenticatedError.useVendor()returns who runs the store.
Storefront state and events
useStorefront() returns the storefront itself. useStorefrontState(state => state.catalogLoaded) subscribes to one part of its state, such as catalog, user, userLoaded, order, utm or closed. closed means the Moonbase account has closed and the SDK has cleared its cached catalog, cart and session.
Have the selector return a value already in the state. Build derived objects or arrays in useMemo afterwards, so the selector doesn't give React a new value on every read.
useStorefrontEvent subscribes when its component mounts and stops when it unmounts:
const storefront = useStorefront()
useStorefrontEvent('checkoutCompleted', (order) => {
storefront.closeCheckout()
// Close your cart drawer and show a thank-you page
})
Events include checkoutInitiated, checkoutBillingDetailsAdded, checkoutPaymentStarted, checkoutPaymentFailed, checkoutCouponApplied, checkoutCouponRemoved, checkoutCouponRejected, checkoutCompleted, checkoutClosed, catalogUpdated and sessionEnded. Payment-failure reasons are Declined, AuthenticationFailed, CardDetails, ProcessingError or Other, without the card issuer's decline code. During a hosted checkout your page isn't loaded; use the OrderPaymentFailed webhook to follow failures there.
The first catalogUpdated can arrive before a component mounts. Read data the page needs from the start through a state hook, or subscribe with storefront.on(event, handler) where you make the storefront. That method returns a function to stop listening.
Outside React, the same object exposes storefront.cart, storefront.auth, storefront.checkout() and storefront.getState(). userLoadedPromise waits until sign-in is known; catalogLoadedPromise waits for the catalog. storefront.dispose() stops it for good, for tests or a page replacing one storefront with another.
Where your store has "Send page events from Moonbase's server" on in its Meta integration (the catalog's tracking.meta.sendPageEvents), relay the events your page sends to its Meta pixel with storefront.sendPageEvents(events), each with the event ID of its pixel call. Moonbase then sends them from its server too, where the visitor's consent allows, and Meta counts each once:
const eventId = crypto.randomUUID()
fbq('track', 'ViewContent', { content_ids: ['example-product'] }, { eventID: eventId })
storefront.sendPageEvents([{ id: eventId, name: 'view_item', productId: 'example-product' }])
It takes up to 20 events at a time and never throws. The Storefront API describes the event fields.
Custom storefront mode
Set your account's storefront mode to Custom integration and configure the pages Moonbase links customers to. Each configured location takes the following parameters:
| Account setting | Suggested path | Query params | SDK call |
|---|---|---|---|
AutoActivation | /activate | token | useActivationRequest(token) with fulfillLicense() or fulfillTrial(optIn) |
OfflineActivation | /activate | None | useInventory().activateProduct(deviceToken, ActivationMethod.Offline) |
LogIn | /login | None | useAuth().signIn(email, password) |
ConfirmAccount | /sign-up | email, code | useAuth().confirmAccount(email, code) |
ConfirmEmail | /confirm-email | email, code | useAuth().confirmEmail(email, code) |
ConfirmEmailChange | /account/confirm-email-change | email, code | useAuth().confirmEmailChange(email, code) |
ResetPassword | /forgot-password | email, code | useAuth().forgotPassword(email) or resetPassword(email, newPassword, code) |
DownloadProduct | /download | product_id, optional version and key | Redirect to the product's account page, then useInventory().downloadProduct(download) |
Checkout | Optional | Leave unset for the hosted fallback; open your cart's checkout with useCart().checkout() | |
ManageSubscription | /subscriptions | subscription_id | useSubscription(id) or useInventory().getSubscription(id) |
The paths are suggestions; the configured locations must match the routes you implement. In Next, wrap client components that use useSearchParams in Suspense so their pages can prerender. Corino implements every callback above; its subscription page shows basic detail because the demo shop doesn't sell subscriptions.
Reference implementation: Corino
The open-source Corino reference site is a Next.js 16 storefront for a fictional Oslo audio-plugin company, wired to corino-demo.moonbase.sh. Build a custom website with React walks through its code, and you can try it at corino-react.moonbase.sh.
It demonstrates:
- Server-rendered prices with
fetchCatalog,getStorefrontandinitialCatalog, with hourly catalog revalidation and fallback prices if the fetch fails. - Product and bundle cards with
useProduct,useBundle,usePriceanduseCartActions, swapping "Add to cart" for "Download" when the customer owns the product. - A cart drawer and checkout overlay, with
useCart,formatMoney, component state for the pending checkout andcheckoutCompletedcleanup inStorefrontEffects.tsx. - Sign-in, sign-up and callback pages, including password setup, email confirmation and password reset.
- Downloads and trials, with public files from the catalog, owned files from
useOwnedProduct, andsortDownloadsanddescribeDownloadfor platform labels. - An account area with profile changes, products, activations, external licenses, purchase history, receipt PDFs and voucher redemption.
- Online and offline activation, with
useActivationRequest(token, { autoFulfill: true })and machine-file uploads throughactivateProduct. - Newsletter sign-ups and cookie consent, with
useCommunicationPreferencesanduseAttributionConsent. - Marketing links that add a product or bundle from
?add_product=or?add_bundle=and open the cart drawer.
Next.js 16 reference storefront demonstrating the React SDK end to end against the public Corino demo Moonbase account.
If you want a much smaller integration with no build step, the embedded storefront docs cover a separate single-file HTML reference site for the same fictional shop.