Skip to main content

Variations Overview

Product variations allow you to offer multiple versions of a product based on attributes like size, color, or material. Elastic Path uses a parent/child model where variant products (children) are automatically generated from attribute combinations.

Common Use Cases

Variations are ideal for products that share core characteristics but differ in specific attributes:

  • Apparel: T-shirts in different sizes (S, M, L) and colors
  • Electronics: Phones with different storage capacities (128GB, 256GB, 512GB) and colors
  • Furniture: Chairs in different finishes (oak, walnut, cherry) and sizes
  • Software: Licenses with different durations (monthly, annual) and user limits
  • Consumables: Products in different quantities or packaging sizes

When to Use Variations

Use Variations When:

  • Products share the same base description and features
  • Differences are limited to specific attributes (size, color, material)
  • You want shoppers to select options from a single product page
  • Inventory needs to be tracked per variant

Don't Use Variations When:

  • Products have fundamentally different features or specifications
  • Products belong to different categories
  • The products don't share a common base (e.g., a laptop vs a mouse)
  • Each variant needs completely different product information architecture

Key Benefits

Using variations provides several advantages over creating separate products:

  • Automatic SKU Generation: Child products are created automatically from option combinations
  • Simplified Management: Update shared attributes once on the parent product
  • Better Shopper Experience: Customers can easily compare and select options on a single page
  • Inventory Tracking: Each variant maintains its own stock levels independently
  • Consistent Pricing: Apply pricing rules across all variants or set individual prices

Parent vs Child Products

Parent-Child Relationship

Parent Product

The parent product serves as a template that:

  • Defines the base product information
  • Contains variation options (size, color, etc.)
  • Is not directly purchasable
  • Generates child products based on attribute combinations

Child Products (Variants)

Child products are the actual purchasable SKUs that:

  • Inherit attributes from the parent
  • Have unique combinations of variation options
  • Contain specific pricing and inventory
  • Are what shoppers add to cart

What Frontend Developers Need to Know

When building variation selection in your storefront, keep these critical points in mind (for implementation details, see Handling Product Types):

Child Product IDs Change

  • Child product IDs are regenerated when the catalog is republished
  • This impacts saved carts, wishlists, and bookmarked URLs
  • Always fetch fresh child data using the parent's variation matrix

Cart Operations

  • Never attempt to add a parent product to cart - it will fail
  • Always use the child product ID for cart operations (see Select a Variation)
  • Each child maintains its own inventory level

Data Fetching Strategy

  • When on a parent product: Use its own variation data
  • When on a child product: Fetch the parent for variation context (see List Parent & Child Products)
  • Variation structure rarely changes (good candidate for caching)

Matrix Structure Varies

  • The variation matrix structure differs between products
  • Don't hardcode assumptions about which variation is at which level
  • Use the recursive lookup pattern for flexibility (see Understanding the Variation Matrix)

Variation Options & Attributes

Variations are built using:

  • Options: The variation types (e.g., "Size", "Color")
  • Option Values: Specific choices (e.g., "Small", "Medium", "Large")
  • Variation Matrix: All possible combinations of option values

Example: A t-shirt with 3 sizes and 4 colors generates 12 child products.

How Options Create Variants

When you define variations on a parent product, Elastic Path automatically generates all valid combinations as child products:

Real-World Example

Here's how variation data looks in practice:

// Parent product variation structure
const parentProduct = {
id: "a2c20cd6-5f34-47b6-9582-5044a5b50991",
attributes: {
name: "Classic T-Shirt",
sku: "TS-PARENT" // Parent SKU
},
meta: {
product_types: ["parent"],
variations: [
{
id: "10a35688-d48e-4228-8bd2-b3b5f71c992d",
name: "Size",
options: [
{ id: "8f749ee2-17fb-4876-963f-2f57c0dffd97", name: "Small" },
{ id: "d536955b-afa3-40e4-88cc-f6ee0248eeea", name: "Medium" },
{ id: "bbd91e51-690b-4743-9eb7-185a5bb88a62", name: "Large" }
]
},
{
id: "6cc91048-c351-4b35-aacd-8d613d515fa7",
name: "Color",
options: [
{ id: "801eabad-5108-4991-9f98-1830252214eb", name: "Blue" },
{ id: "84fd8ba0-9829-4b79-bfe9-ffee1ab60b95", name: "Red" }
]
}
]
}
}

