Skip to main content

createCartHandler
utility

Creates an API that can be used to interact with the cart.

Anchor to createcarthandler(options)createCartHandler(options)

() => string
required

A function that returns the cart id in the form of gid://shopify/Cart/c1-123.

(cartId: string) =>
required

A function that sets the cart ID.

required

The storefront client instance created by createStorefrontClient.

string

The cart mutation fragment used in most mutation requests, except for setMetafields and deleteMetafield. See the example usage in the documentation.

string

The cart query fragment used by cart.get(). See the example usage in the documentation.

TCustomMethods

Define custom methods or override existing methods for your cart API instance. See the example usage in the documentation.

Was this section helpful?

The handler returns the following default methods. Any custom or overwritten methods will also be available in the returned cart instance.

Anchor to addDeliveryAddresses
addDeliveryAddresses

Adds a delivery address to the cart.

Adds items to the cart. If the cart doesn't exist, a new one will be created.

Creates a new cart.

Removes a custom field (metafield) from the cart.

Retrieves the cart information.

() => string

Retrieves the unique identifier of the cart. By default, it gets the ID from the request cookie.

Anchor to removeDeliveryAddresses
removeDeliveryAddresses

Removes a delivery address from the cart

Removes items from the cart.

(cartId: string) =>

Sets the unique identifier of the cart. By default, it sets the ID in the header cookie.

Adds extra information (metafields) to the cart. If the cart doesn't exist, a new one will be created.

Updates additional information (attributes) in the cart.

Updates the buyer's information in the cart. If the cart doesn't exist, a new one will be created.

Anchor to updateDeliveryAddresses
updateDeliveryAddresses

Update cart delivery addresses.

Updates discount codes in the cart.

Updates gift card codes in the cart.

Updates items in the cart.

Updates the note in the cart. If the cart doesn't exist, a new one will be created.

Anchor to updateSelectedDeliveryOption
updateSelectedDeliveryOption

Updates the selected delivery options in the cart. Only available for carts associated with a customer access token.

Was this section helpful?

Server.(js|ts)

import {
createStorefrontClient,
createCartHandler,
cartGetIdDefault,
cartSetIdDefault,
} from '@shopify/hydrogen';
// @ts-expect-error
import * as reactRouterBuild from 'virtual:react-router/server-build';
import {
createRequestHandler,
getStorefrontHeaders,
} from '@shopify/remix-oxygen';

export default {
async fetch(request, env, executionContext) {
const {storefront} = createStorefrontClient({
/* client parameters */
});

// Create a cart api instance.
const cart = createCartHandler({
storefront,
getCartId: cartGetIdDefault(request.headers),
setCartId: cartSetIdDefault(),
});

const handleRequest = createRequestHandler({
build: reactRouterBuild,
mode: process.env.NODE_ENV,
getLoadContext: () => ({
storefront,
cart, // Pass the cart api instance to the loader context.
}),
});

return await handleRequest(request);
},
};

Examples of various ways to use the createCartHandler utility.

Use cartQueryFragment and cartMutateFragment to change the cart data the queries will return.

Was this section helpful?

Example

JavaScript

import {
createCartHandler,
cartGetIdDefault,
cartSetIdDefault,
} from '@shopify/hydrogen';

// Override cart fragments
const cart = createCartHandler({
storefront,
getCartId: cartGetIdDefault(request.headers),
setCartId: cartSetIdDefault(),
cartQueryFragment: CART_QUERY_FRAGMENT,
cartMutateFragment: CART_MUTATE_FRAGMENT,
});

// cartQueryFragment requirements:
// - Must be named `CartApiQuery`
// - Only have access to the following query variables:
// - $cartId: ID!
// - $country: CountryCode
// - $language: LanguageCode
// - $numCartLines: Int
const CART_QUERY_FRAGMENT = `#graphql
fragment CartApiQuery on Cart {
id
totalQuantity
checkoutUrl
note
}
`;

