Raw
1 ---
2 tags:
3 - cart
4 - storefront
5 products:
6 - cart
7 ---
8
9 import { CodeTabs, CodeTab, Prerequisites } from "docs-ui"
10
11 export const metadata = {
12 title: `Create Cart in Storefront`,
13 }
14
15 # {metadata.title}
16
17 In this guide, you'll learn how to create and store a cart in your storefront.
18
19 ## Create Cart on First Access
20
21 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.
22
23 To create a cart, send a request to the [Create Cart API route](!api!/store/carts/create-cart).
24
25 For example:
26
27 <Note title="Tip">
28
29 Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx).
30
31 </Note>
32
33 <CodeTabs group="store-request">
34 <CodeTab label="React" value="react">
35
36 export const highlights = [
37 ["9", "region", "Assuming you previously retrieved the chosen region."],
38 ["17", "cartId", "Retrieve the cart ID from `localStorage`, if exists."],
39 ["24", "create", "Send a request to create the cart."],
40 ["25", "region_id", "Associate the cart with the chosen region for accurate pricing."],
41 ["28", "setItem", "Set the cart's ID in the `localStorage`."]
42 ]
43
44 ```tsx highlights={highlights}
45 "use client" // include with Next.js 13+
46
47 import { useEffect } from "react"
48 import { sdk } from "@/lib/sdk"
49 // other imports...
50
51 export default function Home() {
52 // TODO assuming you have the region retrieved
53 const region = {
54 id: "reg_123",
55 // ...
56 }
57
58 // ...
59
60 useEffect(() => {
61 const cartId = localStorage.getItem("cart_id")
62 if (cartId) {
63 // customer already has a cart created
64 return
65 }
66
67 // create a cart and store it in the localStorage
68 sdk.store.cart.create({
69 region_id: region.id,
70 })
71 .then(({ cart }) => {
72 localStorage.setItem("cart_id", cart.id)
73 })
74 }, [])
75
76 // ...
77 }
78 ```
79
80 </CodeTab>
81 <CodeTab label="JS SDK" value="js-sdk">
82
83 export const fetchHighlights = [
84 ["2", "region_id", "Associate the cart with the chosen region for accurate pricing."],
85 ["5", "setItem", "Set the cart's ID in the `localStorage`."]
86 ]
87
88 ```ts highlights={fetchHighlights}
89 sdk.store.cart.create({
90 region_id: region.id,
91 })
92 .then(({ cart }) => {
93 localStorage.setItem("cart_id", cart.id)
94 })
95 ```
96
97 </CodeTab>
98 </CodeTabs>
99
100 In this example, you create a cart by sending a request to the [Create Cart API route](!api!/store/carts/create-cart).
101
102 The response of the Create Cart API route has a `cart` field, which is a [cart object](!api!/store/carts/schema).
103
104 Refer to the [Create Cart API reference](!api!/store/carts/create-cart) for details on other available request parameters.
105
106 ### Cart Currency
107
108 A cart's currency is set from the region you associate it with. If you pass a `currency_code` when creating a cart, it must match the region's currency. Otherwise, an error is thrown.
109
110 To avoid errors, omit `currency_code` and let Medusa set it from the region automatically.
111
112 <Note>
113
114 This behavior is enforced since Medusa [v2.21.0](https://github.com/medusajs/medusa/releases/tag/v2.21.0).
115
116 </Note>
117
118 ---
119
120 ### Cart's Sales Channel Scope
121
122 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](../../publishable-api-keys/page.mdx) guide). So, Medusa will associate the cart with the sales channel(s) of the publishable API key.
123
124 This is necessary, as the cart's sales channel scopes the products you retrieve for the storefront, the available inventory, and the sales channel of the order created from 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](!api!/store/carts/create-cart) with the desired sales channel's ID.
125
126 <Note>
127
128 Medusa doesn't reject a product variant added to the cart when its product isn't available in the cart's sales channel. Sales channel availability filters the products you retrieve, but Medusa doesn't enforce it when adding items to the cart. Refer to the [Enforce Sales Channel Availability in Carts](../../../commerce-modules/cart/sales-channel-availability/page.mdx) guide to learn how to add that validation.
129
130 </Note>
131
132 For example:
133
134 ```ts
135 sdk.store.cart.create({
136 region_id: region.id,
137 sales_channel_id: "sc_123",
138 })
139 .then(({ cart }) => {
140 // TODO use the cart...
141 console.log(cart)
142 })
143 ```
144
145 ---
146
147 ## Associate Customer with Cart
148
149 When the cart is created for a logged-in customer, it's automatically associated with that customer.
150
151 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](../update/page.mdx#set-carts-customer) guide.
152
153 ---
154
155 ## Set Cart's Locale
156
157 <Prerequisites
158 items={[
159 {
160 text: "Translation Module Configured",
161 link: "/commerce-modules/translation#configure-translation-module",
162 }
163 ]}
164 />
165
166 By default, items in the cart will have their associated product's original content. If your storefront supports [localization](../../localization/page.mdx), you can set the cart's locale to ensure that the item contents are in the customer's preferred language.
167
168 You can set the cart's locale by passing the `locale` request body parameter to the [Create Cart API route](!api!/store/carts/create-cart). For example:
169
170 ```ts
171 sdk.store.cart.create({
172 region_id: region.id,
173 // you can also retrieve the locale from sdk.getLocale()
174 locale: "fr-FR",
175 })
176 .then(({ cart }) => {
177 // TODO use the cart...
178 console.log(cart)
179 })
180 ```
181
182 When the cart's locale is set, the cart's items will have their content in the specified locale if translations are available.
183
184 You can also [update the cart's locale](../update/page.mdx#set-cart-locale) later if the customer changes their language preference.
185
186 ---
187
188 ## Store Cart Details in React Context
189
190 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](../context/page.mdx) guide.