Examples

Product Page

How to create a product page for your Shopify store in Nuxt

For your customers to view and buy your products, you need a product page with a variant picker, price, image and an add to cart button. This example uses Hydrogen's product form from @shopify/hydrogen/vue to select a variant and add it to the cart. The components below use Nuxt UI and Nuxt Image.

Classic T-shirt in Green

Classic T-shirt

$40.00

Crafted from organic cotton, this classic T-shirt features a relaxed fit, crew neckline and timeless look. Enjoy the breathable comfort of 100% organic cotton.

You need a product with a couple of options set up in your store. Make sure the Nuxt Shopify module is configured and your store is set up. The product form adds products to the cart, so your app needs the CartProvider from the cart example.

Fetching the product

Hydrogen's product form works with the product data from your query and doesn't fetch anything itself. It needs the options of the product, the selected variant, the variants next to it and two encoded fields that list which variants exist and which are available. The ProductFormFields fragment contains all of them:

graphql/product-form.ts
export const PRODUCT_FORM_FRAGMENT = `#graphql
  fragment ProductFormFields on Product {
    id
    handle
    title
    description
    requiresSellingPlan
    encodedVariantExistence
    encodedVariantAvailability
    featuredImage {
      ...ImageFields
    }
    priceRange {
      minVariantPrice {
        amount
        currencyCode
      }
    }
    options {
      ...ProductOptionFields
    }
    selectedOrFirstAvailableVariant(selectedOptions: $selectedOptions, ignoreUnknownOptions: true, caseInsensitiveMatch: true) {
      ...ProductVariantFields
    }
    adjacentVariants(selectedOptions: $selectedOptions, ignoreUnknownOptions: true, caseInsensitiveMatch: true) {
      ...ProductVariantFields
    }
  }
`

selectedOrFirstAvailableVariant returns the variant of the selected options, or the first available variant if no options are selected. adjacentVariants returns the variants that differ from it in one option, so the form can switch to them without another request. The variant fragment includes product { handle }, which tells the form when a variant belongs to another product, for example in a combined listing. The fields of the option, variant and image fragments are shown in the code tab.

Reading the selection from the URL

The selected options are kept in the URL, so a selected variant can be shared and stays selected after a refresh. Each option is one query parameter, such as ?Size=Large&Color=Red. getSelectedProductOptions reads them, and watch fetches the product again when they change:

app/pages/products/[handle].vue
const selectedOptions = computed(() => getSelectedProductOptions({ searchParams: toSearchParams(route.query) }))

const { data: product } = await useStorefrontData(`product-${route.params.handle}`, `#graphql
  query GetProductDetails($handle: String!, $selectedOptions: [SelectedOptionInput!]) {
    product(handle: $handle) {
      ...ProductFormFields
    }
  }
`, {
  variables: computed(() => ({
    handle: route.params.handle as string,
    selectedOptions: selectedOptions.value,
  })),
  transform: data => data.product,
  watch: [selectedOptions],
})

toSearchParams turns Nuxt's route.query into URLSearchParams, including parameters that appear more than once:

app/utils/search.ts
export const toSearchParams = (query: Record<string, string | null | (string | null)[]>) => new URLSearchParams(
  Object.entries(query).flatMap(([name, value]) => [value].flat().map(item => [name, item ?? ''])),
)

Creating the product form

Create the product components once with createProductComponents, typed with the fragment:

app/utils/product.ts
import type { SelectedOption } from '@shopify/hydrogen'

import { buildProductSelectionSearchParams } from '@shopify/hydrogen'
import { createProductComponents } from '@shopify/hydrogen/vue'

export type ProductFormData = ProductFormFieldsFragment & Required<Pick<ProductFormFieldsFragment, 'selectedOrFirstAvailableVariant'>>

export const { ProductProvider, useProductForm } = createProductComponents<ProductFormData>()

export const selectionPath = (path: string, selectedOptions: SelectedOption[], optionNames: string[], base: URLSearchParams) => {
  const params = buildProductSelectionSearchParams({ selectedOptions, optionNames, base })

  return params.size ? `${path}?${params}` : path
}

Hydrogen expects selectedOrFirstAvailableVariant to be set on the product, also when it is null. The generated fragment type marks the field as optional, so ProductFormData makes it required. selectionPath builds the URL of a selection with Hydrogen's buildProductSelectionSearchParams, which keeps other query parameters such as ?ref=newsletter.

Then wrap the product in ProductProvider:

app/pages/products/[handle].vue
<template>
  <div>
    <ProductProvider
      v-if="product"
      :product="product"
      :on-select="select"
    >
      <ProductForm :product="product" />
    </ProductProvider>
  </div>
</template>

onSelect runs when the customer selects an option value, and replaces the URL with the new selection:

app/pages/products/[handle].vue
const select = (result: ValidProductSelectionResult) => router.replace(selectionPath(
  route.path,
  result.selectedOptions,
  product.value?.options.map(option => option.name) ?? [],
  toSearchParams(route.query),
))