// cartMutateFragment requirements:
// - Must be named `CartApiMutation`
// - Only have access to the following query variables:
// - $cartId: ID!
// - $country: CountryCode
// - $language: LanguageCode
const CART_MUTATE_FRAGMENT = `#graphql
fragment CartApiMutation on Cart {
id
totalQuantity
checkoutUrl
lines(first: 100) {
edges {
node {
id
quantity
}
}
}
}
`;

Define or override methods in your cart handler instance. Note that for addLines, updateDiscountCodes, updateBuyerIdentity, updateNote, updateAttributes, and setMetafields, if you override any of these methods, a new cart will not be created unless you implement the cart creation logic in your overriding method.

Was this section helpful?

Example

JavaScript

import {
createCartHandler,
cartGetIdDefault,
cartSetIdDefault,
cartLinesAddDefault,
cartLinesRemoveDefault,
} from '@shopify/hydrogen';

const cartQueryOptions = {
storefront,
getCartId: cartGetIdDefault(request.headers),
};

const getCartId = cartGetIdDefault(request.headers);

const cart = createCartHandler({
storefront,
getCartId,
setCartId: cartSetIdDefault(),
customMethods: {
editInLine: async (addLines, removeLineIds, optionalParams) => {
// Using Hydrogen default cart query methods
await cartLinesAddDefault(cartQueryOptions)(addLines, optionalParams);
return await cartLinesRemoveDefault(cartQueryOptions)(
removeLineIds,
optionalParams,
);
},
addLines: async (lines, optionalParams) => {
// With your own Storefront API graphql query
return await storefront.mutate(CART_LINES_ADD_MUTATION, {
variables: {
id: optionalParams.cartId || getCartId(),
lines,
},
});
},
},
});

// Use custom method editInLine that delete and add items in one method
cart.editInLine(
['123'],
[
{
merchandiseId: 'gid://shopify/ProductVariant/456789123',
quantity: 1,
},
],
);

// Use overridden cart.addLines
const result = await cart.addLines(
[
{
merchandiseId: 'gid://shopify/ProductVariant/123456789',
quantity: 1,
},
],
{
cartId: 'c-123',
},
);
// Output of result:
// {
// cartLinesAdd: {
// cart: {
// id: 'c-123',
// totalQuantity: 1
// },
// errors: []
// }
// }

const CART_LINES_ADD_MUTATION = `#graphql
mutation CartLinesAdd(
$cartId: ID!
$lines: [CartLineInput!]!
$country: CountryCode = ZZ
$language: LanguageCode
) @inContext(country: $country, language: $language) {
cartLinesAdd(cartId: $cartId, lines: $lines) {
cart {
id
totalQuantity
}
errors: userErrors {
message
field
code
}
}
}
`;

Add items to the cart. If the cart does not exist, a new cart will be created.

Create a new cart.

Delete extra information (metafield) from the cart.

Retrieve the cart information.

Get the unique identifier of the cart.

Remove items from the cart.

Set the unique identifier of the cart.

Add extra information (metafields) to the cart. If the cart does not exist, a new cart will be created.

Update additional information (attributes) in the cart. If the cart does not exist, a new cart will be created.

Update the buyer’s information in the cart. If the cart does not exist, a new cart will be created.

Update discount codes in the cart.

Update gift card codes in the cart.

Update items in the cart.

Update the note in the cart. If the cart does not exist, a new cart will be created.

Update the selected delivery options in the cart. Only available for carts associated with a customer access token.

Was this section helpful?

Cart.addLines

JavaScript

export async function action({context}) {
const {cart} = context;

// Usage
const result = await cart.addLines(
[
{
merchandiseId: 'gid://shopify/ProductVariant/123456789',
quantity: 1,
},
],
// Optional parameters
{
cartId: '123', // override the cart id
country: 'US', // override the country code to 'US'
language: 'EN', // override the language code to 'EN'
},
);
}

// Output of result:
// {
// cart: {
// id: 'c1-123',
// totalQuantity: 1
// },
// errors: []
// }