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 createHydrogenContext
Anchor link to section titled "Step 1: Create a cart instance with createHydrogenContext"Hydrogen uses createHydrogenContext
to setup a common set of contexts, which includes cart context, that you will need in your Remix loaders and actions.
Create a context.(js|ts)
file. This file should manage all the context that you want to show up in the Remix context.
Step 2: Include the app context in the server.(js|ts)
Anchor link to section titled "Step 2: Include the app context in the server.(js|ts)"In your server.(js|ts)
file, include your appLoadContext
inside the Remix request handler.
If you're using Typescript, then add the return type of createAppLoadContext
type to env.d.ts
to have a type association.
Step 3: Decide how you want to manage the cart ID
Anchor link to section titled "Step 3: 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.