Documentation
One reactive cart. From the first add to the next update.
A cart shared across your theme.
$cart gives Alpine components a shared, reactive view of a Shopify cart. Reads, writes, and opening the cart go through Shopify’s standard storefront actions. The theme stays in charge of its HTML and cart presentation.
You need Alpine.js 3 and a Shopify Liquid storefront with Shopify.actions. This is not a headless Storefront API client, a Shopify Admin integration, or a checkout extension.
Install the plugin
Choose npm for a bundled theme, or use the CDN scripts directly. Both approaches require a Shopify Liquid storefront with standard storefront actions.
Load Alpine only once. If your theme already starts Alpine, register the plugin in that setup rather than adding a second copy or calling Alpine.start() again.
npm
Get alpinejs-shopify-cart on npm, then register it before starting Alpine.
npm install alpinejs@^3 alpinejs-shopify-cart@1.0.0
import Alpine from 'alpinejs'
import shopifyCart from 'alpinejs-shopify-cart'
Alpine.plugin(shopifyCart)
Alpine.start()
CDN
Include these deferred scripts in your theme layout, with the plugin before Alpine. The CDN build registers itself during alpine:init; no separate registration script is needed.
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs-shopify-cart@1.0.0/dist/alpinejs-shopify-cart.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.17.4/dist/cdn.min.js"></script>
Download the version-pinned plugin from jsDelivr. Do not combine CDN Alpine with a second bundled Alpine instance.
Serve from theme assets
For Shopify-hosted files, install through npm and copy node_modules/alpinejs-shopify-cart/dist/alpinejs-shopify-cart.min.js to your theme’s assets/ directory. Copy node_modules/alpinejs/dist/cdn.min.js there as alpine.js. Keep the same loading order:
<script defer src="{{ 'alpinejs-shopify-cart.min.js' | asset_url }}"></script>
<script defer src="{{ 'alpine.js' | asset_url }}"></script>
The plugin automatically starts a cart read after document and action initialization. Check $cart.error if your runtime is unavailable, and call $cart.refresh() to retry once available.
Read reactive state
Every $cart reference resolves to Alpine.store('shopifyCart'). Updating the cart in one component updates dependent expressions elsewhere.
<div x-data>
<span x-text="$cart.totalQuantity"></span>
<span x-show="$cart.pending">Updating cart…</span>
</div>
| Property | Meaning |
|---|---|
ready | The initial read attempt finished, including failure. Check error separately. |
cart | Raw Shopify cart result, or null when no cart exists. |
lines | Cart line array, normalized from an array or a lines.nodes connection. |
totalQuantity | Quantity across all lines; zero before a cart is available. |
cost | Cart cost, or null. Money amounts are decimal strings with a currencyCode. |
discountCodes | Codes returned by Shopify, including applicability. |
pending | Whether local or observed external operations remain pending. |
pendingCount | Number of tracked operations, including queued local calls. |
pendingOperation | Most recently registered pending operation, or null. |
note / attributes | Last successfully observed values; undefined until known. Cleared when the cart ID changes. |
error | Rejected operation details, or null. |
userErrors / warnings | Shopify’s resolved validation errors and non-blocking warnings. |
detail | Custom detail from the most recently applied result. |
A summary, not a product catalog. Standard cart lines expose IDs, quantity, and cost. They do not supply product titles, images, or full merchandise objects. Render those through Liquid or a separate product-data source. Do not divide money amounts by 100.
Change the cart
Mutation methods return the full Shopify result: { cart, userErrors, warnings, detail }. Requests can reject, so catch failures in your component logic. Local calls are queued in order.
Add a variant
Pass a variant ID as merchandiseId, not a cart line ID. A Shopify GID or a documented raw ID can be used.
const result = await this.$cart.add(
{ merchandiseId: this.variantId, quantity: 1 },
{ context: 'product' }
)
if (result.userErrors?.length) return
await this.$cart.open()
Update or remove a line
Use the line ID returned by Shopify. Quantities are absolute targets, not increments. Disable controls while pending if they derive a new quantity from the current snapshot.
await this.$cart.update({ id: line.id, quantity: 2 })
await this.$cart.remove(line.id)
// Both methods also accept arrays.
await this.$cart.remove([firstLine.id, secondLine.id])
Notes, attributes, and discounts
await this.$cart.setNote('Leave at the front desk')
await this.$cart.setAttributes([
{ key: 'Gift wrap', value: 'Yes' }
])
await this.$cart.setDiscountCodes(['WELCOME10'])
Attributes and discount codes replace the complete set. Include every value you want to retain. An empty array clears the set. An empty string clears the note.
Send a complete standard payload
await this.$cart.mutate({
lines: [{ id: line.id, quantity: 2 }],
note: 'Gift order'
}, {
context: 'cart',
detail: { source: 'cart-page' }
})
Refresh and open
await this.$cart.refresh()
await this.$cart.open()
| Method | Input |
|---|---|
add(lines, options?) | One line or an array; merchandiseId, quantity, optional attributes and sellingPlanId. |
update(lines, options?) | One existing line or an array with id and quantity. |
remove(ids, options?) | One line ID or an array; sent with quantity zero. |
setNote(note, options?) | String. |
setAttributes(values, options?) | Complete array of key/value pairs. |
setDiscountCodes(codes, options?) | Complete array of code strings. |
mutate(payload, options?) | Standard updateCart payload. |
refresh(options?) | Optional cartId and signal. Returns { cart }. |
open() | No arguments. Returns Promise<void>. |
Mutation options accept signal, context, detail, and the standard nested event options. Top-level context and detail take precedence over their nested counterparts. Prefer one style consistently.
Line-item properties
Gift wrapping, engraving, and personalization belong to an individual cart line. With Shopify’s standard actions, send these as an attributes array of string key/value pairs inside the line input. Do not use the Ajax API’s properties: { ... } format with $cart.
The recipes below run inside async component methods. Here cart means this.$cart or Alpine.store('shopifyCart'), and IDs come from your theme’s current product selection. Use the error-handling pattern for each call.
Add personalized items
await cart.add({
merchandiseId: variantId,
quantity: 1,
attributes: [
{ key: 'Gift wrap', value: 'Yes' },
{ key: 'Engraving', value: engraving.trim() }
]
}, { context: 'product' })
The same variant with different properties can produce separate cart lines. Use the fresh line IDs from Shopify when updating or removing items, not just the variant ID.
Wire a checkbox and text input
Register this provider before Alpine.start(). Use the markup as your product form inside a parent x-data scope that provides selectedVariantId. Do not nest it inside another form. The submit handler reads the selected variant when the buyer submits, rather than copying it only once.
Alpine.data('giftProduct', () => ({
giftWrap: false,
engraving: '',
message: '',
async add(variantId) {
if (!this.$cart.ready || this.$cart.pending) return
this.message = ''
const attributes = this.giftWrap
? [{ key: 'Gift wrap', value: 'Yes' }]
: []
if (this.engraving.trim()) {
attributes.push({ key: 'Engraving', value: this.engraving.trim() })
}
try {
const result = await this.$cart.add({
merchandiseId: variantId, quantity: 1, attributes
}, { context: 'product' })
this.message = result.userErrors?.[0]?.message
?? result.warnings?.[0]?.message
?? 'Added to cart.'
} catch (error) {
this.message = error?.message ?? 'Could not add this item. Try again.'
}
}
}))
<form x-data="giftProduct" @submit.prevent="add(selectedVariantId)">
<label>
<input type="checkbox" x-model="giftWrap" :disabled="$cart.pending">
Gift wrap
</label>
<label>
Engraving
<input type="text" x-model="engraving" maxlength="30" :disabled="$cart.pending">
</label>
<button type="submit" :disabled="!$cart.ready || $cart.pending">
Add to cart
</button>
<p role="status" x-text="message"></p>
</form>
Edit properties on an existing line
Keep any other properties your theme wants to retain. In this example, retainedAttributes comes from your theme’s line-property data, not from the standard cart summary.
await cart.update({
id: line.id,
quantity: line.quantity,
attributes: [
...retainedAttributes.filter(attribute => attribute.key !== 'Gift wrap'),
{ key: 'Gift wrap', value: 'Yes' }
]
}, { context: 'cart' })
await cart.update({
id: line.id,
quantity: line.quantity,
attributes: []
}, { context: 'cart' })
Inputs are not a product-data API. The standard cart summary does not return line attributes, titles, or images. Keep your property editor backed by Liquid or another appropriate data source; do not assume $cart.lines[0].attributes exists. Re-read the cart’s line IDs after a mutation rather than caching them.
Shopify’s standard updateCart input reference documents attributes and sellingPlanId.
More cart recipes
These examples use the same cart instance as above. Values such as variant IDs and selling-plan IDs must come from your actual theme selection. Await the result, check userErrors and warnings, and catch rejected requests.
Add several items together
await cart.add([
{ merchandiseId: firstVariantId, quantity: 1 },
{
merchandiseId: secondVariantId,
quantity: 2,
attributes: [{ key: 'Gift wrap', value: 'Yes' }]
}
], { context: 'product' })
This is a multi-line add, not a bundle definition. Shopify remains responsible for product availability, pricing, and any cart transforms.
Add a subscription selection
await cart.add({
merchandiseId: variantId,
quantity: 1,
sellingPlanId: selectedSellingPlanId,
attributes: [{ key: 'Gift wrap', value: 'Yes' }]
}, { context: 'product' })
The selling plan must be valid for the selected variant. Use sellingPlanId, not the Ajax API’s selling_plan. The plugin does not choose a plan, calculate subscription prices, or validate purchase eligibility locally.
Save a cart-level gift message
await cart.setNote(giftMessage.trim())
// Clear the cart note.
await cart.setNote('')
A note belongs to the whole cart. For a message attached to one item, use a line attribute instead.
Save cart-level attributes
await cart.setAttributes([
...existingCartAttributes.filter(attribute => attribute.key !== 'Delivery date'),
{ key: 'Delivery date', value: deliveryDate }
])
existingCartAttributes must be hydrated by your theme or another data source. $cart.attributes starts undefined and is not a complete initial snapshot. Passing a partial set can remove attributes you did not intend to change.
Apply and remove a discount code
const codes = [...new Set([
...cart.discountCodes.map(discount => discount.code),
discountCode.trim()
])]
const result = await cart.setDiscountCodes(codes)
if (result.userErrors?.length) {
showMessage(result.userErrors[0].message)
} else if (result.cart?.discountCodes.some(discount => !discount.applicable)) {
showMessage('One or more codes do not apply to this cart.')
} else if (result.warnings?.length) {
showMessage(result.warnings[0].message)
}
Validate that the entered code is non-empty before submitting. showMessage() represents your theme’s feedback UI. A resolved request does not mean every requested code is applicable.
await cart.setDiscountCodes(
cart.discountCodes
.filter(discount => discount.code !== codeToRemove)
.map(discount => discount.code)
)
Combine line properties and a cart note
await cart.mutate({
lines: [{
id: line.id,
quantity: line.quantity,
attributes: [{ key: 'Gift wrap', value: 'Yes' }]
}],
note: giftMessage
}, { context: 'cart' })
Here the nested lines[].attributes belongs to one line, while note belongs to the cart. A root-level attributes field would replace cart attributes. This example intentionally replaces the line’s properties; include other properties you need to retain.
Remove several lines
await cart.remove(selectedLineIds, { context: 'cart' })
Use current line IDs from $cart.lines, and pass only the lines the buyer selected. Removing items is a real cart mutation, not a local UI change.
Receive cart updates
The plugin subscribes to standard events on document. Event properties live directly on the event, including its result promise; they are not all nested under event.detail.
document.addEventListener('shopify:cart:lines-update', event => {
event.promise.then(({ cart, userErrors, warnings }) => {
// Inspect the settled result, not just the initial event.
console.log(cart?.totalQuantity, userErrors, warnings)
}).catch(error => {
console.error(error)
})
})
| Event | Behavior |
|---|---|
shopify:cart:lines-update | Add, update, or remove operation; waits for event.promise. |
shopify:cart:note-update | Retains the requested note after a successful result. |
shopify:cart:attributes-update | Retains attributes after a successful result. |
shopify:cart:discount-update | Reconciles discount codes from the returned cart. |
shopify:cart:error | Records a request failure. |
shopify:cart:view | Reads the cart supplied by the view event. |
Shopify.actions.updateCart() emits its own events. Do not dispatch an additional cart event after using $cart. The plugin tags its own calls to avoid counting them twice.
Changes made outside standard actions are observable only if the theme or app emits the standard events. This plugin does not intercept fetch, poll the cart, or watch arbitrary markup.
Not an analytics channel. These storefront events do not establish tracking consent. Use Shopify Web Pixels for consent-aware analytics.
Handle errors without guessing
There are three distinct outcomes. A rejected promise represents a failed request. userErrors describes a mutation Shopify declined. warnings describes a change that succeeded with an adjustment.
Alpine.data('productForm', variantId => ({
variantId,
message: '',
async add() {
this.message = ''
try {
const result = await this.$cart.add({
merchandiseId: this.variantId,
quantity: 1
})
if (result.userErrors?.length) {
this.message = result.userErrors[0].message
return
}
this.message = result.warnings?.[0]?.message ?? 'Added to cart.'
} catch (error) {
this.message = error.message ?? 'Could not update the cart. Try again.'
}
}
}))
Register this provider before starting Alpine. Wire a button to add(), disable it with $cart.pending, and render message in a live region. The store also records rejected errors; explicit method callers must still handle promise rejection.
Let the theme own the UI
$cart.open() calls Shopify.actions.openCart(). Depending on the theme, that opens a drawer or navigates to the cart page. There is no plugin-owned open state or close method.
Standard actions can reload the page. Shopify’s default update behavior may reload when it cannot recognize the theme’s cart UI. A reactive magic alone does not disable that fallback.
For an in-place experience, the theme must configure an appropriate updateCart handler and event target. Configure a theme-specific openCart handler if needed. This plugin intentionally does not claim those configurations.
Use Shopify’s action configuration reference. Only the first configuration takes effect. Test the actual theme, not just a mocked API, and do not assume wrapping a default handler suppresses its reload.
Lifecycle and limits
The store and its document listeners belong to the page, not to an individual Alpine component. Removing one cart widget must not disconnect other widgets. Register the plugin once before Alpine initializes.
const cart = Alpine.store('shopifyCart')
await cart.refresh()
// Only at application teardown, not when one widget unmounts.
cart.dispose()
dispose() removes listeners, cancels initialization, rejects new calls, and skips queued calls that have not started. Late results cannot update the disposed store. It is terminal, not a restart API. It does not abort requests already sent or undo server-side mutations.
The plugin queues local calls and uses local revisions to reject older results. Standard events do not carry a global server revision, so this is not a guarantee against every race involving unrelated scripts. Test overlapping updates in your integration.
- No built-in checkout, product selector, currency formatter, or cart drawer.
- No cross-tab synchronization or legacy Ajax API fallback.
- Notes and attributes are unknown until observed; the standard summary does not hydrate them.
- Use
$cart.linesrather than depending on a single raw line shape.
Go to the source
- Source code and issues
- TypeScript declarations
- Live-store compatibility fixes
- Shopify standard storefront events and actions
- Alpine plugin authoring
Before shipping a theme integration, run Shopify CLI with the standard events inspector and exercise real cart operations, failure paths, and your theme’s cart presentation.
shopify theme dev --standard-events-inspector