Headless API
Points calculator

Points calculator

<JoyPointsCalculator/> is the headless counterpart of the Liquid Joy: Point calculator block. On a product page it shows the "Earn X points" estimate for the selected variant and quantity. In a cart page or cart drawer it shows the estimate for the cart total. The widget core computes the estimate from the same program data the Liquid block reads, so the numbers match your theme. Design and texts come from the Joy admin: Branding > Point calculator.

Requires @joy-loyalty/hydrogen 0.4.0 and @joy-loyalty/sdk 0.3.1 or later, plus the setup from the Overview and Authentication (root-loader initial data and the /api/joy-token route).

npm install @joy-loyalty/hydrogen@^0.4.0 @joy-loyalty/sdk@^0.3.1

Install with an AI agent

The joy-headless-points-calculator (opens in a new tab) agent skill can do the steps below for you. It walks your coding agent (Claude Code, Codex, Cursor or any agent the Skills CLI (opens in a new tab) supports) through the setup on this page: upgrading @joy-loyalty/hydrogen, adding the Customer Account query to the root loader, spreading the Joy fragments and the cart-level discount fields for your Storefront API version, mounting <JoyPointsCalculator/> on the product page and in the cart, and a verification checklist.

Run this in your Hydrogen project root. Run it again if you installed the skills before this one was added — npx skills update only refreshes skills you already have.

npx skills add tinhnv2001/joy-loyalty-hydrogen-skills

Then ask your agent:

Use the joy-headless-points-calculator skill to add the Joy Point calculator to my product page
(under the add-to-cart button) and to my cart drawer. Add the Customer Account query to my root
loader without letting it throw, and merge the Joy fragments and cart discount fields that match
my Storefront API version. Do not deploy anything.
When you are done, walk me through the verification checklist.

The skill stops when Joy headless isn't installed yet (no getJoyInitialData() in the root loader or no /api/joy-token route) and points to joy-headless-install in the same repository. It tells the agent not to touch JOY_API_SECRET and not to deploy — review the diff before you commit.

1. Pass customer input from the root loader

Customer tags and the B2B flag live in Shopify, not in Joy, so your loader supplies them. In the root loader that calls getJoyInitialData(), run the Customer Account query for a logged-in customer and pass isLoggedIn for every visitor:

import {getJoyInitialData} from '@joy-loyalty/hydrogen/server';
import {JOY_POINTS_CUSTOMER_ACCOUNT_QUERY, toJoyPointsCustomerInput} from '@joy-loyalty/hydrogen';
 
const isLoggedIn = await context.customerAccount.isLoggedIn();
// Run in parallel with getJoyInitialData, and never let this optional query
// throw into the root loader.
const [joy, account] = await Promise.all([
  getJoyInitialData({/* … your existing options … */}),
  isLoggedIn
    ? context.customerAccount.query(JOY_POINTS_CUSTOMER_ACCOUNT_QUERY).catch(() => null)
    : null,
]);
const {customerTags, isB2B} = isLoggedIn
  ? toJoyPointsCustomerInput(account?.data?.customer)
  : {customerTags: undefined, isB2B: undefined};
 
return {joy, joyPoints: {customerTags, isB2B, isLoggedIn} /* , …the rest of your root data */};
  • isLoggedIn lets the block hide, instead of showing guest numbers, when the Joy token mint fails for a logged-in shopper.
  • Never pass customerTags / isB2B for a guest. When isLoggedIn is omitted, they imply "logged in".
  • If the query fails, customerTags / isB2B are undefined and the block degrades as described in Limitations; the page is never affected.
  • This is personalised root data: keep the same cache rule as the rest of your logged-in root data. The block renders only a reserved placeholder on the server and reads customer input after hydration.

2. Add the fragments to your queries

All fragments are exported from the package root. Spread them into your own queries:

