@moonbase.sh/storefront-api
v3.25.1
Published
Package to let you build storefronts with Moonbase.sh as payment and delivery provider
Readme
@moonbase.sh/storefront-api
Browser-first Moonbase SDK for storefront and customer flows: storefront data, identity, carts/orders, vouchers, inventory, and activation requests. Learn more about our storefront API in our official docs: https://moonbase.sh/docs/storefronts/api/
Install
pnpm add @moonbase.sh/storefront-apiCreate a client
import { MoonbaseClient } from '@moonbase.sh/storefront-api'
const client = new MoonbaseClient({
endpoint: 'https://demo.moonbase.sh',
persistUtm: true,
})Configuration notes:
endpoint: your Moonbase storefront URL.includeManifests: include downloadable file manifests when available.persistUtm: in@moonbase.sh/vue, keep the attribution a visitor arrived with in localStorage, across visits, instead of sessionStorage for the tab. Only with the visitor's consent (seeattributionConsent); a refusal removes it.attributionConsent: in@moonbase.sh/vue, whether the visitor has agreed to marketing cookies.falsekeeps the UTM tags, campaign IDs, referrer and the ad platforms a click came from (adClicks) but not the ad click IDs themselves, and records a tagged arrival on the order only with the first thing put in the cart;truekeeps the click IDs too. A banner that asks for Google's two parts separately can pass{ adUserData, adPersonalization }instead, and the click IDs are kept whenadUserDatais granted. Left out, it follows the store's own setting in Moonbase, which the catalog reports for this visitor ascookieConsentRequired. Change it later withsetAttributionConsent().attributionConsentAnsweredAt: when the visitor gave the answer inattributionConsent, as ISO 8601, for a banner that remembers it. Moonbase then counts the answer from that time, so an acceptance the browser kept never outweighs a refusal the customer made since, and@moonbase.sh/vueand@moonbase.sh/reactalso record a signed-in customer's acceptance on their account.setAttributionConsent()takes it as its second argument.
Common usage
Load storefront and create an order
const storefront = await client.storefront.get()
const order = await client.orders.pushContent(
{
id: crypto.randomUUID(),
currency: storefront.suggestedCurrency,
items: [
{
type: 'Product',
productId: storefront.products[0].id,
variationId: storefront.products[0].defaultVariation?.id ?? '',
quantity: 1,
},
],
},
{
returnUrl: `${window.location.origin}/checkout-complete`,
},
)
const redirectUrl = order.hostedCheckoutUrl ?? order.checkoutUrl
if (redirectUrl)
window.location.href = redirectUrlSign in a customer
await client.identity.signIn('[email protected]', 'password')
const user = await client.identity.get()
console.log(user.email)Save a customer's address
The signed-in customer's next checkout starts from the address saved here. A checkout they have already entered billing details in keeps those.
const user = await client.identity.updateAddress({
countryCode: 'AU',
streetAddress1: '1 George Street',
streetAddress2: null,
locality: 'Sydney',
region: 'NSW',
postCode: '2000',
})Redeem a voucher
const preview = await client.vouchers.peek('MY-CODE')
console.log(preview)
await client.identity.signIn('[email protected]', 'password')
const redeemed = await client.vouchers.redeem('MY-CODE')
console.log(redeemed)Enroll a customer in a group
Merchant-owned customer lists that have been opened to public sign-ups can be named by ID on sign-up, on a newsletter subscription, and on an order:
await client.identity.signUp('Jane', '[email protected]', 'password', null, true, true, true, {
groupIds: ['newsletter-2026'],
})
await client.communications.subscribe({ email: '[email protected]', groupIds: ['newsletter-2026'] })
// On an order, after it has been pushed and before it is paid. Additive: each
// call adds to what the order already carries.
await client.orders.joinGroups(order.id, ['buyers-2026'])None of those three report which groups were applied. An ID naming a list that is closed, deleted, rule-driven or another tenant's is skipped in silence, so a stale ID can never fail a registration or a sale. IDs are matched lowercase and at most five per request are applied.
For a customer who is already signed in, joining is a request of its own, and it is the one that does report failure:
await client.groups.join('beta') // throws NotFoundError if it isn't joinableEvery reason it can be refused (no such group, deleted, closed, a segment,
another tenant's) arrives as the same NotFoundError, so that a signed-in
customer cannot use it to enumerate a merchant's group IDs. Joining twice
succeeds and changes nothing.
Captchas on sign-up and newsletter sign-ups
A merchant can ask customers to solve a captcha before they sign up or subscribe to the newsletter. The vendor says whether this store does:
const vendor = await client.vendor.get()
const captcha = vendor.features?.captcha // { url } when it does, null or undefined when notcaptcha.url is a page on the store's own <account-id>.moonbase.sh that draws
the challenge. Embed it in an iframe with action=signup, and it hands you the
solution with postMessage:
const src = new URL(captcha.url)
src.searchParams.set('action', 'signup') // optional: theme=light|dark|auto, size=normal|compact
const frame = document.createElement('iframe')
frame.src = src.href
frame.title = 'Captcha'
frame.style.cssText = 'border: none; color-scheme: normal; width: 300px; height: 65px'
form.append(frame)
let captchaToken: string | undefined
window.addEventListener('message', (event) => {
if (event.source !== frame.contentWindow || event.origin !== src.origin || event.data?.source !== 'moonbase-captcha')
return
if (event.data.event === 'resize')
Object.assign(frame.style, { width: `${event.data.width}px`, height: `${event.data.height}px` })
else if (event.data.event === 'token')
captchaToken = event.data.token
else // 'expired', or 'error' with a `code` ('load-failed' when the challenge could not load)
captchaToken = undefined
})Then pass the solution along, and reset the frame after every attempt, since a solution is good for one:
try {
await client.identity.signUp('Jane', '[email protected]', 'password', null, true, true, true, {
captchaToken,
})
}
catch (err) {
if (err instanceof CaptchaRequiredError)
showError(err.message) // the API's own copy, safe to show
throw err
}
finally {
captchaToken = undefined
frame.contentWindow?.postMessage({ source: 'moonbase-captcha', command: 'reset' }, src.origin)
}Without a solution, or with one that is expired or already used, the sign-up is
refused with CaptchaRequiredError (a MoonbaseError). A site with a
Content-Security-Policy has to allow the store's https://<account-id>.moonbase.sh
in frame-src.
A newsletter sign-up works the same way, with a frame drawn for
action=subscribe (a solution is only good for the action it was drawn for):
await client.communications.subscribe({ email: '[email protected]', captchaToken })Where a customer came from
Pass the UTM tags, ad click IDs and referrer the visitor arrived with, the same shape orders take, so the merchant can see how the customer was acquired:
import { parseOffSiteReferrer } from '@moonbase.sh/storefront-api'
const params = new URLSearchParams(window.location.search)
await client.identity.signUp('Jane', '[email protected]', 'password', null, true, true, true, {
utm: {
source: params.get('utm_source') || undefined,
campaign: params.get('utm_campaign') || undefined,
id: params.get('utm_id') || undefined,
// Google's campaign IDs, which name a campaign rather than the visitor.
gadSource: params.get('gad_source') || undefined,
gadCampaignId: params.get('gad_campaignid') || undefined,
// Click IDs ad platforms add to the link, often with no UTM tags beside them.
gclid: params.get('gclid') || undefined,
fbclid: params.get('fbclid') || undefined,
msclkid: params.get('msclkid') || undefined,
ttclid: params.get('ttclid') || undefined,
// The referring site's host only, and nothing when the visitor came from this site.
referrer: parseOffSiteReferrer(document.referrer, window.location.origin),
},
})Fields left out are not sent. The click IDs (gclid, gbraid and wbraid from
Google Ads, fbclid from Meta, msclkid from Microsoft Advertising and ttclid
from TikTok) and Google's campaign IDs (gad_source, gad_campaignid) go to the
API under those names, and the rest as utm_* (id as utm_id).
useAuth().signUp in @moonbase.sh/vue, and so the storefront widget, fills this
in from the tags and click IDs it has already picked up, unless you pass your own
utm. useInventory().downloadProduct sends the same tags with each download, as
sign-up does.
A click ID identifies the visitor's click, so only send one once the visitor has
agreed to marketing cookies, where the law asks for that. withoutClickIds(utm)
drops their values and keeps the platforms they came from in adClicks (sent as
utm_ad_click), which still counts the visit as an ad click. The campaign IDs
name a campaign, not a visitor, so it keeps them.
What the visitor agreed to, and where they landed
The cart push, sign-up, trial, newsletter subscription and download link also take
AdSignals: what your cookie banner reported of the visitor's consent to ad
tracking, and when and where their tagged arrival landed. Moonbase records them
for ad measurement. The download link takes the visit's utm too, after the
signals, so the merchant's download analytics can tell which campaign brought the
visitor.
const signals = {
// One choice for all ad tracking, or Google's two parts:
// { adUserData: true, adPersonalization: false }
consent: true,
// The first page of the visit that carried its tags, origin and path only.
arrivedAt: '2026-11-10T09:30:00.000Z',
landingPage: 'https://shop.example/plugins/reverb',
}
await client.orders.pushContent(order, undefined, utm, signals)
await client.identity.signUp('Jane', '[email protected]', 'password', null, true, true, true, { utm, signals })
await client.activationRequests.fulfillTrial(requestId, utm, signals)
await client.communications.subscribe({ email: '[email protected]' }, signals)
const url = await client.inventory.products.getDownloadUrl(download.path, signals, utm)They go as query parameters: ad_consent=granted|denied, or ad_user_data and
ad_personalization for the two parts, then arrived_at and landing_page. Leave
consent out when the banner has said nothing, and Moonbase follows the store's
own setting. @moonbase.sh/vue fills all of this in itself.
Where the store connected Meta or Google Analytics in Moonbase (the catalog's
tracking names the pixels and streams), and the visitor's consent lets click IDs
go, signals also carry their browser IDs, which Moonbase matches its own events to
the visitor by: fbp, fbc, gaClientId, gaSessionId and pageUrl (origin and
path only). readBrowserIdentifiers reads them from the page's cookies. When a
signed-in customer withdraws consent with nothing else to send it with, tell
Moonbase on its own:
await client.identity.reportAdConsent({ consent: false })Inventory flow
Most inventory endpoints require an authenticated user:
const products = await client.inventory.products.getOwned()
const licenses = await client.inventory.licenses.get()Pagination on inventory endpoints is done by passing the next URL back into the same method:
let page = await client.inventory.products.getOwned()
while (page.hasMore && page.next) {
page = await client.inventory.products.getOwned(page.next)
}A product's release history needs no sign-in. getReleases lists its published releases, highest
version first, each with its version, release notes, publish date and files, and whether the caller
may download it (downloadsAllowed). It pages the same way:
const releases = await client.inventory.products.getReleases('my-product')Product reviews
When the store takes reviews, the catalog says so with reviewsEnabled, and each product carries its
rating (the average, the count and how many reviews gave each star). client.reviews reads the
published reviews and lets a customer who owns or subscribes to a product write one:
import { hasRating, ProductReviewSort } from '@moonbase.sh/storefront-api'
// Anyone can read them, a page at a time. Follow `next` with `getMore` for the rest.
const page = await client.reviews.get('my-product', { sort: ProductReviewSort.Newest, stars: 5 })
if (hasRating(page.summary))
console.log(`${page.summary.average} from ${page.summary.count} reviews`)
// Signed in: their own review, and whether they may write or change one now
const mine = await client.reviews.getMine('my-product')
if (mine.eligibility.canReview) {
await client.reviews.submit('my-product', {
rating: 5,
title: 'Warm and light on CPU',
body: 'It has been on every mix since I bought it.',
displayName: 'Jane',
anonymous: false,
})
}A review is checked before it is published, so submit and edit return the customer's own copy,
with a status that reads underReview until then. A review that asks for help rather than
reviewing the product is held, reads needsSupport, and supportEmail says where the store answers
support questions. Signed-in customers can mark other people's reviews helpful with vote, and
withdraw takes their own down. A store that does not take reviews answers every call with a
NotFoundError.
Endpoint groups
client.storefront, client.identity, client.orders, client.vouchers, client.inventory, client.activationRequests, client.vendor, client.communications, client.groups, client.reviews.
Image renditions
Assets are stored once, at full size, and every product icon, bundle icon, logo and promotion
image arrives as a single URL. ImageUtils rewrites that URL to ask the CDN for a rendition
sized to where you're actually painting it, so a 96px icon costs 96px:
import { ImageUtils } from '@moonbase.sh/storefront-api'
// Fit inside a box — the natural choice for artwork of unknown shape.
ImageUtils.transform(product.iconUrl, { width: 96 })
// https://assets.moonbase.sh/_i/acme/…/icon.png?w=96
// Crop to fill an exact box, and hand retina screens the sharper one.
ImageUtils.srcSet(product.iconUrl, { width: 96, fit: 'cover' }, 1, 2)Widths are rounded up to the sizes the CDN serves, so two requests for the same visual size share one cached rendition. A URL that isn't a Moonbase asset — a merchant's own artwork on their own host — is returned untouched and logs a warning, since it will be served at full size.
Token storage and logging
By default, credentials are stored in localStorage, falling back to memory only when localStorage
cannot be reached at all. Even that check sits inside a try, because reading
window.localStorage itself throws in Firefox when the buyer has blocked cookies and site data.
Reachability, not writability, is the test on purpose: an origin that is merely full is still
holding the buyer's existing session, so it is used rather than discarded. Individual reads and
writes that fail degrade to an in-memory copy and warn through the configured logger. The session
stays valid for that page load; it just doesn't survive a reload, and
client.tokenStore.isPersistent goes false once that has happened if you want to tell the buyer.
A failure to persist credentials is never reported as a failure to sign in, so a locked-down
browser can't strand someone in a sign-in loop.
You can inject your own storage/logger implementations:
import { ConsoleLogger, InMemoryStore, LogLevel, MoonbaseClient } from '@moonbase.sh/storefront-api'
const client = new MoonbaseClient({
endpoint: 'https://demo.moonbase.sh',
store: new InMemoryStore(),
logger: new ConsoleLogger(LogLevel.Debug),
})