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.
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.
Test it Out#
To test out the validation:
- Start the MedusaGo application.
- 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.
- Create a cart associated with that sales channel using a publishable API key linked to it.
- 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.