create Cart Handlerutility
Creates an API that can be used to interact with the cart.
Anchor to createcarthandler(options)createCartHandler(options)
- Anchor to getCartIdgetCartId() => stringrequired
A function that returns the cart id in the form of
.
- Anchor to setCartIdsetCartId(cartId: string) =>required
A function that sets the cart ID.
- Anchor to storefrontstorefrontrequired
- Anchor to cartMutateFragmentcartMutateFragmentstring
The cart mutation fragment used in most mutation requests, except for
and
. See the example usage in the documentation.
- Anchor to cartQueryFragmentcartQueryFragmentstring
The cart query fragment used by
cart.get()
. See the example usage in the documentation.- Anchor to customMethodscustomMethodsTCustomMethods
Define custom methods or override existing methods for your cart API instance. See the example usage in the documentation.
CartHandlerOptionsForDocs
- cartMutateFragment
The cart mutation fragment used in most mutation requests, except for `setMetafields` and `deleteMetafield`. See the [example usage](/docs/api/hydrogen/utilities/createcarthandler#example-cart-fragments) in the documentation.
string
- cartQueryFragment
The cart query fragment used by `cart.get()`. See the [example usage](/docs/api/hydrogen/utilities/createcarthandler#example-cart-fragments) in the documentation.
string
- customMethods
Define custom methods or override existing methods for your cart API instance. See the [example usage](/docs/api/hydrogen/utilities/createcarthandler#example-custom-methods) in the documentation.
TCustomMethods
- getCartId
A function that returns the cart id in the form of `gid://shopify/Cart/c1-123`.
() => string
- setCartId
A function that sets the cart ID.
(cartId: string) => Headers
- storefront
The storefront client instance created by [`createStorefrontClient`](docs/api/hydrogen/utilities/createstorefrontclient).
Storefront
{
/**
* A function that returns the cart id in the form of `gid://shopify/Cart/c1-123`.
*/
getCartId: () => string | undefined;
/**
* A function that sets the cart ID.
*/
setCartId: (cartId: string) => Headers;
/**
* The storefront client instance created by [`createStorefrontClient`](docs/api/hydrogen/utilities/createstorefrontclient).
*/
storefront: Storefront;
/**
* The cart mutation fragment used in most mutation requests, except for `setMetafields` and `deleteMetafield`.
* See the [example usage](/docs/api/hydrogen/utilities/createcarthandler#example-cart-fragments) in the documentation.
*/
cartMutateFragment?: string;
/**
* The cart query fragment used by `cart.get()`.
* See the [example usage](/docs/api/hydrogen/utilities/createcarthandler#example-cart-fragments) in the documentation.
*/
cartQueryFragment?: string;
/**
* Define custom methods or override existing methods for your cart API instance.
* See the [example usage](/docs/api/hydrogen/utilities/createcarthandler#example-custom-methods) in the documentation.
*/
customMethods?: TCustomMethods;
}
Headers
Headers
Storefront
Interface to interact with the Storefront API.
- cache
Cache
- CacheCustom
(overrideOptions: AllCacheOptions) => AllCacheOptions
- CacheLong
(overrideOptions?: AllCacheOptions) => AllCacheOptions
- CacheNone
() => NoStoreStrategy
- CacheShort
(overrideOptions?: AllCacheOptions) => AllCacheOptions
- generateCacheControlHeader
(cacheOptions: AllCacheOptions) => string
- getApiUrl
(props?: Partial<Pick<StorefrontClientProps, "storefrontApiVersion" | "storeDomain">>) => string
- getPrivateTokenHeaders
(props?: Partial<Pick<StorefrontClientProps, "contentType">> & Pick<StorefrontClientProps, "privateStorefrontToken"> & { buyerIp?: string; }) => Record<string, string>
- getPublicTokenHeaders
(props?: Partial<Pick<StorefrontClientProps, "contentType">> & Pick<StorefrontClientProps, "publicStorefrontToken">) => Record<string, string>
- getShopifyDomain
(props?: Partial<Pick<StorefrontClientProps, "storeDomain">>) => string
- i18n
TI18n
- mutate
<OverrideReturnType extends unknown = never, RawGqlString extends string = string>(mutation: RawGqlString, ...options: IsOptionalVariables<StorefrontMutations[RawGqlString]["variables"], AutoAddedVariableNames, Omit<StorefrontMutations[RawGqlString]["variables"], AutoAddedVariableNames>> extends true ? [(StorefrontCommonExtraParams & ClientVariables<StorefrontMutations, RawGqlString, AutoAddedVariableNames, "variables", RawGqlString extends never ? SetOptional<StorefrontMutations[RawGqlString]["variables"], Extract<keyof StorefrontMutations[RawGqlString]["variables"], AutoAddedVariableNames>> : { readonly [variable: string]: unknown; }, Record<"variables", RawGqlString extends never ? SetOptional<StorefrontMutations[RawGqlString]["variables"], Extract<keyof StorefrontMutations[RawGqlString]["variables"], AutoAddedVariableNames>> : { readonly [variable: string]: unknown; }>>)?] : [StorefrontCommonExtraParams & ClientVariables<StorefrontMutations, RawGqlString, AutoAddedVariableNames, "variables", RawGqlString extends never ? SetOptional<StorefrontMutations[RawGqlString]["variables"], Extract<keyof StorefrontMutations[RawGqlString]["variables"], AutoAddedVariableNames>> : { readonly [variable: string]: unknown; }, Record<"variables", RawGqlString extends never ? SetOptional<StorefrontMutations[RawGqlString]["variables"], Extract<keyof StorefrontMutations[RawGqlString]["variables"], AutoAddedVariableNames>> : { readonly [variable: string]: unknown; }>>]) => Promise<ClientReturn<StorefrontMutations, RawGqlString, OverrideReturnType> & StorefrontError>
- query
<OverrideReturnType extends unknown = never, RawGqlString extends string = string>(query: RawGqlString, ...options: IsOptionalVariables<StorefrontQueries[RawGqlString]["variables"], AutoAddedVariableNames, Omit<StorefrontQueries[RawGqlString]["variables"], AutoAddedVariableNames>> extends true ? [(StorefrontCommonExtraParams & Pick<StorefrontQueryOptions, "cache"> & ClientVariables<StorefrontQueries, RawGqlString, AutoAddedVariableNames, "variables", RawGqlString extends never ? SetOptional<StorefrontQueries[RawGqlString]["variables"], Extract<keyof StorefrontQueries[RawGqlString]["variables"], AutoAddedVariableNames>> : { readonly [variable: string]: unknown; }, Record<"variables", RawGqlString extends never ? SetOptional<StorefrontQueries[RawGqlString]["variables"], Extract<keyof StorefrontQueries[RawGqlString]["variables"], AutoAddedVariableNames>> : { readonly [variable: string]: unknown; }>>)?] : [StorefrontCommonExtraParams & Pick<StorefrontQueryOptions, "cache"> & ClientVariables<StorefrontQueries, RawGqlString, AutoAddedVariableNames, "variables", RawGqlString extends never ? SetOptional<StorefrontQueries[RawGqlString]["variables"], Extract<keyof StorefrontQueries[RawGqlString]["variables"], AutoAddedVariableNames>> : { readonly [variable: string]: unknown; }, Record<"variables", RawGqlString extends never ? SetOptional<StorefrontQueries[RawGqlString]["variables"], Extract<keyof StorefrontQueries[RawGqlString]["variables"], AutoAddedVariableNames>> : { readonly [variable: string]: unknown; }>>]) => Promise<ClientReturn<StorefrontQueries, RawGqlString, OverrideReturnType> & StorefrontError>
{
query: <
OverrideReturnType extends any = never,
RawGqlString extends string = string,
>(
query: RawGqlString,
...options: ClientVariablesInRestParams<
StorefrontQueries,
RawGqlString,
StorefrontCommonExtraParams & Pick<StorefrontQueryOptions, 'cache'>,
AutoAddedVariableNames
>
) => Promise<
ClientReturn<StorefrontQueries, RawGqlString, OverrideReturnType> &
StorefrontError
>;
mutate: <
OverrideReturnType extends any = never,
RawGqlString extends string = string,
>(
mutation: RawGqlString,
...options: ClientVariablesInRestParams<
StorefrontMutations,
RawGqlString,
StorefrontCommonExtraParams,
AutoAddedVariableNames
>
) => Promise<
ClientReturn<StorefrontMutations, RawGqlString, OverrideReturnType> &
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).
number
- mode
The caching mode, generally `public`, `private`, or `no-store`.
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).
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).
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).
number
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
string
{
mode: string;
}
StorefrontMutations
Maps all the mutations found in the project to variables and return types.
export interface StorefrontMutations {
// Example of how a generated mutation type looks like:
// '#graphql mutation m1 {...}': {return: M1Mutation; variables: M1MutationVariables};
}
AutoAddedVariableNames
'country' | 'language'
StorefrontCommonExtraParams
- displayName
string
- headers
HeadersInit
- storefrontApiVersion
string
{
headers?: HeadersInit;
storefrontApiVersion?: string;
displayName?: string;
}
StorefrontError
- errors
StorefrontApiErrors
{
errors?: StorefrontApiErrors;
}
StorefrontApiErrors
JsonGraphQLError[] | undefined
JsonGraphQLError
ReturnType<GraphQLError['toJSON']>
StorefrontQueries
Maps all the queries found in the project to variables and return types.
export interface StorefrontQueries {
// Example of how a generated query type looks like:
// '#graphql query q1 {...}': {return: Q1Query; variables: Q1QueryVariables};
}
StorefrontQueryOptions
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).
number
- mode
The caching mode, generally `public`, `private`, or `no-store`.
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).
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).
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).
number
AllCacheOptions
Anchor to returnsReturns
The handler returns the following default methods. Any custom or overwritten methods will also be available in the returned cart instance.
- Anchor to addDeliveryAddressesaddDeliveryAddresses
Adds a delivery address to the cart.
- Anchor to addLinesaddLines
Adds items to the cart. If the cart doesn't exist, a new one will be created.
- Anchor to createcreate
Creates a new cart.
- Anchor to deleteMetafielddeleteMetafield
Removes a custom field (metafield) from the cart.
Retrieves the cart information.
- Anchor to getCartIdgetCartId() => string
Retrieves the unique identifier of the cart. By default, it gets the ID from the request cookie.
- Anchor to removeDeliveryAddressesremoveDeliveryAddresses
Removes a delivery address from the cart
- Anchor to removeLinesremoveLines
Removes items from the cart.
- Anchor to setCartIdsetCartId(cartId: string) =>
Sets the unique identifier of the cart. By default, it sets the ID in the header cookie.
- Anchor to setMetafieldssetMetafields
Adds extra information (metafields) to the cart. If the cart doesn't exist, a new one will be created.
- Anchor to updateAttributesupdateAttributes
Updates additional information (attributes) in the cart.
- Anchor to updateBuyerIdentityupdateBuyerIdentity
Updates the buyer's information in the cart. If the cart doesn't exist, a new one will be created.
- Anchor to updateDeliveryAddressesupdateDeliveryAddresses
Update cart delivery addresses.
- Anchor to updateDiscountCodesupdateDiscountCodes
Updates discount codes in the cart.
- Anchor to updateGiftCardCodesupdateGiftCardCodes
Updates gift card codes in the cart.
- Anchor to updateLinesupdateLines
Updates items in the cart.
- Anchor to updateNoteupdateNote
Updates the note in the cart. If the cart doesn't exist, a new one will be created.
- Anchor to updateSelectedDeliveryOptionupdateSelectedDeliveryOption
Updates the selected delivery options in the cart. Only available for carts associated with a customer access token.
HydrogenCartForDocs
- addDeliveryAddresses
Adds a delivery address to the cart.
CartDeliveryAddressesAddFunction
- addLines
Adds items to the cart. If the cart doesn't exist, a new one will be created.
CartLinesAddFunction
- create
Creates a new cart.
CartCreateFunction
- deleteMetafield
Removes a custom field (metafield) from the cart.
CartMetafieldDeleteFunction
- get
Retrieves the cart information.
CartGetFunction
- getCartId
Retrieves the unique identifier of the cart. By default, it gets the ID from the request cookie.
() => string
- removeDeliveryAddresses
Removes a delivery address from the cart
CartDeliveryAddressesRemoveFunction
- removeLines
Removes items from the cart.
CartLinesRemoveFunction
- setCartId
Sets the unique identifier of the cart. By default, it sets the ID in the header cookie.
(cartId: string) => Headers
- setMetafields
Adds extra information (metafields) to the cart. If the cart doesn't exist, a new one will be created.
CartMetafieldsSetFunction
- updateAttributes
Updates additional information (attributes) in the cart.
CartAttributesUpdateFunction
- updateBuyerIdentity
Updates the buyer's information in the cart. If the cart doesn't exist, a new one will be created.
CartBuyerIdentityUpdateFunction
- updateDeliveryAddresses
Update cart delivery addresses.
CartDeliveryAddressesUpdateFunction
- updateDiscountCodes
Updates discount codes in the cart.
CartDiscountCodesUpdateFunction
- updateGiftCardCodes
Updates gift card codes in the cart.
CartGiftCardCodesUpdateFunction
- updateLines
Updates items in the cart.
CartLinesUpdateFunction
- updateNote
Updates the note in the cart. If the cart doesn't exist, a new one will be created.
CartNoteUpdateFunction
- updateSelectedDeliveryOption
Updates the selected delivery options in the cart. Only available for carts associated with a customer access token.
CartSelectedDeliveryOptionsUpdateFunction
{
/**
* Adds items to the cart.
* If the cart doesn't exist, a new one will be created.
*/
addLines?: CartLinesAddFunction;
/**
* Adds a delivery address to the cart.
*/
addDeliveryAddresses?: CartDeliveryAddressesAddFunction;
/**
* Creates a new cart.
*/
create?: CartCreateFunction;
/**
* Removes a custom field (metafield) from the cart.
*/
deleteMetafield?: CartMetafieldDeleteFunction;
/**
* Retrieves the cart information.
*/
get?: CartGetFunction;
/**
* Retrieves the unique identifier of the cart.
* By default, it gets the ID from the request cookie.
*/
getCartId?: () => string | undefined;
/**
* Removes a delivery address from the cart
*/
removeDeliveryAddresses?: CartDeliveryAddressesRemoveFunction;
/**
* Removes items from the cart.
*/
removeLines?: CartLinesRemoveFunction;
/**
* Sets the unique identifier of the cart.
* By default, it sets the ID in the header cookie.
*/
setCartId?: (cartId: string) => Headers;
/**
* Adds extra information (metafields) to the cart.
* If the cart doesn't exist, a new one will be created.
*/
setMetafields?: CartMetafieldsSetFunction;
/**
* Update cart delivery addresses.
*/
updateDeliveryAddresses?: CartDeliveryAddressesUpdateFunction;
/**
* Updates additional information (attributes) in the cart.
*/
updateAttributes?: CartAttributesUpdateFunction;
/**
* Updates the buyer's information in the cart.
* If the cart doesn't exist, a new one will be created.
*/
updateBuyerIdentity?: CartBuyerIdentityUpdateFunction;
/**
* Updates discount codes in the cart.
*/
updateDiscountCodes?: CartDiscountCodesUpdateFunction;
/**
* Updates gift card codes in the cart.
*/
updateGiftCardCodes?: CartGiftCardCodesUpdateFunction;
/**
* Updates items in the cart.
*/
updateLines?: CartLinesUpdateFunction;
/**
* Updates the note in the cart.
* If the cart doesn't exist, a new one will be created.
*/
updateNote?: CartNoteUpdateFunction;
/**
* Updates the selected delivery options in the cart.
* Only available for carts associated with a customer access token.
*/
updateSelectedDeliveryOption?: CartSelectedDeliveryOptionsUpdateFunction;
}
CartDeliveryAddressesAddFunction
- addresses
CartSelectableAddressInput[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartDeliveryAddressesAddFunction = (
addresses: Array<CartSelectableAddressInput>,
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartOptionalInput
- cartId
The cart id.
string
- country
The country code.
CountryCode
- language
The language code.
LanguageCode
{
/**
* 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
CartQueryData & {
errors?: StorefrontApiErrors;
}
CartQueryData
- cart
Cart
- userErrors
| CartUserError[] | MetafieldsSetUserError[] | MetafieldDeleteUserError[]
- warnings
CartWarning[]
{
cart: Cart;
userErrors?:
| CartUserError[]
| MetafieldsSetUserError[]
| MetafieldDeleteUserError[];
warnings?: CartWarning[];
}
Cart
Cart
CartUserError
CartUserError
MetafieldsSetUserError
MetafieldsSetUserError
MetafieldDeleteUserError
MetafieldDeleteUserError
CartWarning
CartWarning
StorefrontApiErrors
JsonGraphQLError[] | undefined
JsonGraphQLError
ReturnType<GraphQLError['toJSON']>
CartLinesAddFunction
- lines
CartLineInput[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartLinesAddFunction = (
lines: Array<CartLineInput>,
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartLineInput
CartLineInput
CartCreateFunction
- input
CartInput
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartCreateFunction = (
input: CartInput,
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartInput
CartInput
CartMetafieldDeleteFunction
- key
string
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartMetafieldDeleteFunction = (
key: Scalars['String']['input'],
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartGetFunction
- cartInput
CartGetProps
Promise<CartReturn | null>
export type CartGetFunction = (
cartInput?: CartGetProps,
) => Promise<CartReturn | null>;
CartGetProps
- cartId
The cart ID.
string
- country
The country code.
CountryCode
- language
The language code.
LanguageCode
- numCartLines
The number of cart lines to be returned.
number
{
/**
* 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
Cart & {
errors?: StorefrontApiErrors;
}
CartDeliveryAddressesRemoveFunction
- addressIds
string[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartDeliveryAddressesRemoveFunction = (
addressIds: Array<Scalars['ID']['input']> | Array<string>,
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartLinesRemoveFunction
- lineIds
string[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartLinesRemoveFunction = (
lineIds: string[],
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
Headers
Headers
CartMetafieldsSetFunction
- metafields
MetafieldWithoutOwnerId[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartMetafieldsSetFunction = (
metafields: MetafieldWithoutOwnerId[],
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
MetafieldWithoutOwnerId
MetafieldWithoutOwnerId
CartAttributesUpdateFunction
- attributes
AttributeInput[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartAttributesUpdateFunction = (
attributes: AttributeInput[],
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
AttributeInput
AttributeInput
CartBuyerIdentityUpdateFunction
- buyerIdentity
CartBuyerIdentityInput
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartBuyerIdentityUpdateFunction = (
buyerIdentity: CartBuyerIdentityInput,
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartBuyerIdentityInput
CartBuyerIdentityInput
CartDeliveryAddressesUpdateFunction
- addresses
CartSelectableAddressUpdateInput[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartDeliveryAddressesUpdateFunction = (
addresses: Array<CartSelectableAddressUpdateInput>,
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartDiscountCodesUpdateFunction
- discountCodes
string[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartDiscountCodesUpdateFunction = (
discountCodes: string[],
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartGiftCardCodesUpdateFunction
- giftCardCodes
string[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartGiftCardCodesUpdateFunction = (
giftCardCodes: string[],
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartLinesUpdateFunction
- lines
CartLineUpdateInput[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartLinesUpdateFunction = (
lines: CartLineUpdateInput[],
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartLineUpdateInput
CartLineUpdateInput
CartNoteUpdateFunction
- note
string
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartNoteUpdateFunction = (
note: string,
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartSelectedDeliveryOptionsUpdateFunction
- selectedDeliveryOptions
CartSelectedDeliveryOptionInput[]
- optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>
export type CartSelectedDeliveryOptionsUpdateFunction = (
selectedDeliveryOptions: CartSelectedDeliveryOptionInput[],
optionalParams?: CartOptionalInput,
) => Promise<CartQueryDataReturn>;
CartSelectedDeliveryOptionInput
CartSelectedDeliveryOptionInput
Server.(js|ts)
examples
server.(js|ts)
description
This is the default example
JavaScript
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
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<string, string>, executionContext: ExecutionContext, ): Promise<Response> { 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); }, };
Anchor to examplesExamples
Examples of various ways to use the utility.
Anchor to example-cart-fragmentsCart fragments
Anchor to example-exampleExample
Use and
to change the cart data the queries will return.
Example
JavaScript
examples
Example
description
Use `cartQueryFragment` and `cartMutateFragment` to change the cart data the queries will return.
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 } } } } `;
Anchor to example-custom-methodsCustom methods
Anchor to example-exampleExample
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.
Example
JavaScript
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
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 } } } `;
Anchor to example-cart-instance-usageCart instance usage
Anchor to example-cart.addlinesCart.addLines
Add items to the cart. If the cart does not exist, a new cart will be created.
Anchor to example-cart.createCart.create
Create a new cart.
Anchor to example-cart.deletemetafieldCart.deleteMetafield
Delete extra information (metafield) from the cart.
Anchor to example-cart.getCart.get
Retrieve the cart information.
Anchor to example-cart.getcartidCart.getCartId
Get the unique identifier of the cart.
Anchor to example-cart.removelinesCart.removeLines
Remove items from the cart.
Anchor to example-cart.setcartidCart.setCartId
Set the unique identifier of the cart.
Anchor to example-cart.setmetafieldsCart.setMetafields
Add extra information (metafields) to the cart. If the cart does not exist, a new cart will be created.
Anchor to example-cart.updateattributesCart.updateAttributes
Update additional information (attributes) in the cart. If the cart does not exist, a new cart will be created.
Anchor to example-cart.updatebuyeridentityCart.updateBuyerIdentity
Update the buyer’s information in the cart. If the cart does not exist, a new cart will be created.
Anchor to example-cart.updatediscountcodesCart.updateDiscountCodes
Update discount codes in the cart.
Anchor to example-cart.updategiftcardcodesCart.updateGiftCardCodes
Update gift card codes in the cart.
Anchor to example-cart.updatelinesCart.updateLines
Update items in the cart.
Anchor to example-cart.updatenoteCart.updateNote
Update the note in the cart. If the cart does not exist, a new cart will be created.
Anchor to example-cart.updateselecteddeliveryoptionsCart.updateSelectedDeliveryOptions
Update the selected delivery options in the cart. Only available for carts associated with a customer access token.
Cart.addLines
JavaScript
examples
cart.addLines
description
Add items to the cart. If the cart does not exist, a new cart will be created.
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: [] // }
cart.create
description
Create a new cart.
JavaScript
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
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
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
export async function loader({context}) { // Usage context.cart.getCartId(); // 'gid://shopify/Cart/123' }
cart.removeLines
description
Remove items from the cart.
JavaScript
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
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
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
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
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
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
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
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
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
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: [] // } }