Pagination and sorting with commerce backends

When implementing pagination on your side using commercetools (or maybe another backend), you may see some products are displayed twice on different pages. The reason for this is pretty simple: If you don't provide sorting to the commerce backend while implementing pagination, the results you get back will be randomly sorted.

But don't worry we've got you covered and this article will explain how to prevent such cases from happening with Frontastic.

When you implement pagination with our streams, you'll need to modify the offset parameter of the stream and therefore switch through the pages. When no sorting is given - as is the default - the commerce backends may return the products randomly ordered. This may lead to a product showing up on page 1 but also on page 3 or any other page.

You can prevent this by setting a default sorting using our API decorators.

For listing products, the query() method on the product API should be used, so we'll need to implement a beforeQuery() decorator that sets the default sorting according to your needs on the ProductQuery before the query is actually executed.

Let's have a look at this short example:


namespace YourCustomerNamespace\ProductBundle\Domain;

use Frontastic\Common\ProductApiBundle\Domain\ProductApi;

class DefaultProductSortOrder
    public function beforeQuery(ProductApi $productApi, ProductApi\Query\ProductQuery $query): void
        if (isset($query->query)) {
            // Don't change sort order in real searches

        if (!$query->sortAttributes) {
            $query->sortAttributes = [
                'variants.attributes.popularity' => ProductApi\Query\ProductQuery::SORT_ORDER_DESCENDING,
                'variants.availability.availableQuantity' => ProductApi\Query\ProductQuery::SORT_ORDER_DESCENDING,
                'variants.attributes.brand_value' => ProductApi\Query\ProductQuery::SORT_ORDER_ASCENDING,

        // Ensure we always get a deterministic sort order
        $query->sortAttributes += [
            'variants.sku' => ProductApi\Query\ProductQuery::SORT_ORDER_ASCENDING,

This example will ignore searches where the query parameter is set and if no sortAttributes are set it will set the default ones. By default it'll also always add a sorting by sku to get deterministic results.

TIP: Be sure to name your file the same as your ClassName, so in this example, it would be: DefaultProductSortOrder.php.

Feel free to adapt this example to your needs and add to your codebase but you may need to adjust it to your actual available properties.

Don't forget to source the decorator properly as described in the API decorators article.

‹ Back to article list

Next article ›

Loaders in the frontend frameworks

Still need help? Contact us Contact us