// Resulting child product example
const childProduct = {
id: "ed971d72-ca0c-4472-86f9-db03227bebfd",
attributes: {
name: "Classic T-Shirt", // Inherits from parent
sku: "TS-S-BL", // Unique SKU for Small/Blue
price: [{ amount: 2499, currency: "USD" }]
// Note: inventory is managed via separate inventory API
},
meta: {
product_types: ["child"],
base_product_id: "a2c20cd6-5f34-47b6-9582-5044a5b50991" // Parent reference
}
}
Excluding Invalid Combinations

The variation matrix automatically creates all valid combinations. You can exclude specific combinations using variation modifiers.

For example, if "Extra Small" size isn't available in "Black" color, you can create a modifier to exclude that specific combination from being generated.

Common Implementation Patterns

Choose the right variation selection pattern based on your storefront needs:

PatternBest ForSEOPerformanceComplexityMobile UX
Navigation-BasedTraditional sites, SEO-critical✅ Excellent⚡ Slower🟢 Simple⭐⭐⭐
Dynamic StateSPAs, mobile apps❌ Limited⚡⚡⚡ Fast🟡 Moderate⭐⭐⭐⭐
HybridModern storefronts✅ Good⚡⚡ Fast🔴 Complex⭐⭐⭐⭐
Quick ShopProduct listings❌ None⚡⚡⚡ Fast🟢 Simple⭐⭐⭐⭐⭐

For detailed implementation examples and code for each pattern, see Variation Selection Patterns.

Understanding the Variation Matrix

The variation matrix is a nested data structure that maps option combinations to child product IDs. Key points:

  • Uses option IDs as keys (not variation IDs)
  • Nesting depth = number of variations (2 variations = 2 levels deep)
  • Order is unpredictable - use recursive lookup
  • Leaf values are child product IDs

Example structure:

{
"color_option_id": {
"size_option_id": "child_product_id"
}
}

For implementation details, including the recursive lookup function and complete examples, see Understanding the Variation Matrix.

Key Data Structures

Product Types

Every product has a type in meta.product_types[0]:

// Check product type
const productType = product.data?.meta?.product_types?.[0]
// Values: "parent", "child", "standard"

Variation Options

Available on parent products in meta.variations:

// Example variations structure
[
{
"id": "size_variation",
"name": "Size",
"options": [
{ "id": "small", "name": "Small" },
{ "id": "medium", "name": "Medium" }
]
}
]

Frontend Implementation Considerations

When building variation selection in your storefront, consider these key areas:

User Experience

Loading States

// Show loading state during variant switches
const [isLoadingVariant, setIsLoadingVariant] = useState(false);

async function handleVariantChange(childId: string) {
setIsLoadingVariant(true);
try {
const childData = await fetchProduct(childId);
updateDisplay(childData);
} finally {
setIsLoadingVariant(false);
}
}

Unavailable Combinations

// Disable unavailable option combinations
function isOptionAvailable(optionId: string, selectedOptions: Record<string, string>) {
const testOptions = { ...selectedOptions, [currentVariationId]: optionId };
const childId = getSkuIdFromOptions(Object.values(testOptions), variationMatrix);

if (!childId) return false;

// Optional: Check inventory via separate API call
// See inventory API documentation for stock checking
}

Mobile Considerations

  • Use native select dropdowns for better mobile UX
  • Consider sticky add-to-cart buttons
  • Minimize scrolling between option selection and cart button

Data Fetching Tips

  1. For Parent Products: Use variation data directly from parent
  2. For Child Products: Always fetch parent for full context
  3. Batch Operations: Fetch all children in one request when possible

