--- title: createCartHandler description: Creates an API that can be used to interact with the cart. api_version: 2025-07 api_name: hydrogen source_url: html: https://shopify.dev/docs/api/hydrogen/latest/utilities/createcarthandler md: https://shopify.dev/docs/api/hydrogen/latest/utilities/createcarthandler.md --- # create​Cart​Handler Creates an API that can be used to interact with the cart. ## createCartHandler(options) * getCartId () => string required A function that returns the cart id in the form of `gid://shopify/Cart/c1-123`. * setCartId (cartId: string) => Headers required A function that sets the cart ID. * storefront Storefront required The storefront client instance created by [`createStorefrontClient`](docs/api/hydrogen/utilities/createstorefrontclient). * buyerIdentity CartBuyerIdentityInput Buyer identity. Default buyer identity is passed to cartCreate. * cartMutateFragment string The cart mutation fragment used in most mutation requests, except for `setMetafields` and `deleteMetafield`. See the [example usage](https://shopify.dev/docs/api/hydrogen/utilities/createcarthandler#example-cart-fragments) in the documentation. * cartQueryFragment string The cart query fragment used by `cart.get()`. See the [example usage](https://shopify.dev/docs/api/hydrogen/utilities/createcarthandler#example-cart-fragments) in the documentation. * customMethods TCustomMethods Define custom methods or override existing methods for your cart API instance. See the [example usage](https://shopify.dev/docs/api/hydrogen/utilities/createcarthandler#example-custom-methods) in the documentation. ### CartBuyerIdentityInput ```ts CartBuyerIdentityInput ``` ### Headers ```ts Headers ``` ### Storefront Interface to interact with the Storefront API. * cache ```ts Cache ``` * CacheCustom ```ts (overrideOptions: AllCacheOptions) => AllCacheOptions ``` * CacheLong ```ts (overrideOptions?: AllCacheOptions) => AllCacheOptions ``` * CacheNone ```ts () => NoStoreStrategy ``` * CacheShort ```ts (overrideOptions?: AllCacheOptions) => AllCacheOptions ``` * generateCacheControlHeader ```ts (cacheOptions: AllCacheOptions) => string ``` * getApiUrl ```ts any ``` * getPrivateTokenHeaders ```ts any ``` * getPublicTokenHeaders ```ts any ``` * getShopifyDomain ```ts any ``` * i18n ```ts TI18n ``` * mutate ```ts (mutation: RawGqlString, ...options: ClientVariablesInRestParams) => Promise ``` * query ```ts (query: RawGqlString, ...options: ClientVariablesInRestParams, AutoAddedVariableNames>) => Promise ``` ```ts { query: < OverrideReturnType extends any = never, RawGqlString extends string = string, >( query: RawGqlString, ...options: ClientVariablesInRestParams< StorefrontQueries, RawGqlString, StorefrontCommonExtraParams & Pick, AutoAddedVariableNames > ) => Promise< ClientReturn & StorefrontError >; mutate: < OverrideReturnType extends any = never, RawGqlString extends string = string, >( mutation: RawGqlString, ...options: ClientVariablesInRestParams< StorefrontMutations, RawGqlString, StorefrontCommonExtraParams, AutoAddedVariableNames > ) => Promise< ClientReturn & StorefrontError >; cache?: Cache; CacheNone: typeof CacheNone; CacheLong: typeof CacheLong; CacheShort: typeof CacheShort; CacheCustom: typeof CacheCustom; generateCacheControlHeader: typeof generateCacheControlHeader; getPublicTokenHeaders: ReturnType< typeof createStorefrontUtilities >['getPublicTokenHeaders']; getPrivateTokenHeaders: ReturnType< typeof createStorefrontUtilities >['getPrivateTokenHeaders']; getShopifyDomain: ReturnType< typeof createStorefrontUtilities >['getShopifyDomain']; getApiUrl: ReturnType< typeof createStorefrontUtilities >['getStorefrontApiUrl']; i18n: TI18n; } ``` ### AllCacheOptions Override options for a cache strategy. * maxAge The maximum amount of time in seconds that a resource will be considered fresh. See \`max-age\` in the \[MDN docs]\(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#:\~:text=Response%20Directives-,max%2Dage,-The%20max%2Dage). ```ts number ``` * mode The caching mode, generally \`public\`, \`private\`, or \`no-store\`. ```ts string ``` * sMaxAge Similar to \`maxAge\` but specific to shared caches. See \`s-maxage\` in the \[MDN docs]\(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#s-maxage). ```ts number ``` * staleIfError Indicate that the cache should serve the stale response if an error occurs while revalidating the cache. See \`stale-if-error\` in the \[MDN docs]\(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-if-error). ```ts number ``` * staleWhileRevalidate Indicate that the cache should serve the stale response in the background while revalidating the cache. See \`stale-while-revalidate\` in the \[MDN docs]\(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-while-revalidate). ```ts number ``` ```ts export interface AllCacheOptions { /** * The caching mode, generally `public`, `private`, or `no-store`. */ mode?: string; /** * The maximum amount of time in seconds that a resource will be considered fresh. See `max-age` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#:~:text=Response%20Directives-,max%2Dage,-The%20max%2Dage). */ maxAge?: number; /** * Indicate that the cache should serve the stale response in the background while revalidating the cache. See `stale-while-revalidate` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-while-revalidate). */ staleWhileRevalidate?: number; /** * Similar to `maxAge` but specific to shared caches. See `s-maxage` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#s-maxage). */ sMaxAge?: number; /** * Indicate that the cache should serve the stale response if an error occurs while revalidating the cache. See `stale-if-error` in the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-if-error). */ staleIfError?: number; } ``` ### NoStoreStrategy * mode ```ts string ``` ```ts { mode: string; } ``` ### StorefrontMutations Maps all the mutations found in the project to variables and return types. ```ts export interface StorefrontMutations { // Example of how a generated mutation type looks like: // '#graphql mutation m1 {...}': {return: M1Mutation; variables: M1MutationVariables}; } ``` ### StorefrontCommonExtraParams * displayName ```ts string ``` * headers ```ts HeadersInit ``` * storefrontApiVersion ```ts string ``` ```ts { headers?: HeadersInit; storefrontApiVersion?: string; displayName?: string; } ``` ### AutoAddedVariableNames ```ts 'country' | 'language' ``` ### StorefrontQueries Maps all the queries found in the project to variables and return types. ```ts export interface StorefrontQueries { // Example of how a generated query type looks like: // '#graphql query q1 {...}': {return: Q1Query; variables: Q1QueryVariables}; } ``` ### StorefrontQueryOptions ```ts StorefrontCommonExtraParams & { query: string; mutation?: never; cache?: CachingStrategy; } ``` ### CachingStrategy Use the \`CachingStrategy\` to define a custom caching mechanism for your data. Or use one of the pre-defined caching strategies: CacheNone, CacheShort, CacheLong. * maxAge The maximum amount of time in seconds that a resource will be considered fresh. See \`max-age\` in the \[MDN docs]\(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#:\~:text=Response%20Directives-,max%2Dage,-The%20max%2Dage). ```ts number ``` * mode The caching mode, generally \`public\`, \`private\`, or \`no-store\`. ```ts string ``` * sMaxAge Similar to \`maxAge\` but specific to shared caches. See \`s-maxage\` in the \[MDN docs]\(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#s-maxage). ```ts number ``` * staleIfError Indicate that the cache should serve the stale response if an error occurs while revalidating the cache. See \`stale-if-error\` in the \[MDN docs]\(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-if-error). ```ts number ``` * staleWhileRevalidate Indicate that the cache should serve the stale response in the background while revalidating the cache. See \`stale-while-revalidate\` in the \[MDN docs]\(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#stale-while-revalidate). ```ts number ``` ```ts AllCacheOptions ``` ## Returns The handler returns the following default methods. Any [custom](https://shopify.dev/docs/api/hydrogen/utilities/createcarthandler#example-custom-methods) or overwritten methods will also be available in the returned cart instance. * addDeliveryAddresses CartDeliveryAddressesAddFunction Adds a delivery address to the cart. * addLines CartLinesAddFunction Adds items to the cart. If the cart doesn't exist, a new one will be created. * create CartCreateFunction Creates a new cart. * deleteMetafield CartMetafieldDeleteFunction Removes a custom field (metafield) from the cart. * get CartGetFunction Retrieves the cart information. * getCartId () => string Retrieves the unique identifier of the cart. By default, it gets the ID from the request cookie. * removeDeliveryAddresses CartDeliveryAddressesRemoveFunction Removes a delivery address from the cart * removeGiftCardCodes CartGiftCardCodesRemoveFunction Removes gift card codes from the cart. * removeLines CartLinesRemoveFunction Removes items from the cart. * setCartId (cartId: string) => Headers Sets the unique identifier of the cart. By default, it sets the ID in the header cookie. * setMetafields CartMetafieldsSetFunction Adds extra information (metafields) to the cart. If the cart doesn't exist, a new one will be created. * updateAttributes CartAttributesUpdateFunction Updates additional information (attributes) in the cart. * updateBuyerIdentity CartBuyerIdentityUpdateFunction Updates the buyer's information in the cart. If the cart doesn't exist, a new one will be created. * updateDeliveryAddresses CartDeliveryAddressesUpdateFunction Update cart delivery addresses. * updateDiscountCodes CartDiscountCodesUpdateFunction Updates discount codes in the cart. * updateGiftCardCodes CartGiftCardCodesUpdateFunction Updates gift card codes in the cart. * updateLines CartLinesUpdateFunction Updates items in the cart. * updateNote CartNoteUpdateFunction Updates the note in the cart. If the cart doesn't exist, a new one will be created. * updateSelectedDeliveryOption CartSelectedDeliveryOptionsUpdateFunction Updates the selected delivery options in the cart. Only available for carts associated with a customer access token. ### CartDeliveryAddressesAddFunction * addresses ```ts CartSelectableAddressInput[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartDeliveryAddressesAddFunction = ( addresses: Array, optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartOptionalInput * cartId The cart id. ```ts Scalars ``` * country The country code. ```ts CountryCode ``` * language The language code. ```ts LanguageCode ``` ```ts { /** * The cart id. * @default cart.getCartId(); */ cartId?: Scalars['ID']['input']; /** * The country code. * @default storefront.i18n.country */ country?: CountryCode; /** * The language code. * @default storefront.i18n.language */ language?: LanguageCode; } ``` ### CartQueryDataReturn ```ts CartQueryData & { errors?: StorefrontApiErrors; } ``` ### CartQueryData * cart ```ts Cart ``` * userErrors ```ts | CartUserError[] | MetafieldsSetUserError[] | MetafieldDeleteUserError[] ``` * warnings ```ts CartWarning[] ``` ```ts { cart: Cart; userErrors?: | CartUserError[] | MetafieldsSetUserError[] | MetafieldDeleteUserError[]; warnings?: CartWarning[]; } ``` ### Cart ```ts Cart ``` ### CartUserError ```ts CartUserError ``` ### MetafieldsSetUserError ```ts MetafieldsSetUserError ``` ### MetafieldDeleteUserError ```ts MetafieldDeleteUserError ``` ### CartWarning ```ts CartWarning ``` ### StorefrontApiErrors ```ts JsonGraphQLError[] | undefined ``` ### JsonGraphQLError ```ts ReturnType ``` ### CartLinesAddFunction * lines ```ts CartLineInput[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartLinesAddFunction = ( lines: Array, optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartLineInput ```ts CartLineInput ``` ### CartCreateFunction * input ```ts CartInput ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartCreateFunction = ( input: CartInput, optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartInput ```ts CartInput ``` ### CartMetafieldDeleteFunction * key ```ts Scalars ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartMetafieldDeleteFunction = ( key: Scalars['String']['input'], optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartGetFunction * cartInput ```ts CartGetProps ``` Promise\ ```ts Promise ``` ```ts export type CartGetFunction = ( cartInput?: CartGetProps, ) => Promise; ``` ### CartGetProps * cartId The cart ID. ```ts string ``` * country The country code. ```ts CountryCode ``` * language The language code. ```ts LanguageCode ``` * numCartLines The number of cart lines to be returned. ```ts number ``` ```ts { /** * The cart ID. * @default cart.getCartId(); */ cartId?: string; /** * The country code. * @default storefront.i18n.country */ country?: CountryCode; /** * The language code. * @default storefront.i18n.language */ language?: LanguageCode; /** * The number of cart lines to be returned. * @default 100 */ numCartLines?: number; } ``` ### CartReturn ```ts Cart & { errors?: StorefrontApiErrors; } ``` ### CartDeliveryAddressesRemoveFunction * addressIds ```ts string[] | Scalars[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartDeliveryAddressesRemoveFunction = ( addressIds: Array | Array, optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartGiftCardCodesRemoveFunction * appliedGiftCardIds ```ts string[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartGiftCardCodesRemoveFunction = ( appliedGiftCardIds: string[], optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartLinesRemoveFunction * lineIds ```ts string[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartLinesRemoveFunction = ( lineIds: string[], optionalParams?: CartOptionalInput, ) => Promise; ``` ### Headers ```ts Headers ``` ### CartMetafieldsSetFunction * metafields ```ts MetafieldWithoutOwnerId[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartMetafieldsSetFunction = ( metafields: MetafieldWithoutOwnerId[], optionalParams?: CartOptionalInput, ) => Promise; ``` ### MetafieldWithoutOwnerId ```ts MetafieldWithoutOwnerId ``` ### CartAttributesUpdateFunction * attributes ```ts AttributeInput[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartAttributesUpdateFunction = ( attributes: AttributeInput[], optionalParams?: CartOptionalInput, ) => Promise; ``` ### AttributeInput ```ts AttributeInput ``` ### CartBuyerIdentityUpdateFunction * buyerIdentity ```ts CartBuyerIdentityInput ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartBuyerIdentityUpdateFunction = ( buyerIdentity: CartBuyerIdentityInput, optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartBuyerIdentityInput ```ts CartBuyerIdentityInput ``` ### CartDeliveryAddressesUpdateFunction * addresses ```ts CartSelectableAddressUpdateInput[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartDeliveryAddressesUpdateFunction = ( addresses: Array, optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartDiscountCodesUpdateFunction * discountCodes ```ts string[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartDiscountCodesUpdateFunction = ( discountCodes: string[], optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartGiftCardCodesUpdateFunction * giftCardCodes ```ts string[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartGiftCardCodesUpdateFunction = ( giftCardCodes: string[], optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartLinesUpdateFunction * lines ```ts CartLineUpdateInput[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartLinesUpdateFunction = ( lines: CartLineUpdateInput[], optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartLineUpdateInput ```ts CartLineUpdateInput ``` ### CartNoteUpdateFunction * note ```ts string ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartNoteUpdateFunction = ( note: string, optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartSelectedDeliveryOptionsUpdateFunction * selectedDeliveryOptions ```ts CartSelectedDeliveryOptionInput[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ```ts export type CartSelectedDeliveryOptionsUpdateFunction = ( selectedDeliveryOptions: CartSelectedDeliveryOptionInput[], optionalParams?: CartOptionalInput, ) => Promise; ``` ### CartSelectedDeliveryOptionInput ```ts CartSelectedDeliveryOptionInput ``` ### Examples * #### server.(js|ts) ##### Description This is the default example ##### JavaScript ```js 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); }, }; ``` ##### TypeScript ```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: Request, env: Record, executionContext: ExecutionContext, ): Promise { 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 Examples of various ways to use the `createCartHandler` utility. ### Cart fragments ### Examples * #### Example ##### Description Use \`cartQueryFragment\` and \`cartMutateFragment\` to change the cart data the queries will return. ##### JavaScript ```js 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 } } } } `; ``` ### Custom methods ### Examples * #### Example ##### Description 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. ##### JavaScript ```js 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 } } } `; ``` ### Cart instance usage ### Examples * #### cart.addLines ##### Description Add items to the cart. If the cart does not exist, a new cart will be created. ##### JavaScript ```js 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: [] // } ``` * #### cart.create ##### Description Create a new cart. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.create( { lines: [ { merchandiseId: 'gid://shopify/ProductVariant/123456789', quantity: 1, }, ], discountCodes: ['FREE_SHIPPING'], }, // 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, // discountCodes: [{ code: 'FREE_SHIPPING'}] // }, // errors: [] // } } ``` * #### cart.deleteMetafield ##### Description Delete extra information (metafield) from the cart. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.setMetafields( [ { key: 'custom.gift', type: 'boolean', value: 'true', }, ], // Optional parameters { cartId: '123', // override the cart id }, ); const result2 = await cart.deleteMetafield( 'custom.gift', // Optional parameters { cartId: '123', // override the cart id }, ); } // server.js // To query for metafields, use the `cartQueryFragment` option when creating the cart handler. import { createCartHandler, cartGetIdDefault, cartSetIdDefault, } from '@shopify/hydrogen'; const cart = createCartHandler({ storefront, getCartId: cartGetIdDefault(request.headers), setCartId: cartSetIdDefault(), cartQueryFragment: CART_QUERY_FRAGMENT, }); const CART_QUERY_FRAGMENT = `#graphql fragment CartApiQuery on Cart { id metafields( identifiers: [{ namespace: "custom", key: "gift" ]) { namespace key type value } } `; ``` * #### cart.get ##### Description Retrieve the cart information. ##### JavaScript ```js export async function loader({context}) { const {cart} = context; // Usage const result = await cart.get(); // Optional parameters const result2 = await cart.get({ cartId: '123', // override the cart id numCartLines: 50, //override to return 50 cart lines country: 'US', // override the country code to 'US' language: 'EN', // override the language code to 'EN' }); } ``` * #### cart.getCartId ##### Description Get the unique identifier of the cart. ##### JavaScript ```js export async function loader({context}) { // Usage context.cart.getCartId(); // 'gid://shopify/Cart/123' } ``` * #### cart.removeLines ##### Description Remove items from the cart. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.removeLines( ['123'], // 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: 0 // }, // errors: [] // } } ``` * #### cart.setCartId ##### Description Set the unique identifier of the cart. ##### JavaScript ```js export async function action({context}) { const {cart} = context; const result = await cart.addLines([ { merchandiseId: 'gid://shopify/ProductVariant/123456789', quantity: 1, }, ]); // Usage const headers = cart.setCartId(result.cart.id); } ``` * #### cart.setMetafields ##### Description Add extra information (metafields) to the cart. If the cart does not exist, a new cart will be created. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.setMetafields( [ { key: 'custom.gift', type: 'boolean', value: 'true', }, ], // Optional parameters { cartId: '123', // override the cart id }, ); const result2 = await cart.deleteMetafield( 'custom.gift', // Optional parameters { cartId: '123', // override the cart id }, ); } // server.js // To query for metafields, use the `cartQueryFragment` option when creating the cart handler. import { createCartHandler, cartGetIdDefault, cartSetIdDefault, } from '@shopify/hydrogen'; const cart = createCartHandler({ storefront, getCartId: cartGetIdDefault(request.headers), setCartId: cartSetIdDefault(), cartQueryFragment: CART_QUERY_FRAGMENT, }); const CART_QUERY_FRAGMENT = `#graphql fragment CartApiQuery on Cart { id metafields( identifiers: [{ namespace: "custom", key: "gift" ]) { namespace key type value } } `; ``` * #### cart.updateAttributes ##### Description Update additional information (attributes) in the cart. If the cart does not exist, a new cart will be created. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.updateAttributes( [ { key: 'Somekey', value: '1', }, ], // Optional parameters { cartId: '123', // override the cart id }, ); // Output of result: // { // cart: { // id: 'c1-123', // totalQuantity: 1 // }, // errors: [] // } } ``` * #### cart.updateBuyerIdentity ##### Description Update the buyer’s information in the cart. If the cart does not exist, a new cart will be created. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.updateBuyerIdentity( { customerAccessToken: '123', }, // 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: [] // } } ``` * #### cart.updateDiscountCodes ##### Description Update discount codes in the cart. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.updateDiscountCodes( ['FREE_SHIPPING'], // 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: [] // } } ``` * #### cart.updateGiftCardCodes ##### Description Update gift card codes in the cart. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.updateGiftCardCodes( ['ABC123'], // 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', // appliedGiftCards: [{ // lastCharacters: 'C123', // amountUsed: { // amount: 10, // currencyCode: 'USD', // } // }], // }, // errors: [] // } } ``` * #### cart.updateLines ##### Description Update items in the cart. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.updateLines( [ { merchandiseId: 'gid://shopify/ProductVariant/123456789', quantity: 2, }, ], // 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: 2 // }, // errors: [] // } } ``` * #### cart.updateNote ##### Description Update the note in the cart. If the cart does not exist, a new cart will be created. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.updateNote( 'Some notes', // Optional parameters { cartId: '123', // override the cart id }, ); // Output of result: // { // cart: { // id: 'c1-123', // totalQuantity: 0 // }, // errors: [] // } } ``` * #### cart.updateSelectedDeliveryOptions ##### Description Update the selected delivery options in the cart. Only available for carts associated with a customer access token. ##### JavaScript ```js export async function action({context}) { const {cart} = context; // Usage const result = await cart.updateSelectedDeliveryOptions( [ { deliveryGroupId: '123', deliveryOptionHandle: 'Canada Post', }, ], // 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: 2 // }, // errors: [] // } } ```