Set up a cart handler
This guide shows you how to set up a cart handler inside your Hydrogen app. This makes a dynamic cart
object available on all requests, so it can be read and updated by Remix actions and loaders.
Requirements
Anchor link to section titled "Requirements"- You've completed the quickstart guide.
Step 1: Create a cart
instance with createCartHandler
Anchor link to section titled "Step 1: Create a cart instance with createCartHandler"The createCartHandler
function returns an object instance for you to interact with Storefront API cart queries. It allows you to easily interact with the cart.
In your server.(js|ts)
file, create your cart handler inside the server fetch handler.
Next, pass your cart
instance to the getLoadContext
function.
If you're using Typescript, then add the HydrogenCart
type to remix.env.d.ts
to have a type association.
Step 2: Decide how you want to manage the cart ID
Anchor link to section titled "Step 2: Decide how you want to manage the cart ID"Hydrogen provides the following default methods for getting and setting a cart ID:
cartGetIdDefault(requestHeaders: Headers)
: Retrieves the cart ID from the request header cookie. The cookie name must becart
.cartSetIdDefault()
: Returns a function that accepts a new cart ID and sets a cookie calledcart=<new_cart_id>
in the returnedHeaders
object. By default,cartSetIdDefault()
sets a session cookie. This means the cookie disappears when the user closes the browser.
Update cookie settings by passing an options object to the cartSetIdDefault
function. This options object accepts the same attribute types provided by the cookie-parsing interface from the Worktop package dependency.
- Learn how to read data from a cart
- Learn how to customize your own cart handler.