Understanding the with parameter
Next, we'll highlight the best practices for easily building product listing pages. For this, we will take a closer look at the with
parameter.
The with
parameter is used to define which related data should be resolved when fetching products, categories, variants, etc. Each with
parameter shares a common structure but varies between ProductWith
, CategoryWith
, and even WishlistWith
and BasketWith
.
The most important data types to resolve are:
- attributes
- advanced attributes
- categories
- siblings
- variants
- images
- items/products (for basket and wishlist)
- different price information
If you don’t pass any with
parameters, the Storefront API will return as little information as possible. For instance, when fetching one or more products, we can instruct the Storefront API to return all the variants of each product, enabling us to display each size to the user. We can achieve this with the following:
await fetch({
with: {
variants: 'all'
}
})
Alternatively, we can specify more to get only the data we actually need:
with: {
variants: {
attributes: {
withKey: ['price', 'shopSize'],
},
advancedAttributes: {
withKey: ['deliveryForecast'],
},
},
}
Given the size and potential complexity of with
parameters in your code, we recommend placing them into separate files.
export const BASKET_WITH = {
items: {
variants: 'all',
...
}
}
export const WISHLIST_WITH = {...}
Dev-to-Dev Hint
To check whether you’ve configured your with
parameters correctly, try a manual call to Storefront API via Postman or a similar tool.
with: {
attributes: {
withKey: ['color', 'fit']
}
}
This can be converted into:
https://<bapi-url>/v1/products?shopId=<shop-id>&with=attributes:key(color):key(fit)
Example
Here is an example from the demo shop, where we’re fetching products by ID and resolving the product attributes: color
, brand
and name
, the variants, with their attributes price
and size
, the image, with some specific attributes, and the priceRange
, as well as the lowestPriorPrice
.
await fetchProducts({
ids: productIds.value,
with: {
attributes: {
withKey: ['color', 'brand', 'name'],
},
variants: {
attributes: {
withKey: ['price', 'size'],
},
lowestPriorPrice: true,
},
images: {
attributes: {
withKey: [
'imageType',
'imageView',
'imageBackground',
'imageKind',
],
},
},
priceRange: true,
lowestPriorPrice: true,
},
})
Next Steps
Query the database with the products-query.