--- title: cartMetafieldsSetDefault description: Creates a function that accepts an array of [CartMetafieldsSetInput](https://shopify.dev/docs/api/storefront/2026-01/input-objects/CartMetafieldsSetInput) without `ownerId` and set the metafields to a cart api_version: 2026-01 api_name: hydrogen source_url: html: https://shopify.dev/docs/api/hydrogen/latest/utilities/cartmetafieldssetdefault md: https://shopify.dev/docs/api/hydrogen/latest/utilities/cartmetafieldssetdefault.md --- # cart​Metafields​Set​Default Creates a function that accepts an array of [CartMetafieldsSetInput](https://shopify.dev/docs/api/storefront/2026-01/input-objects/CartMetafieldsSetInput) without `ownerId` and set the metafields to a cart ## cart​Metafields​Set​Default(**[options](#cartmetafieldssetdefault-propertydetail-options)**​) ### Parameters * **options** **CartQueryOptions** **required** ### Returns * **CartMetafieldsSetFunction** ### ### CartMetafieldsSetFunction * **export type CartMetafieldsSetFunction = ( metafields: MetafieldWithoutOwnerId[], optionalParams?: CartOptionalInput, ) => Promise;** ### CartQueryOptions * cartFragment The cart fragment to override the one used in this query. ```ts string ``` * customerAccount The customer account instance created by \[\`createCustomerAccount\`]\(docs/api/hydrogen/latest/customer/createcustomeraccount). ```ts CustomerAccount ``` * getCartId A function that returns the cart ID. ```ts () => string ``` * storefront The storefront client instance created by \[\`createStorefrontClient\`]\(docs/api/hydrogen/latest/utilities/createstorefrontclient). ```ts Storefront ``` ### CustomerAccount * authorize On successful login, the customer redirects back to your app. This function validates the OAuth response and exchanges the authorization code for an access token and refresh token. It also persists the tokens on your session. This function should be called and returned from the Remix loader configured as the redirect URI within the Customer Account API settings in admin. ```ts () => Promise ``` * getAccessToken Returns CustomerAccessToken if the customer is logged in. It also run a expiry check and does a token refresh if needed. ```ts () => Promise ``` * getApiUrl Creates the fully-qualified URL to your store's GraphQL endpoint. ```ts () => string ``` * getBuyer Get buyer token and company location id from session. ```ts () => Promise ``` * handleAuthStatus Check for a not logged in customer and redirect customer to login page. The redirect can be overwritten with \`customAuthStatusHandler\` option. ```ts () => void | DataFunctionValue ``` * i18n The i18n configuration for Customer Account API ```ts { language: LanguageCode; } ``` * isLoggedIn Returns if the customer is logged in. It also checks if the access token is expired and refreshes it if needed. ```ts () => Promise ``` * login Start the OAuth login flow. This function should be called and returned from a Remix loader. It redirects the customer to a Shopify login domain. It also defined the final path the customer lands on at the end of the oAuth flow with the value of the \`return\_to\` query param. (This is automatically setup unless \`customAuthStatusHandler\` option is in use) ```ts (options?: LoginOptions) => Promise ``` * logout Logout the customer by clearing the session and redirecting to the login domain. It should be called and returned from a Remix action. The path app should redirect to after logout can be setup in Customer Account API settings in admin. ```ts (options?: LogoutOptions) => Promise ``` * mutate Execute a GraphQL mutation against the Customer Account API. This method execute \`handleAuthStatus()\` ahead of mutation. ```ts (mutation: RawGqlString, ...options: ClientVariablesInRestParams) => Promise>, "errors"> & { errors?: Pick[]; }> ``` * query Execute a GraphQL query against the Customer Account API. This method execute \`handleAuthStatus()\` ahead of query. ```ts (query: RawGqlString, ...options: ClientVariablesInRestParams) => Promise>, "errors"> & { errors?: Pick[]; }> ``` * setBuyer Set buyer information into session. ```ts (buyer: BuyerInput) => void ``` * UNSTABLE\_getBuyer Deprecated. Please use getBuyer. Get buyer token and company location id from session. ```ts () => Promise ``` * UNSTABLE\_setBuyer Deprecated. Please use setBuyer. Set buyer information into session. ```ts (buyer: BuyerInput) => void ``` ### DataFunctionValue ```ts Response | NonNullable | null ``` ### LoginOptions * acrValues ```ts string ``` * countryCode ```ts CountryCode ``` * locale ```ts string ``` * loginHint ```ts string ``` * loginHintMode ```ts string ``` * uiLocales ```ts LanguageCode ``` ### LogoutOptions * headers Add custom headers to the logout redirect. ```ts HeadersInit ``` * keepSession If true, custom data in the session will not be cleared on logout. ```ts boolean ``` * postLogoutRedirectUri The url to redirect customer to after logout, should be a relative URL. This url will need to included in Customer Account API's application setup for logout URI. The default value is current app origin, which is automatically setup in admin when using \`--customer-account-push\` flag with dev. ```ts string ``` ### CustomerAccountMutations ### CustomerAPIResponse * data ```ts ReturnType ``` * errors ```ts Array<{ message: string; locations?: Array<{line: number; column: number}>; path?: Array; extensions: {code: string}; }> ``` * extensions ```ts { cost: { requestQueryCost: number; actualQueryCakes: number; throttleStatus: { maximumAvailable: number; currentAvailable: number; restoreRate: number; }; }; } ``` ### GraphQLError * locations If an error can be associated to a particular point in the requested GraphQL document, it should contain a list of locations. ```ts { line: number; column: number; }[] ``` * 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. ```ts (string | number)[] ``` * extensions Reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents. ```ts { [key: string]: unknown; } ``` * toString Note: \`toString()\` is internally used by \`console.log(...)\` / \`console.error(...)\` when ingesting logs in Oxygen production. Therefore, we want to make sure that the error message is as informative as possible instead of \`\[object Object]\`. ```ts () => string ``` * toJSON Note: toJSON\` is internally used by \`JSON.stringify(...)\`. The most common scenario when this error instance is going to be stringified is when it's passed to Remix' \`json\` and \`defer\` functions: e.g. \`{promise: storefront.query(...)}\`. In this situation, we don't want to expose private error information to the browser so we only do it in development. ```ts () => Pick ``` * \_\_@toStringTag\@483 ```ts string ``` * name ```ts string ``` * message ```ts string ``` * stack ```ts string ``` ### CustomerAccountQueries ### 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 ``` * forward Forwards the request to the Storefront API. It reads the API version from the request URL. ```ts (request: Request, options?: Pick) => Promise ``` * generateCacheControlHeader ```ts (cacheOptions: AllCacheOptions) => string ``` * getApiUrl ```ts any ``` * getHeaders ```ts () => Record ``` * getPrivateTokenHeaders ```ts any ``` * getPublicTokenHeaders ```ts any ``` * getShopifyDomain ```ts any ``` * i18n ```ts TI18n ``` * isStorefrontApiUrl Checks if the request URL matches the Storefront API GraphQL endpoint. ```ts (request: { url?: string; }) => boolean ``` * mutate ```ts (mutation: RawGqlString, ...options: ClientVariablesInRestParams) => Promise ``` * query ```ts (query: RawGqlString, ...options: ClientVariablesInRestParams, AutoAddedVariableNames>) => Promise ``` * setCollectedSubrequestHeaders Sets the collected subrequest headers in the response. Useful to forward the cookies and server-timing headers from server subrequests to the browser. ```ts (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). ```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 ``` ### NoStoreStrategy * mode ```ts string ``` ### StorefrontCommonExtraParams * displayName ```ts string ``` * headers ```ts HeadersInit ``` * storefrontApiVersion ```ts string ``` ### StorefrontMutations Maps all the mutations found in the project to variables and return types. ### AutoAddedVariableNames ```ts 'country' | 'language' ``` ### StorefrontQueries Maps all the queries found in the project to variables and return types. ### 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 ``` ### Headers ### CartMetafieldsSetFunction * metafields ```ts MetafieldWithoutOwnerId[] ``` * optionalParams ```ts CartOptionalInput ``` Promise\ ```ts Promise ``` ### MetafieldWithoutOwnerId ### CartOptionalInput * cartId The cart id. ```ts Scalars ``` * country The country code. ```ts CountryCode ``` * language The language code. ```ts LanguageCode ``` * visitorConsent Visitor consent preferences for the Storefront API's ```ts VisitorConsent ``` ### VisitorConsent * analytics ```ts ConsentStatus ``` * marketing ```ts ConsentStatus ``` * preferences ```ts ConsentStatus ``` * sale\_of\_data ```ts ConsentStatus ``` ### ConsentStatus ```ts boolean | undefined ``` ### CartQueryDataReturn ```ts CartQueryData & { errors?: StorefrontApiErrors; } ``` ### CartQueryData * cart ```ts Cart ``` * userErrors ```ts | CartUserError[] | MetafieldsSetUserError[] | MetafieldDeleteUserError[] ``` * warnings ```ts CartWarning[] ``` ### Cart ### CartUserError ### MetafieldsSetUserError ### MetafieldDeleteUserError ### CartWarning ### StorefrontApiErrors ```ts JsonGraphQLError[] | undefined ``` ### JsonGraphQLError Examples ### Examples * #### example ##### Description This is the default example ##### JavaScript ```js import {cartMetafieldsSetDefault} from '@shopify/hydrogen'; const cartSetMetafields = cartMetafieldsSetDefault({ storefront, getCartId, }); const result = await cartSetMetafields([ { key: 'custom.gift', type: 'boolean', value: 'true', }, ]); ```