I’m working on a shopify extension and I’m trying to add some meta fields to the cart through the storefront graphql api. I need cart id to do so, but there is no way to get the cart id, the only query to get the cart requires the cart id. How does one get the cart id for use in the storefront api if they didn’t create the cart?
you can check window.Shopify on storefront and see what is available.
If there is no cart id there, you cannot get it.
Instead of a cart id, you should be able to get the checkout token from the extension: https://shopify.dev/docs/api/checkout-ui-extensions/unstable/apis/checkout-token
Instead of doing it via the Storefront API, you can also add a metafield via the extension itself: https://shopify.dev/docs/api/checkout-ui-extensions/unstable/apis/metafields (use the useApplyMetafieldsChange() API)
But are cart Id and checkout token same? can we use checkout token in places where we need to use cart id like in this mutation: https://shopify.dev/docs/api/storefront/2023-10/mutations/cartattributesupdate ?
AFAIK, the only way you can access the cart id is if you create them.
But another way you can do this is via the Metafields mutation in the Checkout UI Extension: https://shopify.dev/docs/api/checkout-ui-extensions/unstable/apis/metafields
Specifically, you can use:
useApplyMetafieldsChange()
and use type: updateCartMetafield
Mmmm some of the previous responses are not really accurate…
From the usual storefront (liquid templates’ javascript context), the cart ID can be obtained from the response of the GET cart.js query, documented here (which requires no previous knowledge):
Notice the “token” value in the response. The current customer cart id can be build like this (leave the token unmodified, i.e. keep the security key and everything):
const cartId = `gid://shopify/Cart/${token}`
And with that ID you can query the Storefront GraphQL queries/mutations that require it. Some of those GraphQL endpoints do not require authentication, so unless you really need it, just give it a try without any authentication complications.