index
Interfaces
CreateHeadlessSourceOptions
Properties
apiUrl
apiUrl: string | null | undefined;Base URL of the Headless API. null/undefined/'' -> no source; the caller falls back to initialData only.
locale?
locale?: string;shopDomain?
shopDomain?: string;The shop's myshopify domain — REQUIRED for getInfo() (beat 2), the one
method scoped by ?d= rather than the JWT. Must be the MYSHOPIFY domain, not
the Hydrogen host's window.location.hostname (which resolves no shop). Fed
into the shared client at construction — see ensureClient.
tokenRoute?
tokenRoute?: string;Same-origin token route the merchant mounted (defaults to DEFAULT_TOKEN_ROUTE).
DataCapabilities
Properties
appleWalletPass
appleWalletPass: boolean;freeGiftStock
freeGiftStock: boolean;googleWalletPass
googleWalletPass: boolean;joinProgram
joinProgram: boolean;profileEdit
profileEdit: boolean;receivedRewards
receivedRewards: boolean;referralHistory
referralHistory: boolean;referralInvite
referralInvite: boolean;socialConnect
socialConnect: boolean;HeadlessDataPort
Extends
CoreDataPort
Properties
capabilities
capabilities: DataCapabilities;Methods
checkSegmentPrograms()
checkSegmentPrograms(segmentPrograms): Promise<SegmentEligibility>;POST /customer/segment-program — Shopify-segment membership for the spending programs gated on it, so a reward the shopper cannot redeem is never rendered with a Redeem button.
Parameters
| Parameter | Type |
|---|---|
segmentPrograms | SegmentProgramQuery[] |
Returns
Promise<SegmentEligibility>
claimBirthdayReward()
claimBirthdayReward(birthdayRewards?): Promise<BirthdayClaimResult>;POST /customer/birthday/claim — the ANNUAL birthday reward, for a program
on MANUAL delivery (authed; parity _handleClaimBirthdayFromEarn). The
reward is minted asynchronously, so a resolved promise means ACCEPTED, not
that a coupon exists.
Parameters
| Parameter | Type |
|---|---|
birthdayRewards? | BirthdayRewardsMap |
Returns
Promise<BirthdayClaimResult>
claimMilestone()
claimMilestone(input): Promise<MilestoneClaimResult>;POST /customer/milestone/claim — claim a REACHED milestone step's reward
(authed; parity Liquid handleMilestoneClaim → /popup/customer-milestone/claim).
The reward is resolved SERVER-SIDE from the program; this carries the
shopper's SELECTIONS only, never reward definitions.
Parameters
| Parameter | Type |
|---|---|
input | MilestoneClaimInput |
Returns
Promise<MilestoneClaimResult>
claimPendingReward()
claimPendingReward(pendingId, input?): Promise<PendingRewardClaimResult>;POST /customer/pending-rewards/{pendingId}/claim — claim an ENTRY-pending
tier reward, minting the coupon now (authed; parity Liquid
handleTierPerkVariantSave → /pending-rewards/:id/claim). IDOR-safe:
pendingId scopes to this customer server-side.
Parameters
| Parameter | Type |
|---|---|
pendingId | string |
input? | { variantIds?: string[]; } |
input.variantIds? | string[] |
Returns
Promise<PendingRewardClaimResult>
deleteAddress()
deleteAddress(addressId): Promise<AddressDeleteResult>;POST /customer/addresses/delete — delete a shipping address (authed; parity _handleAddressDelete).
Parameters
| Parameter | Type |
|---|---|
addressId | string | number |
Returns
Promise<AddressDeleteResult>
disconnectFacebook()
disconnectFacebook(): Promise<FacebookDisconnectResult>;POST /customer/social/facebook/disconnect — clear the current customer's Facebook link (authed).
Returns
Promise<FacebookDisconnectResult>
earn()
earn(req): Promise<EarnResult>;Parameters
| Parameter | Type |
|---|---|
req | EarnRequest |
Returns
Promise<EarnResult>
Inherited from
CoreDataPort.earn
earnSocial()
earnSocial(programId): Promise<SocialEarnResult>;Parameters
| Parameter | Type |
|---|---|
programId | string |
Returns
Promise<SocialEarnResult>
Inherited from
CoreDataPort.earnSocial
earnUpload()
earnUpload(input): Promise<EarnUploadResult>;Parameters
| Parameter | Type |
|---|---|
input | { images: EarnImageUpload[]; } |
input.images | EarnImageUpload[] |
Returns
Promise<EarnUploadResult>
Inherited from
CoreDataPort.earnUpload
generateQrCode()
generateQrCode(): Promise<QrCodeResult>;POST /customer/qrcode — this customer's in-store scan code as a PNG data URL (authed; parity _handleGenerateQr).
Returns
Promise<QrCodeResult>
generateReferralLink()
generateReferralLink(email): Promise<GenerateReferralLinkResult>;POST /referral/generate-link — mint (or fetch) a shareable referral link for
email. PUBLIC (no JWT; shop resolved by ?shop=), so a guest can get a link
before joining. Parity with Liquid's /referral/generateLinkReferral
(_handleGuestReferralLink).
Parameters
| Parameter | Type |
|---|---|
email | string |
Returns
Promise<GenerateReferralLinkResult>
getActivities()
getActivities(query?): Promise<ActivityPage>;Parameters
| Parameter | Type |
|---|---|
query? | ActivityQuery |
Returns
Promise<ActivityPage>
getAddresses()
getAddresses(): Promise<Address[]>;GET /customer/addresses — the customer's saved shipping addresses (authed only).
Returns
Promise<Address[]>
getAppleWalletLink()
getAppleWalletLink(): Promise<string>;POST /customer/wallet-pass/apple — create (or regenerate) this customer's
Apple Wallet pass, resolving its QR data URL (authed; parity
handleGetAppleWalletLink). The full {url, qrUrl} result is collapsed to
just qrUrl here — the only half either surface (Liquid or headless) ever
shows the shopper.
Returns
Promise<string>
getAppleWalletPassCache()
getAppleWalletPassCache(): AppleWalletPassCache;Local-only, synchronous (no network): the wallet-pass click handler's cache
of the customer's own createdApplePass/qrCodeDownloadApplePass fields,
so a repeat click can skip straight to verifyApplePass + reuse the
QR instead of re-minting a pass. Mirrors the Liquid host's own customer
store (its getAppleWalletPassCache); this adapter has
no persistent "current customer" of its own, so the snapshot only reflects
initialData.customer at construction plus whatever a later
setAppleWalletPassCache call layers on top — not a live beat-2 refresh.
Returns
AppleWalletPassCache
getCustomer()
getCustomer(): Promise<Customer>;Returns
Promise<Customer>
Inherited from
CoreDataPort.getCustomer
getFreeGiftStock()
getFreeGiftStock(programId): Promise<FreeGiftStock>;POST /customer/free-gift-stock — live gift stock for a free_product
program, fetched on demand when a gift modal opens (parity with Liquid's
loadFreeGiftStock). Rejects when no live source backs it (SSR-only adapter).
Parameters
| Parameter | Type |
|---|---|
programId | string |
Returns
Promise<FreeGiftStock>
getGoogleWalletLink()
getGoogleWalletLink(): Promise<string>;GET /customer/wallet-pass/google — this customer's "Add to Google Wallet" save link (authed; parity handleGetGoogleWalletLink).
Returns
Promise<string>
getImpactHistory()
getImpactHistory(params?): Promise<ImpactHistory>;GET /customer/impact-history — GoodAPI environmental-impact totals + redemption history (authed; parity /impact-history).
Parameters
| Parameter | Type |
|---|---|
params? | GetImpactHistoryParams |
Returns
Promise<ImpactHistory>
getInfo()
getInfo(params?): Promise<JoyInfo>;GET /info — beat 2. Optional-auth: a guest gets the shop-level payload, an authed client the RICH customer too. Rejects when no live source backs it (SSR-only adapter) — the orchestrator then keeps beat 1.
Parameters
| Parameter | Type |
|---|---|
params? | GetInfoOptions |
Returns
Promise<JoyInfo>
getLineAuthUrl()
getLineAuthUrl(): Promise<LineAuthUrlResult>;POST /customer/social/line/auth-url — mint a LINE Login URL to open in a popup (authed; parity handleLineAuth).
Returns
Promise<LineAuthUrlResult>
getMilestoneProgress()
getMilestoneProgress(): Promise<MilestoneProgress>;GET /customer/milestone — flat {typeMilestone: progress} map across active milestone programs (authed; parity /customer-milestone).
Returns
Promise<MilestoneProgress>
getOrderActivities()
getOrderActivities(orderId): Promise<Activity[]>;GET /customer/activities-by-order?orderId= — Joy point activities for one order (authed; parity /activities-by-order).
Parameters
| Parameter | Type |
|---|---|
orderId | string |
Returns
Promise<Activity[]>
getOrderById()
getOrderById(orderId): Promise<Order | null>;GET /customer/orders?orderId= — a single order, or null when not found (authed; parity /orders?orderId=).
Parameters
| Parameter | Type |
|---|---|
orderId | string |
Returns
Promise<Order | null>
getOrders()
getOrders(): Promise<Order[]>;GET /customer/orders — this customer's orders list (authed; parity /orders).
Returns
Promise<Order[]>
getPendingTierRewardClaims()
getPendingTierRewardClaims(): Promise<PendingTierRewardClaim[]>;GET /customer/pending-rewards — this customer's unclaimed tier-up rewards (authed; parity /pending-rewards).
Returns
Promise<PendingTierRewardClaim[]>
getProductByHandle()
getProductByHandle(handle): Promise<CurrentProduct | null>;Fetch one storefront product by handle for the recently-viewed refresh loop and the recommended
loader. Backed directly by the /api/joy-products resource route (Mode
A) — this is public storefront catalog data, not Joy backend data, so it
bypasses JoyDataSource entirely (no SSR-only rejection). Resolves
null on ANY failure (network error, non-2xx, route not mounted, handle
missing from the response) — never throws; the core's recently-viewed
section depends on that to hide gracefully.
Parameters
| Parameter | Type |
|---|---|
handle | string |
Returns
Promise<CurrentProduct | null>
Overrides
CoreDataPort.getProductByHandle
getPrograms()
getPrograms(): Promise<Program[]>;Returns
Promise<Program[]>
Inherited from
CoreDataPort.getPrograms
getPromotedCollections()
getPromotedCollections(selections): Promise<PromotedCollection[]>;Live title + image for the merchant-curated promoted-collections
strip, from the same resource route (Mode C). Public catalog data, so it
bypasses JoyDataSource for the same reason as
HeadlessDataPort.getProductByHandle. Resolves [] on ANY failure
— never throws.
Parameters
| Parameter | Type |
|---|---|
selections | PromotedCollectionSelection[] |
Returns
Promise<PromotedCollection[]>
getReceivedRewards()
getReceivedRewards(params?): Promise<ReceivedRewardsPage>;GET /customer/received-rewards — the gifts FRIENDS sent this customer
("From friends"), one cursor page (authed; parity /popup/received-rewards).
A separate list from getRewards: these are NOT this customer's own
redemptions, so the widget must not offer revoke or send-to-a-friend on them.
Parameters
| Parameter | Type |
|---|---|
params? | { after?: string; before?: string; limit?: number; } |
params.after? | string |
params.before? | string |
params.limit? | number |
Returns
Promise<ReceivedRewardsPage>
getRecentlyViewedProducts()
getRecentlyViewedProducts(): Promise<RecentlyViewedProduct[]>;Persisted "recently viewed" carousel entries — localStorage['joy-recently-viewed'], the same key the Liquid storefront widget reads/writes.
Returns
Promise<RecentlyViewedProduct[]>
Overrides
CoreDataPort.getRecentlyViewedProducts
getReferral()
getReferral(): Promise<Referral>;Returns
Promise<Referral>
Inherited from
CoreDataPort.getReferral
getReferralHistory()
getReferralHistory(opts?): Promise<ReferralHistoryPage>;Parameters
| Parameter | Type |
|---|---|
opts? | ReferralQuery |
Returns
Promise<ReferralHistoryPage>
Inherited from
CoreDataPort.getReferralHistory
getRewards()
getRewards(params?): Promise<CustomerRewards & object>;pagination describes the redeemed list only and is
optional here — not every JoyDataSource is guaranteed to carry it — so
callers (the orchestrator's loadRewards) read it defensively (?.).
params.received is the Liquid core's way of asking for the "From friends"
gifts through this same call; it delegates to getReceivedRewards and
the gifts come back in their OWN received slot — never in redeemed,
which would let a caller offer revoke/send-to-a-friend on someone else's gift.
Parameters
| Parameter | Type |
|---|---|
params? | RewardQuery |
Returns
Promise<CustomerRewards & object>
getShopConfig()
getShopConfig(): Promise<ShopConfig>;Returns
Promise<ShopConfig>
Inherited from
CoreDataPort.getShopConfig
getStoreCreditTransactions()
getStoreCreditTransactions(params?): Promise<StoreCreditTransactionPage>;GET /customer/store-credit/transactions — this customer's SC history, one page (authed; account resolved server-side, no accountId param — IDOR fix).
Parameters
| Parameter | Type |
|---|---|
params? | GetStoreCreditTransactionsParams |
Returns
Promise<StoreCreditTransactionPage>
getTierRewards()
getTierRewards(): Promise<Tier[]>;GET /customer/tier-rewards — every VIP tier with its rewards (authed; parity /tierRewards).
Returns
Promise<Tier[]>
getTiers()
getTiers(): Promise<Tier[]>;Returns
Promise<Tier[]>
Inherited from
CoreDataPort.getTiers
joinProgram()
joinProgram(joinFrom?): Promise<Customer>;POST /customer/join-program — self-enrol an opt-in guest (authed; parity _handleOptInJoin).
Parameters
| Parameter | Type |
|---|---|
joinFrom? | JoinFrom |
Returns
Promise<Customer>
linkInstagram()
linkInstagram(instagramUsername): Promise<InstagramLinkResult>;POST /customer/social/instagram/link — link a self-reported IG username, grants the one-time reward on first link (authed; parity _handleInstagramLinkFromEarn).
Parameters
| Parameter | Type |
|---|---|
instagramUsername | string |
Returns
Promise<InstagramLinkResult>
redeem()
redeem(programId, opts?): Promise<RedeemResult>;Adds the caller-generated idempotencyKey (see RedeemOptions).
Parameters
| Parameter | Type |
|---|---|
programId | string |
opts? | RedeemOptions |
Returns
Promise<RedeemResult>
Overrides
CoreDataPort.redeem
saveAddress()
saveAddress(address): Promise<Address>;POST /customer/addresses — create a new shipping address (authed; parity _handleAddressSave).
Parameters
| Parameter | Type |
|---|---|
address | AddressInput |
Returns
Promise<Address>
saveBirthday()
saveBirthday(birthday, dateOfBirth?): Promise<BirthdaySaveResult>;POST /customer/birthday — save the customer's birthday date ONCE from the
profile screen (authed; same as the birthday post of the Liquid widget's
profile save). Once-per-lifetime: a re-save rejects
ALREADY_SUBMITTED. Distinct from HeadlessDataPort.setBirthdayRewards
(which reward) and the birthday EARNING claim reached via HeadlessDataPort.earn.
Parameters
| Parameter | Type |
|---|---|
birthday | string |
dateOfBirth? | string |
Returns
Promise<BirthdaySaveResult>
saveRecentlyViewedProducts()
saveRecentlyViewedProducts(items): Promise<void>;Parameters
| Parameter | Type |
|---|---|
items | RecentlyViewedProduct[] |
Returns
Promise<void>
Inherited from
CoreDataPort.saveRecentlyViewedProducts
saveTierPerkVariantSelection()
saveTierPerkVariantSelection(input): Promise<TierPerkSaveResult>;POST /customer/perk/save-variant-selection — persist a tier-PRIVILEGE perk's
variant selection (authed; parity Liquid handleTierPerkVariantSave →
/perk/save-variant-selection). The product-discount Rust function applies
it at checkout, so the server re-resolves the perk's allowed variants; this
carries the shopper's SELECTIONS only, never the reward definition.
Parameters
| Parameter | Type |
|---|---|
input | TierPerkSaveInput |
Returns
Promise<TierPerkSaveResult>
sendReferralEmail()
sendReferralEmail(refereeEmail): Promise<ReferralEmailResult>;POST /customer/referral/send-email — invite a friend by email (automated-sharing mode; authed; parity _handleSendReferralEmail).
Parameters
| Parameter | Type |
|---|---|
refereeEmail | string |
Returns
Promise<ReferralEmailResult>
sendRewardToFriend()
sendRewardToFriend(input): Promise<SendRewardResult>;POST /customer/send-reward-to-friend — gift a coupon THIS customer redeemed to a friend (authed; parity sendRewardToFriend).
Parameters
| Parameter | Type |
|---|---|
input | SendRewardInput |
Returns
Promise<SendRewardResult>
setAppleWalletPassCache()
setAppleWalletPassCache(qrUrl): void;Optimistically record that a pass now exists, right after getAppleWalletLink resolves a fresh QR.
Parameters
| Parameter | Type |
|---|---|
qrUrl | string |
Returns
void
setBirthdayRewards()
setBirthdayRewards(birthdayRewards): Promise<BirthdayRewardsResult>;POST /customer/birthday-rewards — save WHICH birthday reward the shopper
picked, on its own (authed; parity _handleSaveBirthdayRewardsFromEarn).
Claims nothing. Separate from the birthday SAVE that rides HeadlessDataPort.earn, because re-picking stays repeatable while the date
is once-per-lifetime.
Parameters
| Parameter | Type |
|---|---|
birthdayRewards | BirthdayRewardsMap |
Returns
Promise<BirthdayRewardsResult>
updateProfile()
updateProfile(options): Promise<ProfileResult>;POST /customer/profile — update customer profile (firstName, lastName, phone, avatarBase64; authed; parity _handleProfileSave).
Parameters
| Parameter | Type |
|---|---|
options | UpdateProfileOptions |
Returns
Promise<ProfileResult>
verifyApplePass()
verifyApplePass(): Promise<boolean>;GET /customer/wallet-pass/apple/verify — whether a previously-created Apple Wallet pass still exists (authed; parity handleVerifyApplePass).
Returns
Promise<boolean>
HeadlessHostAdapter
Properties
auth
auth: AuthPort;data
data: HeadlessDataPort;initialData
readonly initialData: JoyInitialData | null;The server-serialized payload, or null.
Methods
context()
context(): HeadlessHostContext;Returns
getToken()
getToken(): Promise<string | null>;Returns
Promise<string | null>
navigate()
navigate(target): void;Parameters
| Parameter | Type |
|---|---|
target | NavTarget |
Returns
void
notifyAuth()
notifyAuth(state): void;Internal seam, not part of the generic HostAdapter contract: call after
a browser-side auth mutation (login/logout token exchange) to push the
new state to auth.subscribe listeners — getState() alone can't do
that on its own. Intended caller: the browser login/logout wiring.
Parameters
| Parameter | Type |
|---|---|
state | AuthState |
Returns
void
HeadlessHostAdapterOptions
Properties
context
context: HeadlessHostContextInput;getToken?
getToken?: () => Promise<string | null>;Resolve a customer JWT (browser fetch of the merchant /joy-token route).
Returns
Promise<string | null>
initialData?
initialData?: JoyInitialData | null;Server-serialized data.
productsRoute?
productsRoute?: string;Same-origin resource route the merchant mounted for storefront product reads (defaults to DEFAULT_PRODUCTS_ROUTE).
source?
source?: JoyDataSource;Live source for operations initialData does not carry.
HeadlessHostContext
Read-only snapshot the core reads instead of window.AVADA_JOY. Hydrogen
owns the URL, so it knows route and account details first-hand.
Properties
accountUrl
accountUrl: string;activeMarketCurrency?
activeMarketCurrency?: string;Liquid active-market currency without shop or USD fallback. Not available on headless hosts yet.
apiUrl
apiUrl: string;Base URL of the Headless API (merchant env JOY_API_URL).
contentLocale?
contentLocale?: string;Joy content locale preserves the legacy empty-string fallback. Not available on headless hosts yet.
country
country: string;currency
currency: string;currencyRate?
currencyRate?: number;Liquid active-market currency conversion rate. Not available on headless hosts yet.
currentProduct?
currentProduct?: CurrentProduct;customerProfile?
customerProfile?: object;Synchronous Liquid customer fields used during initial rendering. Not available on headless hosts yet.
addresses?
addresses?: unknown[];avatarUrl?
avatarUrl?: string;first_name?
first_name?: string;last_name?
last_name?: string;orders?
orders?: unknown[];orders_count?
orders_count?: number;phone?
phone?: string;customerTierId?
customerTierId?: string;Liquid customer tier identity backs tier-aware referral rates. Not available on headless hosts yet.
debug?
debug?: boolean;Liquid diagnostic flag; distinct from preview mode. Not available on headless hosts yet.
demoMode?
demoMode?: boolean;locale?
locale?: string;Joy-normalised locale for this request (Hydrogen storefront.i18n).
loginUrl
loginUrl: string;loyaltyPageUrl
loyaltyPageUrl: string;moneyFormat?
moneyFormat?: string;ordersCustomerId?
ordersCustomerId?: string;The legacy orders API requires the bare Shopify session customer id. Not available on headless hosts yet.
page
page: object;Route-derived page info — Hydrogen knows this from its router.
handle
handle: string;resourceId
resourceId: string;type
type: string;preview?
preview?: boolean;registerUrl
registerUrl: string;routesRoot
routesRoot: string;Locale-aware root URL (Hydrogen routes.root).
shopDomain
shopDomain: string;shopId?
shopId?: string;shopifyCustomerId?
shopifyCustomerId?: string;Shopify session identity. Not available on headless hosts yet.
translation
translation: Record<string, string>;Locale-keyed [[WidgetV4]] label overrides for the widget UI.
The CDN locale bundle is not available on headless hosts yet — callers may omit this on HeadlessHostAdapterOptions
(see HeadlessHostContextInput) and it defaults to {}, so every
web component falls back to its built-in English default.
viewport
viewport: object;Real DOM viewport width; caller-supplied. {width: 0} before hydration / on SSR.
width
width: number;JoyDataSource
The subset of the DataPort that the browser Joy client can honestly service. Shop config and tiers remain optional because they are SSR/caller supplied.
Properties
getAddresses?
getAddresses?: () => Promise<Address[]>;Optional — only the browser client services addresses; absent on SSR-only sources.
Returns
Promise<Address[]>
getInfo?
getInfo?: (params?) => Promise<JoyInfo>;Optional — only the browser source (with a shopDomain-bearing client) can service /info.
Parameters
| Parameter | Type |
|---|---|
params? | GetInfoOptions |
Returns
Promise<JoyInfo>
getShopConfig?
getShopConfig?: () => Promise<ShopConfig>;Returns
Promise<ShopConfig>
getTiers?
getTiers?: () => Promise<Tier[]>;Returns
Promise<Tier[]>
Methods
checkSegmentPrograms()
checkSegmentPrograms(segmentPrograms): Promise<SegmentEligibility>;POST /customer/segment-program — Shopify-segment membership for the spending programs gated on it, so a reward the shopper cannot redeem is never rendered with a Redeem button.
Parameters
| Parameter | Type |
|---|---|
segmentPrograms | SegmentProgramQuery[] |
Returns
Promise<SegmentEligibility>
claimBirthdayReward()
claimBirthdayReward(birthdayRewards?): Promise<BirthdayClaimResult>;Parameters
| Parameter | Type |
|---|---|
birthdayRewards? | BirthdayRewardsMap |
Returns
Promise<BirthdayClaimResult>
claimMilestone()
claimMilestone(input): Promise<MilestoneClaimResult>;Parameters
| Parameter | Type |
|---|---|
input | MilestoneClaimInput |
Returns
Promise<MilestoneClaimResult>
claimPendingReward()
claimPendingReward(pendingId, input?): Promise<PendingRewardClaimResult>;Parameters
| Parameter | Type |
|---|---|
pendingId | string |
input? | { variantIds?: string[]; } |
input.variantIds? | string[] |
Returns
Promise<PendingRewardClaimResult>
deleteAddress()
deleteAddress(addressId): Promise<AddressDeleteResult>;Parameters
| Parameter | Type |
|---|---|
addressId | string | number |
Returns
Promise<AddressDeleteResult>
disconnectFacebook()
disconnectFacebook(): Promise<FacebookDisconnectResult>;Returns
Promise<FacebookDisconnectResult>
earn()
earn(programId, context?): Promise<EarnResult>;Parameters
| Parameter | Type |
|---|---|
programId | string |
context? | EarnContext |
Returns
Promise<EarnResult>
earnSocial()
earnSocial(programId): Promise<SocialEarnResult>;Parameters
| Parameter | Type |
|---|---|
programId | string |
Returns
Promise<SocialEarnResult>
earnUpload()
earnUpload(input): Promise<EarnUploadResult>;Parameters
| Parameter | Type |
|---|---|
input | { images: EarnImageUpload[]; } |
input.images | EarnImageUpload[] |
Returns
Promise<EarnUploadResult>
generateQrCode()
generateQrCode(): Promise<QrCodeResult>;Returns
Promise<QrCodeResult>
generateReferralLink()
generateReferralLink(email): Promise<GenerateReferralLinkResult>;Parameters
| Parameter | Type |
|---|---|
email | string |
Returns
Promise<GenerateReferralLinkResult>
getActivities()
getActivities(query?): Promise<ActivityPage>;Parameters
| Parameter | Type |
|---|---|
query? | { after?: string; before?: string; limit?: number; } |
query.after? | string |
query.before? | string |
query.limit? | number |
Returns
Promise<ActivityPage>
getAppleWalletLink()
getAppleWalletLink(): Promise<string>;Returns
Promise<string>
getCustomer()
getCustomer(): Promise<Customer>;Returns
Promise<Customer>
getFreeGiftStock()
getFreeGiftStock(programId, country?): Promise<FreeGiftStock>;POST /customer/free-gift-stock — live gift stock for a free_product program.
country (2-letter, injected by the host adapter from
HeadlessHostContext.country) lets the server filter by Storefront
market availability; optional so a source that ignores it still conforms.
Parameters
| Parameter | Type |
|---|---|
programId | string |
country? | string |
Returns
Promise<FreeGiftStock>
getGoogleWalletLink()
getGoogleWalletLink(): Promise<string>;Returns
Promise<string>
getImpactHistory()
getImpactHistory(params?): Promise<ImpactHistory>;Parameters
| Parameter | Type |
|---|---|
params? | GetImpactHistoryParams |
Returns
Promise<ImpactHistory>
getLineAuthUrl()
getLineAuthUrl(): Promise<LineAuthUrlResult>;Returns
Promise<LineAuthUrlResult>
getMilestoneProgress()
getMilestoneProgress(): Promise<MilestoneProgress>;Returns
Promise<MilestoneProgress>
getOrderActivities()
getOrderActivities(orderId): Promise<Activity[]>;Parameters
| Parameter | Type |
|---|---|
orderId | string |
Returns
Promise<Activity[]>
getOrderById()
getOrderById(orderId): Promise<Order | null>;Parameters
| Parameter | Type |
|---|---|
orderId | string |
Returns
Promise<Order | null>
getOrders()
getOrders(): Promise<Order[]>;Returns
Promise<Order[]>
getPendingTierRewardClaims()
getPendingTierRewardClaims(): Promise<PendingTierRewardClaim[]>;Returns
Promise<PendingTierRewardClaim[]>
getPrograms()
getPrograms(): Promise<Program[]>;Returns
Promise<Program[]>
getReceivedRewards()
getReceivedRewards(params?): Promise<ReceivedRewardsPage>;GET /customer/received-rewards — one page of the gifts friends sent this customer.
Parameters
| Parameter | Type |
|---|---|
params? | { after?: string; before?: string; limit?: number; } |
params.after? | string |
params.before? | string |
params.limit? | number |
Returns
Promise<ReceivedRewardsPage>
getReferral()
getReferral(): Promise<Referral>;Returns
Promise<Referral>
getReferralHistory()
getReferralHistory(params?): Promise<ReferralHistoryPage>;Parameters
| Parameter | Type |
|---|---|
params? | { after?: string; before?: string; } |
params.after? | string |
params.before? | string |
Returns
Promise<ReferralHistoryPage>
getRewards()
getRewards(params?): Promise<CustomerRewardsPage>;Parameters
| Parameter | Type |
|---|---|
params? | { after?: string; before?: string; couponStatus?: "available" | "unavailable"; limit?: number; } |
params.after? | string |
params.before? | string |
params.couponStatus? | "available" | "unavailable" |
params.limit? | number |
Returns
Promise<CustomerRewardsPage>
getStoreCreditTransactions()
getStoreCreditTransactions(params?): Promise<StoreCreditTransactionPage>;Parameters
| Parameter | Type |
|---|---|
params? | GetStoreCreditTransactionsParams |
Returns
Promise<StoreCreditTransactionPage>
getTierRewards()
getTierRewards(): Promise<Tier[]>;Returns
Promise<Tier[]>
joinProgram()
joinProgram(joinFrom?): Promise<Customer>;Parameters
| Parameter | Type |
|---|---|
joinFrom? | JoinFrom |
Returns
Promise<Customer>
linkInstagram()
linkInstagram(instagramUsername): Promise<InstagramLinkResult>;Parameters
| Parameter | Type |
|---|---|
instagramUsername | string |
Returns
Promise<InstagramLinkResult>
redeem()
redeem(programId, opts?): Promise<RedeemResult>;Parameters
| Parameter | Type |
|---|---|
programId | string |
opts? | RedeemOptions |
Returns
Promise<RedeemResult>
saveAddress()
saveAddress(address): Promise<Address>;Parameters
| Parameter | Type |
|---|---|
address | AddressInput |
Returns
Promise<Address>
saveBirthday()
saveBirthday(birthday, dateOfBirth?): Promise<BirthdaySaveResult>;Parameters
| Parameter | Type |
|---|---|
birthday | string |
dateOfBirth? | string |
Returns
Promise<BirthdaySaveResult>
saveTierPerkVariantSelection()
saveTierPerkVariantSelection(input): Promise<TierPerkSaveResult>;Parameters
| Parameter | Type |
|---|---|
input | TierPerkSaveInput |
Returns
Promise<TierPerkSaveResult>
sendReferralEmail()
sendReferralEmail(refereeEmail): Promise<ReferralEmailResult>;Parameters
| Parameter | Type |
|---|---|
refereeEmail | string |
Returns
Promise<ReferralEmailResult>
sendRewardToFriend()
sendRewardToFriend(input): Promise<SendRewardResult>;Parameters
| Parameter | Type |
|---|---|
input | SendRewardInput |
Returns
Promise<SendRewardResult>
setBirthdayRewards()
setBirthdayRewards(birthdayRewards): Promise<BirthdayRewardsResult>;Parameters
| Parameter | Type |
|---|---|
birthdayRewards | BirthdayRewardsMap |
Returns
Promise<BirthdayRewardsResult>
updateProfile()
updateProfile(options): Promise<ProfileResult>;Parameters
| Parameter | Type |
|---|---|
options | UpdateProfileOptions |
Returns
Promise<ProfileResult>
verifyApplePass()
verifyApplePass(): Promise<boolean>;Returns
Promise<boolean>
JoyInitialData
Data resolved server-side and serialized into the HTML payload.
Properties
customer?
customer?: Customer;programs?
programs?: Program[];shopConfig?
shopConfig?: ShopConfig;tiers?
tiers?: Tier[];JoyLoyaltyPageInitialData
The slice of getJoyInitialData's result the page seeds from — structural,
so JoyInitialDataResult (server) and HeadlessInitialData (widget) both fit
without this client file importing either.
Properties
customer?
customer?:
| {
points?: number | null;
tier?: | {
id?: string | null;
name?: string | null;
}
| null;
}
| null;shopifyCustomer?
shopifyCustomer?:
| {
email?: string | null;
firstName?: string | null;
}
| null;JoyLoyaltyPageProps
Properties
apiUrl
apiUrl: string;Base URL of the Headless API (JOY_API_URL).
assetUrl?
assetUrl?: string;Override the widget-core CDN URL (JOY_WIDGET_ASSET_URL).
cart?
cart?:
| StorefrontCart
| (() => StorefrontCart | null | undefined);The storefront cart (or a getter for it) — see <JoyWidget/>'s identical prop for the same reasoning.
cartFetcher?
cartFetcher?: HydrogenCartFetcher;React Router's useFetcher() result. Required together with JoyLoyaltyPageProps.cartRevalidate to enable the redeem dialog's cart-total read.
cartRevalidate?
cartRevalidate?: () => void;React Router's useRevalidator().revalidate. Pairs with JoyLoyaltyPageProps.cartFetcher.
Returns
void
cartRoute?
cartRoute?: string;Locale-aware cart action route (e.g. /fr/cart). Defaults to /cart.
data
data: JoyLoyaltyPageData;SSR-safe server data from getJoyLoyaltyPageData — carries NO customer field (D2, see file header).
initialData?
initialData?: JoyLoyaltyPageInitialData | null;The ROOT loader's getJoyInitialData result — the same value <JoyWidget/>
takes as its initialData. Read client-side only, to seed the page's
customer for first paint (buildInitialLoyaltyPageCustomer); it
never reaches this component's server HTML, so D2 holds (the root loader is
already per-request and per-session — this component's own loader still
carries no customer).
onCartUpdated?
onCartUpdated?: (cart) => void;Called with the cart each of this page's cart mutations returns — wire it
to the host's cart store so the header count and drawer update without a
navigation (a joy:cart-updated window event carries the same cart).
Parameters
| Parameter | Type |
|---|---|
cart | StorefrontCart |
Returns
void
onNavigate?
onNavigate?: (url) => void;Client-side navigation (React Router's useNavigate()) for same-tab,
same-origin joy-host-navigate requests — e.g. free shipping's
"Continue shopping". Omitted → a full page load.
Parameters
| Parameter | Type |
|---|---|
url | string |
Returns
void
onOpenCartDrawer?
onOpenCartDrawer?: () => void;Opens the host's cart drawer — the open_cart_drawer apply behavior. The
page closes its own modal first, as Liquid does. Omitted → the shopper stays put.
Returns
void
sectionId?
sectionId?: string;Render exactly one section instead of the complete page.
shopDomain
shopDomain: string;The shop's myshopify domain.
tokenRoute?
tokenRoute?: string;Same-origin token route the merchant mounted (defaults to /api/joy-token, lib/token.ts).
JoyPointsCalculatorProps
Properties
align?
align?: "left" | "center" | "right";apiUrl
apiUrl: string;Base URL of the Headless API (JOY_API_URL) — the member client for "Join Program".
assetUrl?
assetUrl?: string;Override the widget-core CDN URL (JOY_WIDGET_ASSET_URL).
cart?
cart?:
| StorefrontCart
| (() => StorefrontCart | null | undefined);context="cart": the storefront cart (or a getter for it); falls back to the <JoyProvider> cart.
className?
className?: string;context
context: "cart" | "product";Where the block lives. Explicit, never inferred; anything else collapses the block with one warn.
customerTags?
customerTags?: string[];The logged-in customer's tags (Customer Account API customer.tags, JoyPointsCustomer fragment).
initialData
initialData:
| JoyInitialDataResult
| null
| undefined;The root loader's getJoyInitialData() result — the same value <JoyWidget initialData>
takes. Supplies the blob (programs, point-calculator config, translation), customer,
login_url, locale and the core manifest.
isB2B?
isB2B?: boolean;The logged-in customer has a company contact (B2B) — toJoyPointsCustomerInput(...).isB2B.
isLoggedIn?
isLoggedIn?: boolean;await customerAccount.isLoggedIn(). Pass it for guests too (as false): it is what tells a
logged-in shopper whose Joy token could not be minted apart from a guest.
loginUrl?
loginUrl?: string;Fallback guest "Sign in" target: the merchant's callActionLink wins, then this, then initialData.login_url.
onJoinClick?
onJoinClick?: (action) => boolean | void;Called before a "Join" click is handled; return true to take over (nothing else runs).
Parameters
| Parameter | Type |
|---|---|
action | { href: string; kind: "login" | "open_widget" | "join_program"; } |
action.href | string |
action.kind | "login" | "open_widget" | "join_program" |
Returns
boolean | void
onNavigate?
onNavigate?: (url) => void;Client-side navigation (React Router's useNavigate()); omitted → a full page load.
Parameters
| Parameter | Type |
|---|---|
url | string |
Returns
void
product?
product?: PointsStorefrontProduct | null;context="product": the Storefront product (JoyPointsProduct fragment).
quantity?
quantity?: number;context="product": the quantity picked on the page. Defaults to 1.
selectedVariant?
selectedVariant?: PointsStorefrontVariant | null;context="product": the selected variant (JoyPointsVariant fragment).
sellingPlanId?
sellingPlanId?: string | null;context="product": the selected selling plan (GID); none → one-time purchase.
shopDomain
shopDomain: string;The shop's myshopify domain.
tokenRoute?
tokenRoute?: string;Same-origin token route the merchant mounted (defaults to /api/joy-token).
JoyRedeemCartProps
Properties
apiUrl
apiUrl: string;Base URL of the Headless API (JOY_API_URL).
assetUrl?
assetUrl?: string;Override the widget-core CDN URL (JOY_WIDGET_ASSET_URL).
cart?
cart?:
| StorefrontCart
| (() => StorefrontCart | null | undefined);The storefront cart (or a getter for it). Read even without an adapter: it feeds eligibility and the dynamic cap.
cartFetcher?
cartFetcher?: HydrogenCartFetcher;useFetcher({key: 'joy-redeem-cart'}). Required together with JoyRedeemCartProps.cartRevalidate to apply codes to the cart.
cartRevalidate?
cartRevalidate?: () => void;useRevalidator().revalidate. Pairs with JoyRedeemCartProps.cartFetcher.
Returns
void
cartRoute?
cartRoute?: string;Locale-aware cart action route (e.g. /fr/cart). Defaults to /cart.
className?
className?: string;initialData
initialData:
| JoyInitialDataResult
| null
| undefined;The root loader's getJoyInitialData() result — the same value <JoyWidget initialData>
takes. Supplies the blob (programs, redeem-in-cart config, translation), customer,
login_url, locale and the core manifest.
loginUrl?
loginUrl?: string;Overrides initialData.login_url (the guest "Sign in" target).
onCartUpdated?
onCartUpdated?: (cart) => void;Called with the cart each of this block's cart mutations returns.
Parameters
| Parameter | Type |
|---|---|
cart | StorefrontCart |
Returns
void
onNavigate?
onNavigate?: (url) => void;Client-side navigation for "Sign in" (React Router's useNavigate()); omitted → a full page load.
Parameters
| Parameter | Type |
|---|---|
url | string |
Returns
void
shopDomain
shopDomain: string;The shop's myshopify domain.
tokenRoute?
tokenRoute?: string;Same-origin token route the merchant mounted (defaults to /api/joy-token).
JoyWidgetProps
Properties
accentColor?
accentColor?: string;Overrides the theme primary color for the launcher.
apiUrl?
apiUrl?: string | null;Base URL of the Headless API (merchant env JOY_API_URL). null disables the balance.
assetUrl?
assetUrl?: string;Override the widget-core CDN URL (JOY_WIDGET_ASSET_URL). Reserved: not
read by the core loader yet; accepted now so the contract is stable.
cart?
cart?:
| StorefrontCart
| (() => StorefrontCart | null | undefined);The storefront cart (or a getter for it) — the context.cart / cart-store
value the app already has. Powers the post-redeem auto-apply + add-to-cart
OPTIONAL: absent → the cart port's getCart returns null and
cart actions degrade to cart-unavailable, exactly as today.
cartFetcher?
cartFetcher?: HydrogenCartFetcher;React Router's useFetcher() result, from the app that renders <JoyWidget/>
inside its Router. @joy-loyalty/hydrogen cannot own this hook (it must match the
app's react-router version), so the app calls it and passes it down. Required
together with JoyWidgetProps.cartRevalidate to enable cart mutations.
cartRevalidate?
cartRevalidate?: () => void;React Router's useRevalidator().revalidate, from the app. Pairs with JoyWidgetProps.cartFetcher.
Returns
void
cartRoute?
cartRoute?: string;Locale-aware cart action route (e.g. /fr/cart). Defaults to /cart.
country?
country?: string;2-letter buyer country (ISO 3166-1 alpha-2, e.g. CN) so getFreeGiftStock
filters by Storefront market availability. Falls back to initialData.country
(getJoyInitialData reads storefront.i18n.country), then to 'US' when
omitted (the app must resolve this from its own
storefront.i18n.country, e.g. via context.storefront.i18n in the root
loader — @joy-loyalty/hydrogen has no other way to learn it client-side).
currency?
currency?: string;ISO currency code for storefront price formatting (the recently-viewed
and recommended-products sections).
The core's product-card formatter has no other way to learn this on
headless. Falls back to the live cart's cost.totalAmount.currencyCode
when omitted, then to 'USD'.
initialData?
initialData?: HeadlessInitialData | null;Server-serialized data. Accepts BOTH the legacy JoyInitialData
(shopConfig/programs/tiers/customer) AND the SSR result
(HeadlessInitialData: beat-1 blob, thin shopifyCustomer, and the
synthesised login_url/page/... Layer-2 fields). When it carries the
blob and the CDN core exposes renderingProps, the orchestrator paints
through the real core builders; otherwise the customer balance
shows via the minimal path, then refreshes after hydration.
launcherLabel?
launcherLabel?: string;locale?
locale?: string;Joy-normalised locale for balance formatting + API text.
loginLabel?
loginLabel?: string;loginUrl?
loginUrl?: string;Where the guest CTA links (theme login route).
loyaltyPageUrl?
loyaltyPageUrl?: string;Where "View rewards" links.
onOpenCartDrawer?
onOpenCartDrawer?: () => void;Opens the host's cart drawer — the open_cart_drawer apply behavior. The
widget closes itself first, as Liquid does. Falls back to the
<JoyProvider onOpenCartDrawer>, then to clicking the merchant's
cartDrawerButtonSelector.
Returns
void
panelHeading?
panelHeading?: string;pathname?
pathname?: string;Current router pathname (useLocation().pathname) for "Recently viewed"
tracking. Pass it so client-side navigations are seen without reading
window.location mid-transition; falls back to window.location.pathname.
pointsLabel?
pointsLabel?: string;position?
position?: "bottom-right" | "bottom-left";preload?
preload?: "idle" | "interaction" | "eager";WHEN to fetch + mount the heavy Lit widget core from the CDN (~200KB gzip, parsed on the main thread). The lightweight React launcher below always renders immediately and stays until the core has mounted AND its first data settled, so nothing is ever unclickable; this only controls when it UPGRADES to the full widget:
'interaction': fetch on the shopper's first hover / focus / pointerdown / click of the launcher. Most storefront visitors never open the loyalty widget, so this keeps the core off the vast majority of page loads entirely — the largest performance win (perf C2) — at the cost of first-open latency (the hover/pointerdown head start usually covers it).'idle'(default): prefetch once the page has finished loading (window.load,document.readyState === 'complete') AND the browser is idle, so the full widget is ready before the first click without competing with hydration or LCP. Mirrors the Liquid/scripttag host's "page first, widget afterwindow.load" ordering. Also renders<link rel="modulepreload">for the core's entry graph from the SSR HTML wheninitialData.coreis present.'eager': fetch immediately on mount — earlier than Liquid (beforewindow.load), so it can compete with critical page rendering. Rarely what you want.
The launcher's hover / focus / pointerdown / click always call startCore
too, so any mode still upgrades on interaction as a fail-safe if idle is delayed.
shopDomain?
shopDomain?: string;The shop's myshopify domain — required for the beat-2 getInfo() live merge
(?d= shop scope). When initialData.blob is present its shop.shopifyDomain
is used automatically and this prop is unnecessary; pass it for the no-SSR-blob
case (C2's loader already carries it). NOT the Hydrogen storefront hostname.
tokenRoute?
tokenRoute?: string;Same-origin token route the merchant mounted (defaults to /api/joy-token).
viewRewardsLabel?
viewRewardsLabel?: string;LoadWidgetCoreOptions
Properties
assetUrl?
assetUrl?: string;Override the CDN origin (JOY_WIDGET_ASSET_URL) — e.g. a self-hosted mirror. Defaults to JOY_CDN_ORIGIN.
core?
core?: WidgetCoreManifest | null;The build manifest the SSR loader already fetched (getJoyInitialData /
getJoyLoyaltyPageData → core). When present the client skips its own
no-store build.json round trip AND emits <link rel="modulepreload"> /
the stylesheet <link> for the entry graph before injecting the script,
so the wrapper, the entry, its chunk and the CSS download in parallel
instead of being discovered one hop at a time (perf H1).
preloadLazy?
preloadLazy?: string[];Extra manifest.lazy[...] groups to preload alongside the entry graph (e.g. ['loyaltyPageV2'] on the loyalty page).
RedeemOptions
Superset of the SDK port's RedeemOptions — adds the caller-generated
idempotencyKey the Headless /customer/redeem endpoint dedupes on, so a
retry of the same intent never spends points twice.
Extends
RedeemOptions
Properties
idempotencyKey?
idempotencyKey?: string;points?
points?: number;Inherited from
CoreRedeemOptions.points
recipient?
recipient?: RedeemRecipient | null;Inherited from
CoreRedeemOptions.recipient
variantId?
variantId?: string;Inherited from
CoreRedeemOptions.variantId
RedeemRecipient
Properties
email: string;message?
message?: string;name?
name?: string;sendNotificationAt?
sendNotificationAt?: string;ReferralHistoryItem
Properties
createdAt
createdAt: string | null;email: string;id
id: string;status
status: "complete" | "pending" | "cancel";ReferralHistoryPage
Properties
items
items: ReferralHistoryItem[];pagination
pagination: Pagination;RewardQuery
Superset of the SDK's RewardQuery (@joy-loyalty/sdk/ports) — adds the headless-only
couponStatus switch that the base port does not carry.
Extends
RewardQuery
Properties
couponStatus?
couponStatus?: "available" | "unavailable";Which coupons the redeemed list holds. Threaded
straight to the SDK's GetRewardsParams.couponStatus — 'unavailable'
is the used+expired, unpaginated tab; anything else is the live
default. A top-level switch, like received, rather than folded into
query: it changes WHICH list comes back, not a cursor within it.
query?
query?: string | URLSearchParams;Inherited from
CoreRewardQuery.query
received?
received?: boolean;Inherited from
CoreRewardQuery.received
WidgetCoreManifest
build.json next to the CDN entry (scripts/copyWidgetV4Artifact.mjs):
the published build id plus the entry's STATIC module graph and CSS, every
path relative to the channel root (/widget-v4/latest/). Older manifests
carry buildId only; everything else is optional.
Properties
buildId
buildId: string;coreApiVersion?
coreApiVersion?: number;The core's API version (see SUPPORTED_CORE_API_VERSION); absent on manifests published before the contract.
css?
css?: string[];Design-token stylesheets (b/<buildId>/assets/*.css).
entry?
entry?: string;Path of the core's entry script, under b/<buildId>/.
imports?
imports?: string[];Chunks the entry imports at evaluation time (b/<buildId>/chunks/index-*.js).
lazy?
lazy?: Record<string, string[]>;Per-surface lazy chunk groups a host can preload when it KNOWS it will mount that surface.
WidgetCorePreloadLinksProps
Properties
assetUrl?
assetUrl?: string;core?
core?: WidgetCoreManifest | null;lazy?
lazy?: string[];manifest.lazy[...] groups to preload too (e.g. ['loyaltyPageV2']).
Type Aliases
ActivityQuery
type ActivityQuery = string | URLSearchParams;EarnRequest
type EarnRequest =
| {
context: SubmitFormEarnContext;
endpoint: "/submit-form";
programId: string;
}
| {
context: GoogleMapsReviewEarnContext;
endpoint: "/google-maps-review";
programId: string;
}
| {
context: ReceiptEarnContext;
endpoint: "/activity/submit-receipt";
programId: string;
}
| {
context: BirthdayEarnContext;
endpoint: "/birthday";
programId: string;
};StorefrontCart
type StorefrontCart = object;Properties
cost?
cost?:
| {
subtotalAmount?: | {
amount?: string | null;
currencyCode?: string | null;
}
| null;
totalAmount?: | {
amount?: string | null;
currencyCode?: string | null;
}
| null;
}
| null;deliveryGroups?
deliveryGroups?:
| {
nodes?: | (
| {
discountAllocations?: StorefrontCartDiscountAllocation[] | null;
}
| null)[]
| null;
}
| null;2026-07+: shipping allocations per delivery group.
discountAllocations?
discountAllocations?: StorefrontCartDiscountAllocation[] | null;Cart-level allocations (deprecated on Storefront, valid through 2026-10; absent in the 2026-07+ fragment).
discountCodes?
discountCodes?: object[] | null;lines?
lines?:
| {
nodes?: CartLine[] | null;
}
| null;updatedAt?
updatedAt?: string | null;Storefront Cart.updatedAt — orders the host's cart against a mutation result.
Variables
JOY_PERSONALIZED_CACHE_CONTROL
const JOY_PERSONALIZED_CACHE_CONTROL: "private, no-store" = 'private, no-store';The Cache-Control a response embedding personalized Joy data MUST use.
JOY_POINTS_CART_LINE_FRAGMENT
const JOY_POINTS_CART_LINE_FRAGMENT: "#graphql\n fragment JoyPointsCartLine on CartLine {\n id\n quantity\n cost {\n totalAmount {\n amount\n currencyCode\n }\n subtotalAmount {\n amount\n currencyCode\n }\n compareAtAmountPerQuantity {\n amount\n currencyCode\n }\n }\n discountAllocations {\n targetType\n discountedAmount {\n amount\n currencyCode\n }\n ... on CartCodeDiscountAllocation {\n code\n }\n }\n merchandise {\n ... on ProductVariant {\n id\n price {\n amount\n currencyCode\n }\n compareAtPrice {\n amount\n currencyCode\n }\n product {\n id\n title\n tags\n vendor\n productType\n priceRange {\n minVariantPrice {\n amount\n currencyCode\n }\n }\n collections(first: 20) {\n nodes {\n id\n title\n }\n pageInfo {\n hasNextPage\n }\n }\n }\n }\n }\n }\n";Storefront API, on CartLine — spread inside the cart query's lines { nodes { … } }.
JOY_POINTS_CART_LINE_SELLING_PLAN_FRAGMENT
const JOY_POINTS_CART_LINE_SELLING_PLAN_FRAGMENT: "#graphql\n fragment JoyPointsCartLineSellingPlan on CartLine {\n sellingPlanAllocation {\n sellingPlan {\n id\n }\n }\n }\n";Storefront API, on CartLine — optional, needs unauthenticated_read_selling_plans.
JOY_POINTS_CUSTOMER_ACCOUNT_QUERY
const JOY_POINTS_CUSTOMER_ACCOUNT_QUERY: "#graphql\n query JoyPointsCustomer {\n customer {\n ...JoyPointsCustomer\n }\n }\n #graphql\n fragment JoyPointsCustomer on Customer {\n tags\n companyContacts(first: 1) {\n nodes {\n id\n }\n }\n }\n\n";Customer Account API — run with context.customerAccount.query(...) for a logged-in customer.
JOY_POINTS_CUSTOMER_FRAGMENT
const JOY_POINTS_CUSTOMER_FRAGMENT: "#graphql\n fragment JoyPointsCustomer on Customer {\n tags\n companyContacts(first: 1) {\n nodes {\n id\n }\n }\n }\n";Customer Account API, on Customer: live tags (Liquid customer.tags) and B2B (customer.b2b?).
JOY_POINTS_PRODUCT_FRAGMENT
const JOY_POINTS_PRODUCT_FRAGMENT: "#graphql\n fragment JoyPointsProduct on Product {\n id\n title\n tags\n vendor\n productType\n priceRange {\n minVariantPrice {\n amount\n currencyCode\n }\n }\n collections(first: 20) {\n nodes {\n id\n title\n }\n pageInfo {\n hasNextPage\n }\n }\n }\n";Storefront API, on Product.
JOY_POINTS_VARIANT_FRAGMENT
const JOY_POINTS_VARIANT_FRAGMENT: "#graphql\n fragment JoyPointsVariant on ProductVariant {\n id\n price {\n amount\n currencyCode\n }\n compareAtPrice {\n amount\n currencyCode\n }\n }\n";Storefront API, on the selected ProductVariant.
JOY_POINTS_VARIANT_SELLING_PLANS_FRAGMENT
const JOY_POINTS_VARIANT_SELLING_PLANS_FRAGMENT: "#graphql\n fragment JoyPointsVariantSellingPlans on ProductVariant {\n sellingPlanAllocations(first: 10) {\n nodes {\n sellingPlan {\n id\n }\n checkoutChargeAmount {\n amount\n currencyCode\n }\n priceAdjustments {\n price {\n amount\n currencyCode\n }\n }\n }\n }\n }\n";Storefront API, on the selected ProductVariant — optional, needs unauthenticated_read_selling_plans.
Functions
createHeadlessHostAdapter()
function createHeadlessHostAdapter(options): HeadlessHostAdapter;Build a headless host adapter. SSR reads take precedence; every missing live operation rejects deliberately instead of attempting an undefined method.
Parameters
| Parameter | Type |
|---|---|
options | HeadlessHostAdapterOptions |
Returns
createHeadlessSource()
function createHeadlessSource(options): JoyDataSource | undefined;Returns undefined when there is no apiUrl to talk to — callers then
omit source from createHeadlessHostAdapter, which already degrades
every live method to a deliberate rejection.
Parameters
| Parameter | Type |
|---|---|
options | CreateHeadlessSourceOptions |
Returns
JoyDataSource | undefined
createJoyDataSource()
function createJoyDataSource(client): JoyDataSource;Build the supported live source around the singleton client from JoyProvider.
Parameters
| Parameter | Type |
|---|---|
client | JoyClient |
Returns
isJoyInitialDataPersonalized()
function isJoyInitialDataPersonalized(joy): boolean;True when joy (a getJoyInitialData result) carries anything scoped to
one shopper — balance/tier, Shopify identity, or a live JWT. false for a
guest, where every one of those keys is absent by construction.
Parameters
| Parameter | Type |
|---|---|
joy | PersonalizedJoyData | null | undefined |
Returns
boolean
isLoyaltyPageV2Enabled()
function isLoyaltyPageV2Enabled(data): boolean;The Liquid theme block's own switch (loyalty-page-v2.liquid:1-2): V2 renders
only when the blob's shop.loyaltyPageVersion is exactly 'v2' — missing or
anything else defaults to 'v1', and the block renders nothing. A headless
host must honour the same admin toggle, so a merchant who switches back to V1
does not keep serving the V2 page on Hydrogen.
Parameters
| Parameter | Type |
|---|---|
data | | Pick<JoyLoyaltyPageData, "shop"> | undefined |
Returns
boolean
JoyLoyaltyPage()
function JoyLoyaltyPage(__namedParameters): ReactNode;Parameters
| Parameter | Type |
|---|---|
__namedParameters | JoyLoyaltyPageProps |
Returns
ReactNode
JoyPointsCalculator()
function JoyPointsCalculator(__namedParameters): ReactNode;Parameters
| Parameter | Type |
|---|---|
__namedParameters | JoyPointsCalculatorProps |
Returns
ReactNode
JoyRedeemCart()
function JoyRedeemCart(__namedParameters): ReactNode;Parameters
| Parameter | Type |
|---|---|
__namedParameters | JoyRedeemCartProps |
Returns
ReactNode
JoyWidget()
function JoyWidget(__namedParameters): Element;@joy-loyalty/hydrogen — embed the Joy Loyalty Widget V4 in ANY Hydrogen / headless
Shopify storefront. One host-neutral core (published to the Joy CDN)
reached through HeadlessHostAdapter — no Weaverse.
4-step merchant integration:
// 1. npm i @joy-loyalty/hydrogen
// 2. env: JOY_API_URL, JOY_SHOP_DOMAIN, JOY_API_SECRET (server-only)
// 3. app/routes/api.joy-token.ts: export {loader} from '@joy-loyalty/hydrogen/routes/joy-token';
// app/root.tsx: <JoyWidget apiUrl={env.JOY_API_URL} />
// 4. app/csp.ts: scriptSrc: [...JOY_CSP_DIRECTIVES.scriptSrc]Optional resource routes, each mounted the same one-line way — the widget degrades gracefully when they are absent, so add only what the shop needs:
// app/routes/api.joy-place-order-scope.ts — only for a place_order program
// restricted to specific products/collections; without it that earn modal
// falls back to its plain info CTA.
export {loader} from '@joy-loyalty/hydrogen/routes/joy-place-order-scope';
// app/routes/api.joy-products.ts — powers the "Recently viewed" and
// "Recommended for you" widget sections from the Storefront API; without it
// both sections simply hide themselves.
export {loader} from '@joy-loyalty/hydrogen/routes/joy-products';Cart drawer block — redeem points for a discount code inside the cart (<JoyRedeemCart/>).
Pass the same root-loader getJoyInitialData() result <JoyWidget/> takes; add the cart
adapter (cartFetcher + cartRevalidate) to apply the code to the cart, otherwise the
issued code is shown with a Copy button:
const fetcher = useFetcher({key: 'joy-redeem-cart'});
const {revalidate} = useRevalidator();
<JoyRedeemCart apiUrl={env.JOY_API_URL} shopDomain={env.PUBLIC_STORE_DOMAIN}
initialData={rootData.joy} cart={cart} cartFetcher={fetcher} cartRevalidate={revalidate} />Point calculator block — "Earn X points" on the product page (context="product") and in the
cart (context="cart"). Spread the JoyPoints* fragments into your Storefront queries and, for a
logged-in shopper, run JOY_POINTS_CUSTOMER_ACCOUNT_QUERY in the same loader as getJoyInitialData:
// loader: const isLoggedIn = await customerAccount.isLoggedIn();
// const [joy, account] = await Promise.all([getJoyInitialData({...}),
// isLoggedIn ? customerAccount.query(JOY_POINTS_CUSTOMER_ACCOUNT_QUERY).catch(() => null) : null]); // never throw into the loader
// const {customerTags, isB2B} = toJoyPointsCustomerInput(account?.data?.customer);
<JoyPointsCalculator apiUrl={env.JOY_API_URL} shopDomain={env.PUBLIC_STORE_DOMAIN} initialData={rootData.joy}
context="product" product={product} selectedVariant={selectedVariant} quantity={quantity}
customerTags={customerTags} isB2B={isB2B} isLoggedIn={isLoggedIn} />Parameters
| Parameter | Type |
|---|---|
__namedParameters | JoyWidgetProps |
Returns
Element
loadWidgetCore()
function loadWidgetCore(options?): Promise<WidgetCoreLoadResult>;Load the widget core. Resolves once the core's custom elements are
registered — never throws; a CDN failure resolves {loaded: false}. A
failed load is NOT memoized: the next call retries.
Parameters
| Parameter | Type |
|---|---|
options? | LoadWidgetCoreOptions |
Returns
Promise<WidgetCoreLoadResult>
preconnectWidgetCore()
function preconnectWidgetCore(options?): void;Warm the DNS/TLS connection to the widget-core CDN so the eventual core fetch — which the host may DEFER behind idle/first-interaction to keep ~160-220KB gzip off page loads where the shopper never opens the widget — pays no connection-setup latency when it finally fires.
A no-op on the server, and idempotent on the client (dedup-guarded per origin
like loadWidgetCore's script tag). Cheap — a preconnect hint carries
no payload — so a host can call it eagerly on mount even while gating the core
itself. crossOrigin: 'anonymous' matches the core script's own
crossOrigin so the warmed connection is actually reused (a preconnect whose
CORS mode differs opens a second, wasted connection).
Parameters
| Parameter | Type |
|---|---|
options? | LoadWidgetCoreOptions |
Returns
void
preloadWidgetCore()
function preloadWidgetCore(manifest, options?): void;Emit <link rel="modulepreload"> for the entry graph and the stylesheet
<link> for the tokens, dedup-guarded per href so a host that already
rendered them server-side (<WidgetCorePreloadLinks/>) adds nothing. The
stylesheet carries CORE_CSS_ATTR so the CDN wrapper does not append
its own copy. No-op on the server.
Parameters
| Parameter | Type |
|---|---|
manifest | WidgetCoreManifest |
options? | { assetUrl?: string; lazy?: string[]; } |
options.assetUrl? | string |
options.lazy? | string[] |
Returns
void
resolveWidgetCoreAssetUrls()
function resolveWidgetCoreAssetUrls(manifest, options?): object;Absolute URLs of everything in a WidgetCoreManifest the browser can
fetch up front: the entry + its static chunks (modulepreload), the design
tokens (stylesheet) and, when asked, the named lazy groups. Pure — shared by
the client loader (<link> injection) and the SSR components (<link> JSX).
Parameters
| Parameter | Type |
|---|---|
manifest | WidgetCoreManifest |
options? | { assetUrl?: string; lazy?: string[]; } |
options.assetUrl? | string |
options.lazy? | string[] |
Returns
object
css
css: object[];modules
modules: string[];toJoyPointsCustomerInput()
function toJoyPointsCustomerInput(customer): object;Parameters
| Parameter | Type | Description |
|---|---|---|
customer | PointsAccountCustomer | null | undefined | customer from JOY_POINTS_CUSTOMER_ACCOUNT_QUERY |
Returns
object
the calculator's customerTags / isB2B inputs; undefined when the field was not
selected (an empty tag list stays []). isB2B = Liquid customer.b2b?.
customerTags
customerTags: string[] | undefined;isB2B
isB2B: boolean | undefined;WidgetCorePreloadLinks()
function WidgetCorePreloadLinks(__namedParameters): ReactNode;Parameters
| Parameter | Type |
|---|---|
__namedParameters | WidgetCorePreloadLinksProps |
Returns
ReactNode
References
clearJoyToken
Re-exports clearJoyToken
DEFAULT_PLACE_ORDER_SCOPE_ROUTE
Re-exports DEFAULT_PLACE_ORDER_SCOPE_ROUTE
DEFAULT_POINTS_LABEL
Re-exports DEFAULT_POINTS_LABEL
DEFAULT_TOKEN_ROUTE
Re-exports DEFAULT_TOKEN_ROUTE
ensureClient
Re-exports ensureClient
formatMoney
Re-exports formatMoney
formatPointsNumber
Re-exports formatPointsNumber
getJoyToken
Re-exports getJoyToken
GetJoyTokenOptions
Re-exports GetJoyTokenOptions
getPlaceOrderScope
Re-exports getPlaceOrderScope
GetPlaceOrderScopeOptions
Re-exports GetPlaceOrderScopeOptions
ICON_IMAGE_SIZE
Re-exports ICON_IMAGE_SIZE
isLineFollowOaProgram
Re-exports isLineFollowOaProgram
isRepeatableSocialProgram
Re-exports isRepeatableSocialProgram
isSocialEarnProgram
Re-exports isSocialEarnProgram
JOY_API_ORIGIN
Re-exports JOY_API_ORIGIN
JOY_CDN_ORIGIN
Re-exports JOY_CDN_ORIGIN
JOY_CSP_DIRECTIVES
Re-exports JOY_CSP_DIRECTIVES
JoyConfig
Re-exports JoyConfig
joyCspDirectives
Re-exports joyCspDirectives
JoyCspDirectives
Re-exports JoyCspDirectives
JoyCustomerState
Re-exports JoyCustomerState
JoyMoney
Re-exports JoyMoney
JoyProvider
Re-exports JoyProvider
JoyProviderCartHandlers
Re-exports JoyProviderCartHandlers
POINTS_LABEL_HELP
Re-exports POINTS_LABEL_HELP
resolvePointsLabel
Re-exports resolvePointsLabel
sizeShopifyImage
Re-exports sizeShopifyImage
SOCIAL_EARN_EVENT_KEYS
Re-exports SOCIAL_EARN_EVENT_KEYS
useJoyConfig
Re-exports useJoyConfig
useJoyCustomer
Re-exports useJoyCustomer
useJoyProviderCart
Re-exports useJoyProviderCart
useJoyProviderCartHandlers
Re-exports useJoyProviderCartHandlers