Collection Filters
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.

from $120.00

from $28.00

from $24.50

from $45.00

from $40.00

from $180.00

from $30.00

from $90.00

from $90.00

from $48.00

from $200.00
<script setup lang="ts">
import type { ProductFilter } from '#shopify/storefront'
import { parseCollectionParams } from '@shopify/hydrogen'
import { CollectionProvider } from '@shopify/hydrogen/vue'
const route = useRoute()
const storefront = useStorefront()
const handle = route.params.handle as string
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(`#graphql
query GetCollectionFilters(
$handle: String!,
$first: Int,
$filters: [ProductFilter!],
$sortKey: ProductCollectionSortKeys,
$reverse: Boolean
) {
localization {
country {
currency {
isoCode
}
}
}
collection(handle: $handle) {
title
products(first: $first, filters: $filters, sortKey: $sortKey, reverse: $reverse) {
filters {
...FilterFields
}
nodes {
...ProductFields
}
}
}
}
`, {
variables: {
handle,
first: 12,
filters: filters as ProductFilter[],
sortKey,
reverse,
},
})
return {
dataSearch,
currencyCode: data?.localization.country.currency.isoCode,
collection: data?.collection,
}
}, {
watch: [search],
})
const navigate = (next: string) => navigateTo(`${route.path}${next}`, { replace: search.value.length > 0 })
</script>
<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>
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:
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:
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:
<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:
<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:
<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.
