Examples

Using the Cart

How to use the cart in your Shopify store in Nuxt

This example will show you how to add products to the cart and how to build a cart drawer. When the storefront client is configured, the module adds Hydrogen's cart API at /api/cart, so you don't need any server code for the cart. The cart API keeps the ID of the cart in a cart cookie. In your components, you use the cart with CartProvider, useCart and useCartForm from @shopify/hydrogen/vue.

Hydrogen's cart forms are normal HTML forms that are sent to /api/cart, so adding to the cart also works before JavaScript has loaded. After that, Hydrogen updates the cart without a page load and shows the change right away, before Shopify confirms it. The components below use Nuxt UI and Nuxt Image.

To add fields such as metafields to the cart, set a cart fragment in the cart option.

Cart components

Create the cart components once, in a file in your app/utils directory:

app/utils/cart.ts
import type { CartDataFromHandlers, CartServerHandlers } from '@shopify/hydrogen'

import { createCartComponents } from '@shopify/hydrogen/vue'

export type CartLine = CartDataFromHandlers<CartServerHandlers>['lines']['nodes'][number]

export const { CartProvider, useCart, useCartForm } = createCartComponents<CartServerHandlers>()

Nuxt auto-imports useCart and useCartForm from there. Then wrap your app in CartProvider, which loads the cart after the page is mounted:

app/app.vue
<script setup lang="ts">
import { CartProvider } from '~/utils/cart'
</script>

<template>
  <UApp>
    <CartProvider>
      <NuxtLayout>
        <NuxtPage />
      </NuxtLayout>
    </CartProvider>
  </UApp>
</template>

Adding to the cart

To add a product to the cart, you need the ID of its variant, not of the product, such as selectedOrFirstAvailableVariant.id from the product page example. register binds each field of the form to the cart, and beforeSubmit opens the cart drawer while the line is added:

app/components/AddToCart.vue
<script setup lang="ts">
defineProps<{
  variantId: string
  available: boolean
}>()

const { formProps, register } = useCartForm()

const open = useState('cart-drawer', () => false)

const quantity = ref(1)
</script>

<template>
  <form v-bind="formProps({ beforeSubmit: () => { open = true } })">
    <input
      type="hidden"
      v-bind="register('merchandiseId', { value: variantId })"
    >

    <input
      type="hidden"
      v-bind="register('quantity', { value: quantity })"
    >

    <UInputNumber
      v-model="quantity"
      :min="1"
    />

    <UButton
      type="submit"
      v-bind="register('add')"
      :disabled="!available"
    >
      {{ available ? 'Add to cart' : 'Sold out' }}
    </UButton>
  </form>
</template>

Rendering the cart

useCart takes a selector, so a component only updates when the part of the cart that it reads changes. The drawer is a Nuxt UI USlideover, and the button that opens it is in its default slot. Totals are greyed out while Shopify recalculates them.

The checkout button is a normal link to the checkoutUrl of the cart, which is hosted by Shopify. Prices are formatted with Hydrogen's formatMoney. Use the totals of the cart instead of calculating them yourself, because they include discounts, taxes and duties.

app/components/CartDrawer.vue
<script setup lang="ts">
import type { MoneyV2 } from '@shopify/hydrogen'

import { formatMoney } from '@shopify/hydrogen'

const open = useState('cart-drawer', () => false)

const cart = useCart(state => state.data)
const loading = useCart(state => state.loading)
const totalsPending = useCart(state => state.pending.cost === true || state.revalidating)

const lines = computed(() => cart.value.lines.nodes)

const price = (money: MoneyV2) => formatMoney(money, { locale: 'en-US' }).toString()
</script>

<template>
  <USlideover
    v-model:open="open"
    title="Cart"
    :description="`${cart.totalQuantity} item${cart.totalQuantity === 1 ? '' : 's'}`"
  >
    <UButton
      icon="i-lucide-shopping-cart"
      color="neutral"
      variant="outline"
    >
      Cart ({{ cart.totalQuantity }})
    </UButton>

    <template #body>
      <p
        v-if="!loading && !lines.length"
        class="text-muted"
      >
        Your cart is empty.
      </p>

      <ul
        v-else
        class="divide-y divide-default"
      >
        <li
          v-for="line in lines"
          :key="line.id"
          class="py-4 first:pt-0"
        >
          <CartLineItem :line="line" />
        </li>
      </ul>
    </template>

    <template #footer>
      <div
        v-if="lines.length"
        class="flex w-full items-center justify-between"
      >
        <span
          class="text-lg font-semibold transition-opacity"
          :class="{ 'opacity-50': totalsPending }"
        >
          {{ price(cart.cost.subtotalAmount) }}
        </span>

        <UButton
          :to="cart.checkoutUrl"
          external
          size="lg"
          :disabled="totalsPending"
        >
          Checkout
        </UButton>
      </div>
    </template>
  </USlideover>