Common Frontend Pitfalls

Avoid these common mistakes when implementing variations:

1. Not Checking Product Type

// ❌ Wrong: Assuming all products have variations
const variations = product.meta.variations; // May be undefined

// ✅ Correct: Check product type first
const productType = product.meta?.product_types?.[0];
if (productType === 'parent') {
const variations = product.meta.variations;
}

2. Trying to Add Parent to Cart

// ❌ Wrong: Adding parent product ID
addToCart(parentProduct.id); // Will fail!

// ✅ Correct: Only add child product IDs
const childId = getSkuIdFromOptions(selectedOptions, variationMatrix);
if (childId) {
addToCart(childId);
}

3. Hardcoding Matrix Structure

// ❌ Wrong: Assuming color is always first level
const childId = matrix[colorId][sizeId]; // May fail!

// ✅ Correct: Use recursive lookup
const childId = getSkuIdFromOptions([colorId, sizeId], matrix);

4. Not Pre-selecting on Child Products

// ❌ Wrong: Showing empty selections on child product page
// User loses context of what variant they're viewing

// ✅ Correct: Pre-select current variant's options
if (productType === 'child') {
const parent = await fetchParent(product.attributes.base_product_id);
const currentSelections = getCurrentSelections(product.id, parent.meta.variation_matrix);
setSelectedOptions(currentSelections);
}

See List Parent & Child Products for a complete example of pre-selecting options.

5. Ignoring Loading States

// ❌ Wrong: No feedback during variant switches
handleOptionSelect(optionId); // User doesn't know something is happening

// ✅ Correct: Show loading state
setIsLoading(true);
await handleOptionSelect(optionId);
setIsLoading(false);

6. Forgetting Mobile UX

// ❌ Wrong: Tiny color swatches on mobile
<div className="grid grid-cols-8 gap-1">
{colors.map(color => <ColorSwatch size="xs" />)}
</div>

// ✅ Correct: Mobile-friendly selection
<select onChange={handleColorSelect}>
{colors.map(color => <option value={color.id}>{color.name}</option>)}
</select>

For more UI patterns, see Variation Selection Patterns.

7. Not Handling Invalid Combinations

// ❌ Wrong: Allowing selection of unavailable combinations
// User gets error when trying to add to cart

// ✅ Correct: Validate combinations exist
const isValidCombination = getSkuIdFromOptions(selectedOptions, matrix) !== undefined;
setAddToCartEnabled(isValidCombination);

Troubleshooting

Common Issues and Solutions

"404 Not Found" when accessing child products

  • Cause: Child product IDs change when catalog is republished
  • Solution: Always fetch fresh child data using getByContextChildProducts

Empty variation_matrix on parent product

  • Cause: Catalog not published or variations not properly configured
  • Solution: Ensure catalog is published and variations have been built

"base_product_id" is missing on child product

  • Cause: Product is not actually a child variant
  • Solution: Check meta.product_types[0] equals "child"

Can't add parent product to cart

  • Cause: Parent products are templates, not purchasable items
  • Solution: Always add the specific child product ID to cart

Variation options not showing correctly

  • Cause: Incorrect option order when using variation_matrix
  • Solution: Use the same order as the variations array from parent

Inventory not showing on product

  • Cause: Inventory is managed separately via the inventory API
  • Solution: Use the getStock function from the SDK to fetch inventory data

Learning Path

Follow this recommended path to master variation implementation:

  1. Handling Product Types
    Learn to detect and handle different product types (parent, child, standard)

  2. List Parent & Child Products
    Fetch and display parent products with their child variants

  3. Select a Variation
    Implement variation selection and add variants to cart

  4. Understanding the Variation Matrix (Advanced)
    Deep dive into the variation matrix structure and recursive lookup

  5. Variation Selection Patterns
    Choose and implement the best UI pattern for your storefront

Next Steps

How-To Guides

References