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:
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:
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.