create Cart Handler
Creates an API that can be used to interact with the cart.
Anchor to createcarthandler(options)createCartHandler(options)
- Anchor to getCartIdget
Cart Idget Cart Id () => string() => stringrequiredrequired A function that returns the cart id in the form of
.- Anchor to setCartIdset
Cart Idset Cart Id (cartId: string) => Headers(cartId: string) => Headersrequiredrequired A function that sets the cart ID.
- Anchor to storefrontstorefrontstorefrontStorefrontStorefrontrequiredrequired
- Anchor to buyerIdentitybuyer
Identitybuyer Identity CartBuyerIdentityInputCartBuyerIdentityInput Buyer identity. Default buyer identity is passed to cartCreate.
- Anchor to cartMutateFragmentcart
Mutate Fragmentcart Mutate Fragment stringstring The cart mutation fragment used in most mutation requests, except for
and. See the example usage in the documentation.- Anchor to cartQueryFragmentcart
Query Fragmentcart Query Fragment stringstring The cart query fragment used by
cart.get(). See the example usage in the documentation.- Anchor to customMethodscustom
Methodscustom Methods TCustomMethodsTCustomMethods Define custom methods or override existing methods for your cart API instance. See the example usage in the documentation.
CartBuyerIdentityInput
Headers
Storefront
Interface to interact with the Storefront API.
- cache
The **`Cache`** interface provides a persistent storage mechanism for Request / Response object pairs that are cached in long lived memory. Available only in secure contexts. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache)
Cache - CacheCustom
(overrideOptions: AllCacheOptions) => AllCacheOptions - CacheLong
(overrideOptions?: AllCacheOptions) => AllCacheOptions - CacheNone
() => NoStoreStrategy - CacheShort
(overrideOptions?: AllCacheOptions) => AllCacheOptions - forward
Forwards the request to the Storefront API. It reads the API version from the request URL.
(request: Request, options?: Pick<StorefrontCommonExtraParams, "storefrontApiVersion">) => Promise<Response> - forwardMcp
Forwards the request to the Storefront MCP endpoint.
(request: Request) => Promise<Response> - generateCacheControlHeader
(cacheOptions: AllCacheOptions) => string - getApiUrl
(props?: Partial<Pick<StorefrontClientProps, "storefrontApiVersion" | "storeDomain">>) => string - getHeaders
() => Record<string, 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 - isMcpUrl
Checks if the request URL matches the Storefront MCP endpoint.
(request: { url?: string; }) => boolean - isStorefrontApiUrl
Checks if the request URL matches the Storefront API GraphQL endpoint.
(request: { url?: string; }) => boolean - mutate
< OverrideReturnType extends any = never, RawGqlString extends string = string, >( mutation: RawGqlString, ...options: ClientVariablesInRestParams< StorefrontMutations, RawGqlString, StorefrontCommonExtraParams, AutoAddedVariableNames > ) => Promise< ClientReturn<StorefrontMutations, 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 > - setCollectedSubrequestHeaders
Sets the collected subrequest headers in the response. Useful to forward the cookies and server-timing headers from server subrequests to the browser.
(response: { headers: Headers; }) => void
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
NoStoreStrategy
- mode
string
StorefrontCommonExtraParams
- displayName
string - headers
HeadersInit - storefrontApiVersion
string
StorefrontClientProps
- contentType
Customizes which `"content-type"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `"json"`. When fetching with a `body` that is a plain string, use `"graphql"`. Defaults to `"json"` Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`
'json' | 'graphql' - privateStorefrontToken
The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details.
string - publicStorefrontToken
The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details.
string - storeDomain
The host name of the domain (eg: `{shop}.myshopify.com`).
string - storefrontApiVersion
The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details.
string
StorefrontMutations
Maps all the mutations found in the project to variables and return types.
AutoAddedVariableNames
'country' | 'language'StorefrontError
- errors
StorefrontApiErrors
StorefrontApiErrors
JsonGraphQLError[] | undefinedJsonGraphQLError
- extensions
Reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.
{ [key: string]: unknown; } - locations
If an error can be associated to a particular point in the requested GraphQL document, it should contain a list of locations.
{ line: number; column: number; }[] - message
string - name
string - path
If an error can be associated to a particular field in the GraphQL result, it _must_ contain an entry with the key `path` that details the path of the response field which experienced the error. This allows clients to identify whether a null result is intentional or caused by a runtime error.
(string | number)[] - stack
string
StorefrontQueries
Maps all the queries found in the project to variables and return types.
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
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 addDeliveryAddressesadd
Delivery Addressesadd Delivery Addresses CartDeliveryAddressesAddFunctionCartDeliveryAddressesAddFunction Adds a delivery address to the cart.
- Anchor to addGiftCardCodesadd
Gift Card Codesadd Gift Card Codes CartGiftCardCodesAddFunctionCartGiftCardCodesAddFunction Adds gift card codes to the cart without replacing existing ones.
- Anchor to addLinesadd
Linesadd Lines CartLinesAddFunctionCartLinesAddFunction Adds items to the cart. If the cart doesn't exist, a new one will be created.
- Anchor to createcreatecreateCartCreateFunctionCartCreateFunction
Creates a new cart.
- Anchor to deleteMetafielddelete
Metafielddelete Metafield CartMetafieldDeleteFunctionCartMetafieldDeleteFunction Removes a custom field (metafield) from the cart.
- Anchor to getgetgetCartGetFunctionCartGetFunction
Retrieves the cart information.
- Anchor to getCartIdget
Cart Idget Cart Id () => string() => string Retrieves the unique identifier of the cart. By default, it gets the ID from the request cookie.
- Anchor to removeDeliveryAddressesremove
Delivery Addressesremove Delivery Addresses CartDeliveryAddressesRemoveFunctionCartDeliveryAddressesRemoveFunction Removes a delivery address from the cart
- Anchor to removeGiftCardCodesremove
Gift Card Codesremove Gift Card Codes CartGiftCardCodesRemoveFunctionCartGiftCardCodesRemoveFunction Removes gift card codes from the cart.
- Anchor to removeLinesremove
Linesremove Lines CartLinesRemoveFunctionCartLinesRemoveFunction Removes items from the cart.
- Anchor to replaceDeliveryAddressesreplace
Delivery Addressesreplace Delivery Addresses CartDeliveryAddressesReplaceFunctionCartDeliveryAddressesReplaceFunction Replace all delivery addresses on the cart.
- Anchor to setCartIdset
Cart Idset Cart Id (cartId: string) => Headers(cartId: string) => Headers Sets the unique identifier of the cart. By default, it sets the ID in the header cookie.
- Anchor to setMetafieldsset
Metafieldsset Metafields CartMetafieldsSetFunctionCartMetafieldsSetFunction Adds extra information (metafields) to the cart. If the cart doesn't exist, a new one will be created.
- Anchor to updateAttributesupdate
Attributesupdate Attributes CartAttributesUpdateFunctionCartAttributesUpdateFunction Updates additional information (attributes) in the cart.
- Anchor to updateBuyerIdentityupdate
Buyer Identityupdate Buyer Identity CartBuyerIdentityUpdateFunctionCartBuyerIdentityUpdateFunction Updates the buyer's information in the cart. If the cart doesn't exist, a new one will be created.
- Anchor to updateDeliveryAddressesupdate
Delivery Addressesupdate Delivery Addresses CartDeliveryAddressesUpdateFunctionCartDeliveryAddressesUpdateFunction Update cart delivery addresses.
- Anchor to updateDiscountCodesupdate
Discount Codesupdate Discount Codes CartDiscountCodesUpdateFunctionCartDiscountCodesUpdateFunction Updates discount codes in the cart.
- Anchor to updateGiftCardCodesupdate
Gift Card Codesupdate Gift Card Codes CartGiftCardCodesUpdateFunctionCartGiftCardCodesUpdateFunction Updates gift card codes in the cart.
- Anchor to updateLinesupdate
Linesupdate Lines CartLinesUpdateFunctionCartLinesUpdateFunction Updates items in the cart.
- Anchor to updateNoteupdate
Noteupdate Note CartNoteUpdateFunctionCartNoteUpdateFunction Updates the note in the cart. If the cart doesn't exist, a new one will be created.
- Anchor to updateSelectedDeliveryOptionupdate
Selected Delivery Optionupdate Selected Delivery Option CartSelectedDeliveryOptionsUpdateFunctionCartSelectedDeliveryOptionsUpdateFunction Updates the selected delivery options in the cart. Only available for carts associated with a customer access token.
CartDeliveryAddressesAddFunction
- addresses
CartSelectableAddressInput[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartOptionalInput
- cartId
The cart id.
string - country
The country code.
CountryCode - language
The language code.
LanguageCode - visitorConsent
Visitor consent preferences for the Storefront API's
VisitorConsent
VisitorConsent
- analytics
ConsentStatus - marketing
ConsentStatus - preferences
ConsentStatus - sale_of_data
ConsentStatus
ConsentStatus
boolean | undefinedCartQueryDataReturn
CartQueryData & {
errors?: StorefrontApiErrors;
}CartQueryData
- cart
A cart represents the merchandise that a buyer intends to purchase, and the estimated cost associated with the cart, throughout a customer's session. Use the [`checkoutUrl`](https://shopify.dev/docs/api/storefront/current/objects/Cart#field-checkoutUrl) field to direct buyers to Shopify's web checkout to complete their purchase. Learn more about [interacting with carts](https://shopify.dev/docs/storefronts/headless/building-with-the-storefront-api/cart/manage).
Cart - userErrors
| CartUserError[] | MetafieldsSetUserError[] | MetafieldDeleteUserError[] - warnings
CartWarning[]
Cart
- attributes
The cart's attributes.
{ __typename?: "Attribute"; key?: string; value?: string; }[] - buyerIdentity
The cart's buyer identity.
CartType['buyerIdentity'] - checkoutUrl
The checkout URL for the cart, if the cart has been created in the Storefront API.
string - cost
The cost for the cart, including the subtotal, total, taxes, and duties.
CartType['cost'] - discountCodes
The discount codes applied to the cart.
{ __typename?: "CartDiscountCode"; applicable?: boolean; code?: string; }[] - id
The cart's ID if it has been created through the Storefront API.
string - lines
The cart lines.
Array<CartLine | ComponentizableCartLine> - note
The cart's note.
string - totalQuantity
The total number of items in the cart, across all lines. If there are no lines, then the value is 0.
number
CartUserError
MetafieldsSetUserError
MetafieldDeleteUserError
CartWarning
CartGiftCardCodesAddFunction
- giftCardCodes
string[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartLinesAddFunction
- lines
CartLineInput[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartLineInput
CartCreateFunction
- input
CartInput - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartInput
CartMetafieldDeleteFunction
- key
string - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>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 - visitorConsent
Visitor consent preferences for the Storefront API's
VisitorConsent
CartReturn
Cart & {
errors?: StorefrontApiErrors;
}CartDeliveryAddressesRemoveFunction
- addressIds
string[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartGiftCardCodesRemoveFunction
- appliedGiftCardIds
string[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartLinesRemoveFunction
- lineIds
string[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartDeliveryAddressesReplaceFunction
- addresses
CartSelectableAddressInput[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartMetafieldsSetFunction
- metafields
MetafieldWithoutOwnerId[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>MetafieldWithoutOwnerId
CartAttributesUpdateFunction
- attributes
AttributeInput[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>AttributeInput
CartBuyerIdentityUpdateFunction
- buyerIdentity
CartBuyerIdentityInput - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartDeliveryAddressesUpdateFunction
- addresses
CartSelectableAddressUpdateInput[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartDiscountCodesUpdateFunction
- discountCodes
string[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartGiftCardCodesUpdateFunction
- giftCardCodes
string[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartLinesUpdateFunction
- lines
CartLineUpdateInput[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartLineUpdateInput
CartNoteUpdateFunction
- note
string - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartSelectedDeliveryOptionsUpdateFunction
- selectedDeliveryOptions
CartSelectedDeliveryOptionInput[] - optionalParams
CartOptionalInput
Promise<CartQueryDataReturn>CartSelectedDeliveryOptionInput
Examples
Server.(js|ts)
JavaScript
import { createStorefrontClient, createCartHandler, cartGetIdDefault, cartSetIdDefault, createRequestHandler, } from '@shopify/hydrogen'; import * as reactRouterBuild from 'virtual:react-router/server-build'; 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, createRequestHandler, } from '@shopify/hydrogen'; import * as reactRouterBuild from 'virtual:react-router/server-build'; 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); }, };