</template>

Each line is a form of its own. Its hidden set button comes first, so pressing Enter in the quantity input sets the entered quantity. The increase, decrease and remove buttons submit the same form with their own intent. Until Shopify has confirmed a new line, its ID starts with optimistic: and it can't be changed yet:

app/components/CartLineItem.vue
<script setup lang="ts">
import type { MoneyV2 } from '@shopify/hydrogen'
import type { CartLine } from '~/utils/cart'

import { formatMoney } from '@shopify/hydrogen'

const props = defineProps<{
  line: CartLine
}>()

const { formProps, register } = useCartForm()
const pendingLines = useCart(state => state.pending.lines)
const lineErrors = useCart(state => state.errors.lines)

const optimistic = computed(() => props.line.id.startsWith('optimistic:'))
const pending = computed(() => pendingLines.value.has(props.line.id))
const errors = computed(() => lineErrors.value.get(props.line.id)?.userErrors ?? [])

const price = (money: MoneyV2) => formatMoney(money, { locale: 'en-US' }).toString()
</script>

<template>
  <form
    v-bind="formProps()"
    class="flex gap-4"
  >
    <button v-bind="register('set')" />

    <input
      type="hidden"
      v-bind="register('lineId', { value: line.id })"
    >

    <NuxtImg
      v-if="line.merchandise?.image"
      :src="line.merchandise.image.url"
      :alt="line.merchandise.image.altText ?? line.merchandise.product.title"
      width="88"
      height="88"
      class="size-22 shrink-0 rounded-sm object-cover"
    />

    <div class="flex flex-1 flex-col gap-2">
      <p class="font-semibold">
        {{ line.merchandise?.product.title }}
      </p>

      <div
        class="flex items-center justify-between gap-2 transition-opacity"
        :class="{ 'opacity-50': pending }"
      >
        <div class="flex items-center">
          <UButton
            type="submit"
            v-bind="register('decrease')"
            icon="i-lucide-minus"
            color="neutral"
            variant="ghost"
            size="sm"
            aria-label="Decrease quantity"
            :disabled="optimistic"
          />

          <input
            v-bind="register('quantity', { value: line.quantity, interactive: true })"
            class="w-10 bg-transparent text-center"
            aria-label="Quantity"
            :disabled="optimistic"
          >

          <UButton
            type="submit"
            v-bind="register('increase')"
            icon="i-lucide-plus"
            color="neutral"
            variant="ghost"
            size="sm"
            aria-label="Increase quantity"
            :disabled="optimistic"
          />
        </div>

        <span class="font-semibold">{{ price(line.cost.totalAmount) }}</span>
      </div>

      <p
        v-for="error in errors"
        :key="error.message"
        role="alert"
        class="text-sm text-error"
      >
        {{ error.message }}
      </p>
    </div>

    <UButton
      type="submit"
      v-bind="register('remove')"
      icon="i-lucide-x"
      color="neutral"
      variant="ghost"
      size="sm"
      aria-label="Remove from cart"
      :disabled="optimistic"
    />
  </form>
</template>

Errors that don't belong to a line, such as a failed network request, are in useCart(state => state.errors), in its network and cart.userErrors fields.

Analytics

Shopify creates the cart events cart_updated, product_added_to_cart and product_removed_from_cart from this cart. With analytics enabled, call useCartAnalytics() once inside CartProvider, for example in your layout:

app/layouts/default.vue
<script setup lang="ts">
import { useCartAnalytics } from '@shopify/hydrogen/vue'

useCartAnalytics()
</script>

<template>
  <div>
    <CartDrawer />

    <slot />
  </div>
</template>

To report that the drawer was viewed, add const cartState = useCart(state => state) to the drawer and <ShopifyCartView :cart="cartState" /> to its #body slot. The component takes the whole cart state, not only its data, and reports the view once per mount, after the cart has loaded. It is only available while analytics is enabled. Don't publish the cart events yourself, or they are counted twice.

Customers and markets

When the customer account client is configured, the cart is linked to the customer. Logging in links the customer to the cart, so they are also logged in at checkout, and logging out removes them from the cart again.

The cart uses the locale of the request. To set the locales of your storefront, see markets.

A cart keeps the currency of the market it was created in. When a visitor switches to another country, update the buyer identity of the cart with the cartBuyerIdentityUpdate mutation before you load the new market, as the starter template does.
Published under the MIT License