FragmentSpread into
JOY_POINTS_PRODUCT_FRAGMENT (...JoyPointsProduct)The product in your product-page query.
JOY_POINTS_VARIANT_FRAGMENT (...JoyPointsVariant)The selected variant in your product-page query.
JOY_POINTS_CART_LINE_FRAGMENT (...JoyPointsCartLine)Inside your existing lines(first: $numCartLines) { nodes { … } }. There is no Cart-level fragment with its own lines.
JOY_POINTS_VARIANT_SELLING_PLANS_FRAGMENT, JOY_POINTS_CART_LINE_SELLING_PLAN_FRAGMENTOptional. They need the unauthenticated_read_selling_plans Storefront scope. Without them, subscription lines count as one-time purchases.
import {JOY_POINTS_PRODUCT_FRAGMENT, JOY_POINTS_VARIANT_FRAGMENT} from '@joy-loyalty/hydrogen';
 
const PRODUCT_QUERY = `#graphql
  query Product($handle: String!, $selectedOptions: [SelectedOptionInput!]!) {
    product(handle: $handle) {
      ...JoyPointsProduct
      selectedOrFirstAvailableVariant(selectedOptions: $selectedOptions) {
        ...JoyPointsVariant
      }
      # …your own fields
    }
  }
  ${JOY_POINTS_PRODUCT_FRAGMENT}
  ${JOY_POINTS_VARIANT_FRAGMENT}
`;
  • Keep collections(first: 20) at 20. It merges with the Redeem in Cart fragment's selection, and a different argument is a GraphQL field conflict.

Cart-level discounts (required for context="cart")

The cart-line fragment carries only line-level discount allocations. On the Cart, also select discountCodes { code applicable } and the order-level allocations — the same fields as the Redeem in Cart fragment:

  • Default (Storefront API 2025-10 to 2026-10): Cart.discountAllocations { targetType discountedAmount { amount currencyCode } ... on CartCodeDiscountAllocation { code } }.
  • Modern (Storefront API 2026-07 and later): joyAllDiscounts: discountAllocations(lineLevelOnly: false) { … } on each CartLine.
⚠️

Without one of these two sources the cart calculator hides and logs one [joy] JoyPointsCalculator: … warning — whether or not a discount code is applied, because an automatic order discount (no code) is only visible through them. It never shows a wrong estimate.

3. Mount the block

Product page — pass the product, the selected variant and the quantity state:

import {JoyPointsCalculator} from '@joy-loyalty/hydrogen';
import {useRouteLoaderData} from 'react-router';
 
export function ProductPoints({product, selectedVariant, quantity}) {
  const root = useRouteLoaderData('root');
  if (!root?.joyApiUrl || !root.joyShopDomain) return null;
 
  return (
    <JoyPointsCalculator
      apiUrl={root.joyApiUrl}
      shopDomain={root.joyShopDomain}
      initialData={root.joy ?? null}
      context="product"
      product={product}
      selectedVariant={selectedVariant}
      quantity={quantity}
      customerTags={root.joyPoints?.customerTags}
      isB2B={root.joyPoints?.isB2B}
      isLoggedIn={root.joyPoints?.isLoggedIn}
    />
  );
}

Cart page or drawer — one component for both, cart total only:

<JoyPointsCalculator
  apiUrl={root.joyApiUrl}
  shopDomain={root.joyShopDomain}
  initialData={root.joy ?? null}
  context="cart"
  cart={cart}
  customerTags={root.joyPoints?.customerTags}
  isB2B={root.joyPoints?.isB2B}
  isLoggedIn={root.joyPoints?.isLoggedIn}
/>

context is explicit — "product" or "cart". Any other value renders nothing and warns once. Where you mount the block decides where it shows: the Choose positions and Also use on Cart Page settings in the Joy admin apply to Online Store themes only.

Props

