Create Cart in Storefront

In this guide, you'll learn how to create and store a cart in your storefront.

Create Cart on First Access#

It's recommended to create a cart the first time a customer accesses a page in your storefront. Then, you can store the cart's ID in the localStorage and access it whenever necessary.

To create a cart, send a request to the Create Cart API route.

For example:

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

In this example, you create a cart by sending a request to the Create Cart API route.

The response of the Create Cart API route has a cart field, which is a cart object.

Refer to the Create Cart API reference for details on other available request parameters.

Cart's Sales Channel Scope#

As mentioned before, you must always pass the publishable API key in the header of the request (which is done automatically by the JS SDK, as explained in the Publishable API Keys guide). So, Medusa will associate the cart with the sales channel(s) of the publishable API key.

This is necessary, as only products matching the cart's sales channel(s) can be added to the cart. If you want to associate the cart with a different sales channel, or if the publishable API key is associated with multiple sales channels and you want to specify which one to use, you can pass the sales_channel_id parameter to the Create Cart API route with the desired sales channel's ID.

For example:

Code
1sdk.store.cart.create({2  region_id: region.id,3  sales_channel_id: "sc_123",4})5.then(({ cart }) => {6  // TODO use the cart...7  console.log(cart)8})

Associate Customer with Cart#

When the cart is created for a logged-in customer, it's automatically associated with that customer.

However, if the cart is created for a guest customer, then the customer logs in, then you have to set the cart's customer as explained in the Update Cart guide.


Store Cart Details in React Context#

If you're using React, it's then recommended to create a context that stores the cart details and make it available to all components in your application, as explained in the Cart React Context in Storefront guide.

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