medusa-cart-logic
v1.0.0
Published
React hook and helpers for Medusa Store cart (line items, promotions, cookie credentials).
Readme
medusa-cart-logic
Reusable cart hook logic for Medusa storefronts.
This package exposes useCart and Medusa cart helpers used by cart flows:
- cart create/retrieve/update
- line items (add/update/remove)
- promotions/coupons (apply/remove)
- totals + items state for cart UI
- guest/customer cookie session support via
credentials: "include"
Installation
npm installFor local development in this monorepo:
npm run buildExports
From src/index.ts:
useCarthook- cart service helpers from
medusa-services/cart
Quick Usage
import { useCart } from "medusa-cart-logic"
const cart = useCart({
backendUrl: "https://your-medusa-server.com",
publishableApiKey: "pk_...",
cartId, // from localStorage/session/app state
onCartIdChange: (nextId) => {
setCartId(nextId)
if (nextId) localStorage.setItem("cart_id", nextId)
},
credentials: "include",
})
await cart.ensureCart()
await cart.addLineItem({ variant_id: "variant_123", quantity: 1 })
await cart.applyPromotions(["SUMMER10"])useCart Input
backendUrl: Medusa backend URLpublishableApiKey: Medusa publishable keycartId: current cart id (nullable)onCartIdChange: callback whencreateCartreturns a new idauthorization: optional customer JWT (Bearerprefix optional)credentials: request credentials mode (defaults to"include")fields: optional Medusa Storefieldsquery overrideenabled: controls auto refresh behavior (defaulttrue)
Returned API
- State:
cartloadingmutatingerror
- Actions:
refreshcreateCartensureCartupdateCartaddLineItemupdateLineItemremoveLineItemapplyPromotionsremovePromotionsclearError
Medusa Guest Cart Notes
- Browser JavaScript cannot read HttpOnly cookies like
_medusa_cart_id. - Keep your own
cartIdreference (for example in localStorage, session state, or server session). - Always send cart requests with
credentials: "include"so cookie-backed session/cart behavior works across requests.
Notes
- This package is UI-agnostic and focuses only on cart logic/state transitions.
- Use your own UI components for list rendering, quantity controls, coupon input, and checkout CTA.