PropTypeNotes
apiUrlstringRequired. Headless API base URL (JOY_API_URL). Used for Join Program.
shopDomainstringRequired. The shop's *.myshopify.com domain.
initialDataJoyInitialDataResult
or null
Required. The root loader's getJoyInitialData() result. null renders nothing.
context'product'
or 'cart'
Required. Where the block lives. Never inferred.
productPointsStorefrontProductProduct page. The product with ...JoyPointsProduct.
selectedVariantPointsStorefrontVariantProduct page. The selected variant with ...JoyPointsVariant.
quantitynumberQuantity picked on the page. Default 1.
sellingPlanIdstringSelected selling plan GID. None means a one-time purchase.
cartStorefrontCart
or a getter
Cart context. The cart with ...JoyPointsCartLine. Falls back to <JoyProvider cart>.
customerTagsstring[]Customer Account customer.tags. Logged-in customers only.
isB2BbooleanThe customer has a company contact. Logged-in customers only.
isLoggedInbooleanawait customerAccount.isLoggedIn(). Pass it for guests too (false).
align'left', 'center'
or 'right'
Default left, as the Liquid block. Read at mount.
loginUrlstringFallback join/login target. The merchant's Text action link (Point calculator settings) wins, then this, then initialData.login_url, then /account/login.
tokenRoutestringSame-origin token route. Default /api/joy-token.
onNavigate(url) => voidClient-side navigation (useNavigate()). Omitted: full page load.
onJoinClick(action) => boolean | voidCalled before a join click is handled. Return true to take over.
assetUrlstringOverrides the widget-core CDN URL (JOY_WIDGET_ASSET_URL). Leave unset in production.
classNamestringClass for the wrapper element.

Join button

  • Guests. When Trigger: Point Calculator link (non-login customers) is set to Open loyalty widget (Joy admin settings, see Redemption behavior (opens in a new tab)), the link opens <JoyWidget/> through #joy-open — the widget must be mounted, otherwise it goes to the login URL. With Redirect to login page, it goes to the login URL.
  • Logged-in shoppers who haven't joined see Join Program. It calls POST /customer/join-program with joinFrom: product_page and reloads on success.
  • onJoinClick returning true overrides both.

Customer fields the block reads

The estimate for a logged-in customer uses three fields of GET /customer (see the Customer schema):

FieldUse
assignedTierIdThe customer's own stored tier id, null when they have none. Unlike tier, it is never a resolved or fallback tier, so tier-based earning rates match Liquid.
excludedFromLoyaltytrue when the customer left the program or is excluded by a membership segment. The block hides.
earningLimit.remainingCapacityPoints the customer can still earn this period (null = unlimited). The estimate is capped to it.

All three are additive and optional. A client that reads them must treat a missing field as "not known": fall back to tier.id, treat excludedFromLoyalty as false, and apply no cap.

Limitations

⚠️

Shop currency only. When the cart's or buyer's currency differs from the shop's base currency, the block renders nothing, so no amount is shown in the wrong currency. Market-rate conversion is not supported yet.

  • Cart: one estimate for the cart total. There is no per-line estimate.
  • Look. V4 style (Lit web component), no counting animation. Icon, icon size, colors and text size follow the admin settings. HTML in the calculator texts is shown as plain text.
  • Collections. Products in more than 20 collections can differ from Liquid (collections(first: 20)). Without the cart-line fragment, rules scoped to products, collections or tags are not matched on cart lines.
  • Free gifts. The Joy free-gift residue is not applied, so a cart with a Joy free-gift line can read about one minor unit per gift line higher than the Liquid block.
  • Customer tags and B2B. Tag rules, hiding for customers tagged as having left the program, and the B2B exclusion need customerTags / isB2B. Without them, tag rules evaluate with no tags and B2B customers are not hidden.
  • Balance not loaded. A logged-in shopper whose Joy balance isn't loaded (deferCustomerBalance: true, or the /customer read failed) doesn't see the block. It is never shown with guest numbers.
  • Login redirects. The join/login link uses the Text action link first and loginUrl only when it's empty. Custom login redirects are not applied — use onJoinClick to override.
  • No Weaverse block yet. On Weaverse storefronts, use the component directly.
  • Widget core. The block needs a widget core that provides loadPointsCalculatorCore. Against an older core it renders nothing and logs one [joy] JoyPointsCalculator: … warning. It never throws into your page.

Related