Retrieve Nested Categories in Storefront

In this guide, you'll learn how to retrieve nested categories in the storefront.

How to Retrieve Nested Categories in Storefront?#

A product category has parent and child categories. For example, a "Shoes" category can have a "Running Shoes" child category.

There are two ways to retrieve nested categories:


Retrieve Nested Categories of a Category#

To retrieve the child or nested categories of a category in your storefront, pass to the Get a Category API Route the following query parameters:

  • include_descendants_tree=true to retrieve each category's nested categories at all levels.
  • Add category_children to fields, which is the field that will hold a category's nested categories.
    • You can either pass *category_children to retrieve all fields of a child category, or specify the fields specifically to avoid a large response size. For example, field=category_children.id,category_children.name.

For example:

Tip: Learn how to install and configure the JS SDK in the JS SDK documentation.

In this example, you retrieve the nested categories of a category by passing the include_descendants_tree query parameter to the Get a Category API Route.

The response has a product_category field, which is a product category object. It will have a category_children field, which is an array of product category objects.

Then, in the React component, you show a category's children by iterating over the category_children field.


Retrieve Categories as a Hierarchy#

Alternatively, you may want to retrieve all categories as a hierarchy.

To do this, you can pass the include_descendants_tree query parameter to the List Product Categories API Route, along with the parent_category_id query parameter set to null. This ensures that only categories with children are retrieved at the top level.

For example:

In this example, you retrieve all categories as a hierarchy by passing the include_descendants_tree query parameter to the List Product Categories API Route.

The response has a product_categories field, which is an array of product category objects.

Each category will have a category_children field, which is an array of product category objects.

You can then show the categories in a tree structure by iterating over the product_categories field and displaying the category_children field for each category.

Was this page helpful?
Ask Anything
FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break