Option values

useProductForm returns the options of the product with the state of each value:

  • selected: the value is part of the current selection
  • exists: a variant exists for the value together with the other selected values
  • available: that variant is available for sale

Each value is a link to the URL of its selection, so selecting a value also works before JavaScript has loaded. A click on the link selects the value with register('optionValue', …).onClick() instead of following the link, and onSelect updates the URL:

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

const props = defineProps<{
  product: ProductFormFieldsFragment
}>()

const route = useRoute()
const form = useProductForm()

const choosable = computed(() => form.options.some(option => option.values.length > 1))

const to = (selectedOptions: SelectedOption[], handle: string) => selectionPath(
  handle === props.product.handle ? route.path : `/products/${handle}`,
  selectedOptions,
  form.options.map(option => option.name),
  toSearchParams(route.query),
)

const select = (event: MouseEvent, optionName: string, value: string) => {
  if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return

  event.preventDefault()

  form.register('optionValue', { optionName, value }).onClick()
}
</script>

<template>
  <div
    v-if="choosable"
    class="space-y-4"
  >
    <div
      v-for="option in form.options"
      :key="option.name"
    >
      <p class="mb-2 text-sm font-semibold text-muted">
        {{ option.name }}
      </p>

      <div class="flex flex-wrap gap-2">
        <template
          v-for="value in option.values"
          :key="value.name"
        >
          <NuxtLink
            v-if="value.handle !== product.handle"
            :to="to(value.selectedOptions, value.handle)"
            class="rounded-md border border-default px-3 py-1.5 text-sm hover:bg-elevated"
          >
            {{ value.name }}
          </NuxtLink>

          <button
            v-else-if="!value.exists"
            type="button"
            class="rounded-md border border-default px-3 py-1.5 text-sm opacity-25"
            :aria-pressed="value.selected"
            disabled
          >
            {{ value.name }}
          </button>

          <NuxtLink
            v-else
            v-slot="{ href }"
            :to="to(value.selectedOptions, value.handle)"
            custom
          >
            <a
              :href="href ?? undefined"
              class="rounded-md border px-3 py-1.5 text-sm"
              :class="[
                value.selected ? 'border-inverted bg-inverted text-inverted' : 'border-default hover:bg-elevated',
                { 'line-through opacity-50': !value.available },
              ]"
              :aria-current="value.selected ? 'true' : undefined"
              @click="select($event, option.name, value.name)"
            >
              {{ value.name }}
            </a>
          </NuxtLink>
        </template>
      </div>
    </div>
  </div>
</template>

The option picker is hidden when no option has more than one value. Values without a variant are disabled buttons. Sold out values stay links, so the customer can still select them and see that the variant is sold out. Clicks with a modifier key, for example to open the link in a new tab, work like normal links. A value that belongs to another product, for example in a combined listing, links to the page of that product.

Price and add to cart

form.selectedVariant is the variant of the current selection. The price comes from that variant, or from the lowest price of the product while no variant is selected, and Hydrogen's formatMoney formats it. canAddToCart checks that a variant is selected, that it is available and that the product doesn't require a selling plan:

app/components/ProductForm.vue
<script setup lang="ts">
import type { ProductFormData } from '~/utils/product'

import { canAddToCart, formatMoney } from '@shopify/hydrogen'

const props = defineProps<{
  product: ProductFormFieldsFragment
}>()

const form = useProductForm()

const quantity = ref(1)

const image = computed(() => form.selectedVariant?.image ?? props.product.featuredImage)
const price = computed(() => formatMoney(form.selectedVariant?.price ?? props.product.priceRange.minVariantPrice, { locale: 'en-US' }).toString())
const addable = computed(() => canAddToCart(props.product as ProductFormData, form.options))

const label = computed(() => {
  if (addable.value) return 'Add to cart'
  if (!form.selectedVariant) return 'Select options'

  return form.selectedVariant.availableForSale ? 'Unavailable' : 'Sold out'
})

const errors = computed(() => [...form.errors.userErrors, ...form.errors.warnings, ...form.errors.networkErrors])
</script>

<template>
  <form
    v-bind="form.formProps()"
    class="flex items-end gap-4"
  >
    <input
      type="hidden"
      v-bind="form.register('merchandiseId', {})"
    >

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

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

    <UButton
      v-bind="form.register('addToCart', {})"
      size="lg"
      :loading="form.pending.value"
      :disabled="!addable"
    >
      {{ label }}
    </UButton>
  </form>

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

The form sends the selected variant and the quantity to the cart. To open your cart drawer at the same time, pass a beforeSubmit callback to formProps, as in the cart example. form.errors holds the errors of the last submission, such as a quantity that is not in stock. The image, title and description are left out above. The full component is in the code tab.

Published under the MIT License