Examples

Collection Filters

How to create collection filters for your Shopify store in Nuxt

Once you have a collection page, the next step is filtering and sorting. The Storefront API returns the filters a collection supports, and filters the products by the values you pass to the query. This example uses Hydrogen's CollectionProvider from @shopify/hydrogen/vue to keep the filters and the sort order in the URL. The URL has the same format as in Shopify's online store, such as ?filter.v.option.color=Red&sort_by=price-descending. The components below use Nuxt UI and Nuxt Image.

Availability
Price
Color
More filters
Classic Crewneck in Green
Classic Crewneck
This high-quality crewneck is perfect for your everyday look. Made with 100% cotton, it's soft, comfortable, and undeniably stylish. Full sleeved for a classic look and effortlessly versatile, this cotton crewneck is a must-have in any wardrobe.

from $120.00

Classic T-shirt in Green
Classic T-shirt
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.

from $28.00

Sweatpants in Green
Sweatpants
Soft and comfortable sweatpants in stylish shades. They are perfect for lounging with their cozy stretch fabric that offers just the right amount of warmth. Enjoy the ultimate relaxation experience!

from $24.50

Shorts in Green
Shorts
These shorts are designed to help you reach peak performance. Constructed with high performance nylon fabric in a variety of shades, they are built to last and provide maximum comfort.

from $45.00

Canvas Sneakers in Green
Canvas Sneakers
These high-quality canvas sneakers offer a comfortable fit and superior breathability, thanks to their cushioning midsoles and durable construction. An array of stylish colors adds to the appeal, making them perfect for casual wear. Slip them on and enjoy reliable performance and style that lasts.

from $40.00

High Top Sneakers
High Top Sneakers
These stylish and durable high top sneakers are perfect for any casual look, offering superior comfort and protection with their foam cushioning and reinforced heel support.

from $180.00

Gray Runners
Gray Runners
These gray runners are the perfect choice for running enthusiasts. These shoes provide superior breathability and comfort, so you can run longer with less fatigue. The lightweight design and airy mesh material make these shoes durable and lightweight, giving you the support you need for peak performance.

from $30.00

Leather Sneakers in White
Leather Sneakers
These leather sneakers combine comfort and style for the perfect professional look. The breathable leather material ensures breathability and provides a comfortable fit, perfect for the office and other formal occasions. The handmade design is stylish and guaranteed to last.

from $90.00

Soft Cotton Hoodie in Green, front
Soft Cotton Hoodie
This hoodie is the perfect choice for comfort and warmth. Meticulously crafted from 100% cotton, the hoodie features a soft, plush fleece interior and a unisex sizing design. Soft and lightweight, it's sure to be your go-to for chilly days.

from $90.00

Puffer in Green
Puffer
This light puffer vest is made from durable nylon and will keep you dry and comfortable in all weather. Its light coating provides reliable protection from wind and rain, and its versatile fit offers maximum mobility. Perfect for moderate temperatures and varied conditions.

from $48.00

Frontpack in Green
Frontpack
This frontpack is the perfect combination of form and function, with a modern, sporty design and patented technology that enables you to easily carry numerous items on the go. It's light, comfortable and has adjustable straps to fit all body types. Plus, its water-resistant outer shell ensures your items stay dry and secure.

from $200.00

Sunnies in Black
Sunnies
These modern sunglasses provide 100% UV400 protection from harmful sunrays and feature mirrored lenses for a timeless and stylish look. With lightweight construction and comfortable fit, you can look cool and stay safe in any situation.

from $25.00

This example reuses the ProductCard component and the ProductFields fragment from the collection page example. You also need a collection with a few products, and filters set up for it in Shopify's Search & Discovery app.

Fetching the filters

You don't need to hardcode the list of filters. The products connection has a filters field, which returns every filter the collection supports, with its type, its values and the number of products for each value:

products(first: $first, filters: $filters, sortKey: $sortKey, reverse: $reverse) {
  filters {
    ...FilterFields
  }
  nodes {
    ...ProductFields
  }
}

The filter fields are in a fragment of their own, which also gives you a FilterFieldsFragment type for the filter component:

graphql/filter.ts
export const FILTER_FRAGMENT = `#graphql
  fragment FilterFields on Filter {
    id
    label
    type
    values {
      id
      label
      count
      input
    }
  }
`

Reading the filters from the URL

parseCollectionParams reads the filters and the sort order from the URL and returns them in the format of the Storefront API. Pass them to the filters, sortKey and reverse arguments of the products connection:

app/pages/collections/[handle].vue
const search = computed(() => toSearchParams(route.query).toString())

const { data, status } = await useAsyncData(`collection-${handle}`, async () => {
  const dataSearch = search.value
  const { filters, sortKey, reverse } = parseCollectionParams(new URLSearchParams(dataSearch))

  const { data } = await storefront.request(query, {
    variables: {
      handle,
      first: 12,
      filters: filters as ProductFilter[],
      sortKey,
      reverse,
    },
  })

  return {
    dataSearch,
    currencyCode: data?.localization.country.currency.isoCode,
    collection: data?.collection,
  }
}, {
  watch: [search],
})

