Preorder badge, button and notify-me on a headless storefront
Worked recipe: on Hydrogen or any headless stack, show a Preorder badge and button that add the right cart line, a notify-me form for sold-out variants, and a custom widget read straight from STOQ's metafields. Every step, the code, and how to check orders and signups land.
Last updated
For: Hydrogen and headless developers. STOQ’s theme app embed doesn’t load on a headless storefront, so the storefront has to ask STOQ’s data itself.
Goal: on the product page, a Preorder badge and a Preorder button for variants on an offer, which add the cart line with the offer’s selling plan; a notify-me form for sold-out variants; and, optionally, a fully custom widget built from STOQ’s metafields with no SDK at all.
Before you start
Section titled “Before you start”- The store’s public Storefront API token, the one the headless store already uses (Hydrogen’s
PUBLIC_STOREFRONT_API_TOKEN). Never use a private Storefront token or STOQ’s API key in browser code. - The SDK:
npm install @artossoftware/stoq-sdk(React 18+ for the hooks), or the script tag from Headless & Hydrogen. - An offer with variants on it: see Launch a preorder offer. Back-in-stock signups need email (or SMS) turned on in STOQ.
- Markets: if the store’s offers are limited to some Shopify Markets, pass the buyer’s
marketto the SDK, or every variant reads as not on preorder. - Plan: none needed beyond what the offer uses.
1. Wrap the app in the provider
Section titled “1. Wrap the app in the provider”// app/root.tsx (alongside your existing Outlet and useLoaderData imports)
export default function App() { const { env } = useLoaderData<typeof loader>() return ( <StoqProvider config={{ shop: 'your-shop.myshopify.com', storefrontToken: env.PUBLIC_STOREFRONT_API_TOKEN }}> <Outlet /> </StoqProvider> )}init makes one Storefront API call for STOQ’s configuration, then looks up each variant’s availability when you ask (batched, cached for 60 seconds). Nothing calls STOQ’s servers except a signup.
2. Add the badge, the button and the notify-me form
Section titled “2. Add the badge, the button and the notify-me form”Include availableForSale and currentlyNotInStock in your variant fragment, and pass the variant object so the SDK uses your data as it is:
StoqNotifyMeButton, StoqPreorderBadge, useStoqCartLine, useStoqVariant,} from '@artossoftware/stoq-sdk/react'
export function BuyBox({ variant }) { const state = useStoqVariant(variant) const line = useStoqCartLine(variant, 1)
// Both are null while the SDK loads (and on the server). Keep the button // disabled until they resolve: a plain line would add a preorder without its // selling plan, so a deposit offer would charge the full price. const ready = state != null && line != null
if (!variant.availableForSale && !state?.isPreorder) { return <StoqNotifyMeButton variantId={variant.id} productId={variant.product.id} /> }
return ( <> <StoqPreorderBadge variantId={variant}>Preorder</StoqPreorderBadge> <CartForm route="/cart" action={CartForm.ACTIONS.LinesAdd} inputs={{ lines: ready ? [line] : [] }}> <button type="submit" disabled={!state || !line}>{state?.isPreorder ? 'Preorder now' : 'Add to cart'}</button> </CartForm> {state?.isPreorder && state.shippingText ? <p>{state.shippingText}</p> : null} {state?.isPreorder && state.remainingCount != null ? <p>{state.remainingCount} left</p> : null} </> )}useStoqVariantgives{ isPreorder, sellingPlanId, shippingText, maxCount, remainingCount }, ornullwhile loading.remainingCountis the offer’s preorder limit, so show it only whenisPreorderis true.useStoqCartLinegives the StorefrontCartLineInput, ornullwhile loading; never replace it with a line of your own. It carriessellingPlanIdonly when the variant sells as a preorder, orattributesfor offers that use line-item properties instead of a selling plan. Pass it through untouched.<StoqPreorderButton onAddToCart={…}>is the ready-made alternative: the merchant’s button copy and the payment option picker (full payment or deposit), then your callback with the final line. UsetoCartFormInput(line)to post it to Hydrogen’s/cartaction.
Over MCP, design_theme writes a starter for the store:
{ "tool": "design_theme", "arguments": { "surface": "sdk", "widget": "product_page", "format": "react", "variant_id": "43900910010503", "product_id": "8123456789" } }3. Build your own notify-me form (optional)
Section titled “3. Build your own notify-me form (optional)”<StoqNotifyMeButton> renders a minimal button and email form (stoq-* class names and --stoq-* CSS variables to restyle it). For your own form, use useStoqSignup:
export function NotifyMe({ variant }) { const { submit, submitting, result, error } = useStoqSignup()
if (result?.ok) return <p>You’re on the list.</p>
return ( <form onSubmit={(e) => { e.preventDefault() const email = new FormData(e.currentTarget).get('email') as string submit({ variantId: variant.id, productId: variant.product.id, email, acceptsMarketing: false }) }} > <input name="email" type="email" required placeholder="you@example.com" /> <button disabled={submitting}>Notify me</button> {error || (result && !result.ok) ? <p role="alert">Couldn’t sign you up. Try again.</p> : null} </form> )}productId is required. submit resolves to { ok, status, intents, errors }: ok is true when the signup was created (status 201); a duplicate or invalid signup comes back with ok: false and the reason in errors. A signup fires stoq:restock-modal:submitted on window.
4. A custom widget straight from the metafields (no SDK)
Section titled “4. A custom widget straight from the metafields (no SDK)”For full control, or to render server-side in a Hydrogen loader, read STOQ’s metafields with your own Storefront API query. This example reads the shop-level selling_plans metafield: a plain array with every enabled offer’s configuration, including its full variant_ids list (numeric strings), preorder_button_text and preorder_shipping_text. STOQ writes it on every publish, next to cachedSellingPlans. The theme extension and the SDK read cachedSellingPlans first. In that metafield the offers sit under plans, and on some stores every offer’s variant_ids is empty with variant_ids_truncated: true, so membership has to come from each variant’s selling plan allocations (see Headless & Hydrogen). For a simple variant-to-offer match, the full list in selling_plans is the easier read:
query StoqPreorderWidget($handle: String!) { shop { offers: metafield(namespace: "restockrocket_production", key: "selling_plans") { value } } product(handle: $handle) { variants(first: 100) { nodes { id currentlyNotInStock preorderCount: metafield(namespace: "restockrocket_production", key: "preorder_count") { value } preorderMaxCount: metafield(namespace: "restockrocket_production", key: "preorder_max_count") { value } } } }}// In the loader: parse the shop's offers once, then ask per variant.function parseStoqOffers(offersJson: string | undefined) { try { const offers = offersJson ? JSON.parse(offersJson) : [] return Array.isArray(offers) ? offers : [] } catch { return [] }}
// Which offer applies to a variant, and what to show. null: sell it normally.function preorderFor(variant, offers: any[]) { const numericId = typeof variant?.id === 'string' ? variant.id.split('/').pop() : null if (!numericId || !variant.currentlyNotInStock) return null
const offer = offers.find( (o) => o?.enabled && Array.isArray(o.variant_ids) && o.variant_ids.map(String).includes(numericId), ) if (!offer?.shopify_selling_plan_id) return null
const max = variant.preorderMaxCount ? Number(variant.preorderMaxCount.value) : null const sold = variant.preorderCount ? Number(variant.preorderCount.value) || 0 : 0 // The offer's limit is reached: no more preorders for this variant. if (max !== null && Number.isFinite(max) && sold >= max) return null
return { buttonText: offer.preorder_button_text || 'Preorder', shippingText: offer.preorder_shipping_text, sellingPlanId: `gid://shopify/SellingPlan/${offer.shopify_selling_plan_id}`, remaining: max === null || !Number.isFinite(max) ? null : max - sold, }}
// const offers = parseStoqOffers(data.shop.offers?.value)// const preorders = data.product.variants.nodes.map((v) => preorderFor(v, offers))This simple check covers offers that sell when the variant is out of stock (the default). Offers that sell while in stock, market-scoped offers, schedules and line-item-property offers have more rules: the SDK applies all of them, so prefer it unless you need the raw data. The fields are listed in Shop-level metafields and Variant-level metafields.
If it fails
Section titled “If it fails”The storefront side has no STOQ error codes: the SDK reports problems through useStoq().status / .error and the console. The checks below use the API.
| Symptom or code | What happened | What to do |
|---|---|---|
Nothing renders, useStoq(). |
Wrong shop domain or Storefront token | Check both in the provider config; the console names the failing call |
isPreorder is always false |
Offers limited to Markets with no market passed, the variant isn’t on an enabled offer, or it’s in stock on an out-of-stock offer |
Pass market; check the variant with the availability call below |
Signup ok: false |
The signup was refused, for example the shopper is already waiting for that variant, or productId or the contact is missing |
Read result. and result.; tell a shopper who is already waiting that they’re on the list |
invalid_ on the availability check |
country missing, or more than 100 ids |
Send an ISO country code and up to 100 variant ids |
auth_ on a check |
The API key is wrong | Use the store’s key, server-side only |
Check it worked
Section titled “Check it worked”-
Ask STOQ how a buyer in a country sees the variant (server-side, with the API key):
curl "https://app.stoqapp.com/api/v2/external/preorders/product_variants/availability?country=US&shopify_variant_ids=43900910010503" \-H "X-Auth-Token: $STOQ_API_KEY"{ "tool": "execute_read", "arguments": { "method": "GET", "path": "/preorders/product_variants/availability", "params": { "country": "US", "shopify_variant_ids": ["43900910010503"] } } }status: "live"means an offer applies and its limit isn’t reached; your badge should show when the variant meets the offer’sstock_condition.not_enrolledmeans the variant is on no offer. -
Add the variant to the cart and read the cart with the Storefront API: the line has a
sellingPlanAllocationwith the offer’s selling plan (or the_stoq_shopify_selling_plan_idattribute). -
Place a test order with a test payment gateway, then find it:
GET /preorders/orders?shopify_variant_id=43900910010503lists it. -
Sign up on a sold-out variant with a test email, then
GET /back_in_stock/signups?shopify_variant_id=<id>shows the signup. Delete it withDELETE /back_in_stock/signups/:id.
Thanks for letting us know.
Still stuck? Ask Quinn or chat with support