Enforce Sales Channel Availability in Carts

In this guide, you'll learn how to reject product variants whose product isn't available in the cart's sales channel.

Why Medusa Doesn't Enforce This by Default#

A product's availability in a sales channel is a merchandising filter, not an authorization boundary.

Medusa applies it when you retrieve products. For example, the List Products Store API route only returns the products available in the sales channels of the publishable API key in the request. So, a product that you remove from a sales channel disappears from that channel's storefront.

Medusa doesn't apply that filter when a variant is added to a cart or when a cart is completed. A customer who knows a variant's ID can still add it to a cart scoped to a sales channel that the variant's product isn't available in.

Warning: Medusa doesn't enforce this by default because merchants use sales channels for merchandising, and rejecting items would break carts whenever a merchant changes a product's availability. If you rely on sales channels for legal or contractual restrictions, such as licensing agreements that forbid selling a product in a country, add the validation shown in this guide.

The inventory check that does run when you add an item to a cart, which the confirmVariantInventoryWorkflow performs, only checks the quantity available at the stock locations of the cart's sales channel. It doesn't check whether the variant's product is linked to that sales channel.

To enforce the availability, consume the validate hook of the workflows that add items to a cart and complete a cart. A workflow hook is a point in a workflow where you can inject custom functionality as a step function. If the step function throws an error, the workflow stops and the API route returns the error.

Note: This guide doesn't cover draft orders that admin users create in the dashboard, as it's assumed that merchants don't need to enforce sales channel availability for them.

Test it Out#

To test out the validation:

  1. Start the MedusaGo application.
  2. In the Medusa Admin dashboard, add a product that doesn't belong to a sales channel, or remove a product from a sales channel, as explained in the user guide.
  3. Create a cart associated with that sales channel using a publishable API key linked to it.
  4. Send a request to the Add Line Item Store API route with a variant of the product you removed.

The request returns a response with the 400 status code and the error message you specified.

Found a problem with this page?Report Issue
Edited Nov 14·Edit this page