The page uses useAsyncData with useStorefront instead of useStorefrontData, because Hydrogen needs to know which URL the products were fetched for. The handler keeps it as dataSearch before the request starts. toSearchParams is the same helper as in the product page example and turns route.query into URLSearchParams. localization returns the currency of your store, which the price filter needs.

Adding the collection provider

CollectionProvider keeps track of the filters and the sort order in the URL. Pass it the collection handle with the dataSearch of the products, and the current URL as url-search:

app/pages/collections/[handle].vue
<template>
  <div>
    <CollectionProvider
      v-if="data?.collection"
      :data="{ handle, dataSearch: data.dataSearch }"
      :url-search="search"
      @change="navigate"
    >
      <div class="grid gap-8 md:grid-cols-4">
        <CollectionFilters
          :filters="data.collection.products.filters"
          :currency-code="data.currencyCode"
        />

        <div
          class="grid gap-4 grid-cols-1 sm:grid-cols-2 md:col-span-3 transition-opacity"
          :class="{ 'opacity-50': status === 'pending' }"
        >
          <ProductCard
            v-for="product in data.collection.products.nodes"
            :key="product.id"
            :product="product"
          />
        </div>
      </div>
    </CollectionProvider>
  </div>
</template>

When the customer changes a filter, the provider emits change with the new query string, and navigate goes to the new URL:

const navigate = (next: string) => navigateTo(`${route.path}${next}`, { replace: search.value.length > 0 })

The watch option of useAsyncData then fetches the products for the new URL.

The filter form

The filters are a form that is sent to the collection page with GET, so they also work without JavaScript. formProps from useCollectionForm handles the form in the browser instead, and updates the URL without loading the page again:

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

import { formatMoney, getSortByValue, isFilterInputActive, serializeCollectionParams } from '@shopify/hydrogen'
import { useCollection, useCollectionForm } from '@shopify/hydrogen/vue'

const props = defineProps<{
  filters: FilterFieldsFragment[]
  currencyCode?: string
}>()

const route = useRoute()

const state = useCollection()
const { formProps } = useCollectionForm()

const sortOptions = [
  { label: 'Featured', value: getSortByValue('COLLECTION_DEFAULT', false) },
  { label: 'Best selling', value: getSortByValue('BEST_SELLING', false) },
  { label: 'Price, low to high', value: getSortByValue('PRICE', false) },
  { label: 'Price, high to low', value: getSortByValue('PRICE', true) },
]

const sort = computed(() => getSortByValue(state.value.sortKey ?? 'COLLECTION_DEFAULT', state.value.reverse))
const price = computed(() => state.value.filters.find(filter => filter.price)?.price)

const symbol = computed(() => props.currencyCode
  ? formatMoney({ amount: '0', currencyCode: props.currencyCode }, { locale: 'en-US' }).currencyNarrowSymbol
  : undefined)

const toParam = (input: string) => {
  const [entry] = serializeCollectionParams({ filters: [JSON.parse(input) as ProductFilter], sortKey: undefined, reverse: false })

  return entry && { name: entry[0], value: entry[1] }
}

const groups = computed(() => props.filters.map(filter => ({
  ...filter,
  values: filter.values.map(value => ({
    ...value,
    param: toParam(value.input),
    active: isFilterInputActive(state.value.filters, value.input),
  })),
})))

const submit = (event: Event) => (event.target as HTMLInputElement).form?.requestSubmit()
</script>

Each filter value has an input field, which holds the filter as JSON. serializeCollectionParams turns it into the name and value of a checkbox, such as filter.v.option.color and Red, and isFilterInputActive checks whether the value is selected:

app/components/CollectionFilters.vue
<label
  v-for="value in filter.values"
  :key="value.id"
  class="flex items-center gap-2 text-sm"
>
  <input
    type="checkbox"
    :name="value.param?.name"
    :value="value.param?.value"
    :checked="value.active"
    class="accent-primary"
    @change="submit"
  >

  {{ value.label }} ({{ value.count }})
</label>

Checkboxes and the sort order submit the form as soon as they change. Without JavaScript, the button in the noscript element submits it.

The price filter has two number inputs with the fixed names filter.v.price.gte and filter.v.price.lte. They submit the form when they lose focus or when you press Enter. formatMoney returns the currency symbol for the currency of the query, which the inputs show in front of the price.

getSortByValue builds the values of the sort options, such as price-descending. These are the same values Shopify's online store uses, and parseCollectionParams reads them back from the URL.

Showing the products

The products are the nodes of the connection, so you can pass them to the ProductCard from the collection page example, as shown in the template above. While the products for a new URL are loading, status from useAsyncData is pending and the grid is faded out.

And that's it! Because the filters are in the URL, a filtered page can be shared and still works after a refresh.

Published under the MIT License