1 ---
2 sidebar_label: "Checkout Step 2: Set Address"
3 tags:
4 - cart
5 - storefront
6 products:
7 - cart
8 - customer
9 ---
10
11 import { CodeTabs, CodeTab } from "docs-ui"
12
13 export const metadata = {
14 title: `Checkout Step 2: Set Shipping and Billing Addresses`,
15 }
16
17 # {metadata.title}
18
19 In this guide, you'll learn how to set the cart's shipping and billing addresses. This typically should be the second step of the checkout flow, but you can also change the steps of the checkout flow as you see fit.
20
21 ## Approaches to Set the Cart's Addresses
22
23 A cart has shipping and billing addresses that customers need to set. You can either:
24
25 - [Show a form to enter the address](#approach-one-address-form);
26 - Or [allow the customer to pick an address from their account](#approach-two-select-customer-address).
27
28 This guide shows you how to implement both approaches. You can choose either or combine them, based on your use case.
29
30 ---
31
32 ## Approach One: Address Form
33
34 The first approach to setting the cart's shipping and billing addresses is to show a form to the customer to enter their address details.
35
36 Then, to update the cart's address, use the [Update Cart API route](!api!/store/carts/update-a-cart).
37
38 For example:
39
40 <Note title="Tip">
41
42 - This example uses the `useCart` hook defined in the [Cart React Context guide](../../cart/context/page.mdx).
43 - Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx).
44
45 </Note>
46
47 <CodeTabs group="store-request">
48 <CodeTab label="React" value="react">
49
50 export const highlights = [
51 ["4", "useCart", "The `useCart` hook was defined in the Cart React Context documentation."],
52 ["30", "address", "Assemble the address object to be used for both shipping and billing addresses."],
53 ["96", "", "The address's country can only be within the cart's region."]
54 ]
55
56 ```tsx highlights={highlights}
57 "use client" // include with Next.js 13+
58
59 import { useState } from "react"
60 import { useCart } from "@/providers/cart"
61 import { sdk } from "@/lib/sdk"
62
63 export default function CheckoutAddressStep() {
64 const { cart, setCart } = useCart()
65 const [loading, setLoading] = useState(false)
66 const [firstName, setFirstName] = useState("")
67 const [lastName, setLastName] = useState("")
68 const [address1, setAddress1] = useState("")
69 const [company, setCompany] = useState("")
70 const [postalCode, setPostalCode] = useState("")
71 const [city, setCity] = useState("")
72 const [countryCode, setCountryCode] = useState("")
73 const [province, setProvince] = useState("")
74 const [phoneNumber, setPhoneNumber] = useState("")
75
76 const updateAddress = (
77 e: React.MouseEvent<HTMLButtonElement, MouseEvent>
78 ) => {
79 if (!cart) {
80 return
81 }
82
83 e.preventDefault()
84 setLoading(true)
85
86 const address = {
87 first_name: firstName,
88 last_name: lastName,
89 address_1: address1,
90 company,
91 postal_code: postalCode,
92 city,
93 country_code: countryCode || cart.region?.countries?.[0].iso_2,
94 province,
95 phone: phoneNumber,
96 }
97
98 sdk.store.cart.update(cart.id, {
99 shipping_address: address,
100 billing_address: address,
101 })
102 .then(({ cart: updatedCart }) => {
103 setCart(updatedCart)
104 console.log(updatedCart)
105 })
106 .finally(() => setLoading(false))
107 }
108
109 return (
110 <form>
111 {!cart && <span>Loading...</span>}
112 <input
113 type="text"
114 placeholder="First Name"
115 value={firstName}
116 onChange={(e) => setFirstName(e.target.value)}
117 />
118 <input
119 type="text"
120 placeholder="Last Name"
121 value={lastName}
122 onChange={(e) => setLastName(e.target.value)}
123 />
124 <input
125 type="text"
126 placeholder="Address Line"
127 value={address1}
128 onChange={(e) => setAddress1(e.target.value)}
129 />
130 <input
131 type="text"
132 placeholder="Company"
133 value={company}
134 onChange={(e) => setCompany(e.target.value)}
135 />
136 <input
137 type="text"
138 placeholder="Postal Code"
139 value={postalCode}
140 onChange={(e) => setPostalCode(e.target.value)}
141 />
142 <input
143 type="text"
144 placeholder="City"
145 value={city}
146 onChange={(e) => setCity(e.target.value)}
147 />
148 <select
149 value={countryCode}
150 onChange={(e) => setCountryCode(e.target.value)}
151 >
152 {cart?.region?.countries?.map((country) => (
153 <option
154 key={country.iso_2}
155 value={country.iso_2}
156 >
157 {country.display_name}
158 </option>
159 ))}
160 </select>
161 <input
162 type="text"
163 placeholder="Province"
164 value={province}
165 onChange={(e) => setProvince(e.target.value)}
166 />
167 <input
168 type="tel"
169 placeholder="Phone Number"
170 value={phoneNumber}
171 onChange={(e) => setPhoneNumber(e.target.value)}
172 />
173 <button
174 disabled={!cart || loading}
175 onClick={updateAddress}
176 >
177 Save
178 </button>
179 </form>
180 )
181 }
182 ```
183
184 </CodeTab>
185 <CodeTab label="JS SDK" value="js-sdk">
186
187 ```ts
188 const cartId = localStorage.getItem("cart_id")
189
190 const address = {
191 first_name,
192 last_name,
193 address_1,
194 company,
195 postal_code,
196 city,
197 country_code,
198 province,
199 phone,
200 }
201
202 sdk.store.cart.update(cart.id, {
203 shipping_address: address,
204 billing_address: address,
205 })
206 .then(({ cart }) => {
207 // use cart...
208 console.log(cart)
209 })
210 ```
211
212 </CodeTab>
213 </CodeTabs>
214
215 In the example above:
216
217 - The same address is used for shipping and billing for simplicity. You can provide the option to enter both addresses instead.
218 - You send the address to the Update Cart API route under the `shipping_address` and `billing_address` request body parameters.
219 - The updated cart object is returned in the response.
220 - **React example:** in the address, the chosen country must be in the cart's region. So, only the countries part of the cart's region are shown in the Country input.
221
222 ---
223
224 ## Approach Two: Select Customer Address
225
226 The second approach to setting the cart's shipping and billing addresses is to allow the logged-in customer to select an address they added previously to their account.
227
228 To retrieve the logged-in customer's addresses, use the [List Customer Addresses API route](!api!/store/customers/list-customers-addresses). Then, once the customer selects an address, use the [Update Cart API route](!api!/store/carts/update-a-cart) to update the cart's addresses.
229
230 <Note title="Good to Know">
231
232 A customer's address and a cart's address are represented by different data models in the Medusa application, as they're managed by the [Customer Module](../../../commerce-modules/customer/page.mdx) and the [Cart Module](../../../commerce-modules/cart/page.mdx), respectively. So, addresses that the customer used previously during checkout aren't automatically saved to their account. You need to save the customer's address using the [Create Customer Address API route](!api!/store/customers/create-address).
233
234 </Note>
235
236 For example:
237
238 <Note title="Tip">
239
240 - This example uses the `useCart` hook defined in the [Cart React Context guide](../../cart/context/page.mdx).
241 - This example uses the `useCustomer` hook defined in the [Customer React Context guide](../../customers/context/page.mdx).
242
243 </Note>
244
245 <CodeTabs group="store-request">
246 <CodeTab label="React" value="react">
247
248 export const react2Highlights = [
249 ["4", "useCart", "The `useCart` hook was defined in the Cart React Context documentation."],
250 ["5", "useCustomer", "The `useCustomer` hook was defined in the Customer React Context documentation."],
251 ["12", "selectedAddress", "Store the ID of the address that the customer selects."],
252 ["21", "updateAddress", "Update the cart's shipping and billing addresses based on the selected address."],
253 ["32", "address", "Map the customer address to the expected cart address."],
254 ["45", "shipping_address", "Pass the selected address as a shipping address."],
255 ["46", "billing_address", "Pass the selected address as a billing address."],
256 ["58", "select", "Show a select input to select from the customer's addresses."],
257 ]
258
259 ```tsx highlights={react2Highlights}
260 "use client" // include with Next.js 13+
261
262 import { useEffect, useState } from "react"
263 import { useCart } from "@/providers/cart"
264 import { useCustomer } from "@/providers/customer"
265 import { sdk } from "@/lib/sdk"
266
267 export default function CheckoutAddressStep() {
268 const { cart, setCart } = useCart()
269 const { customer } = useCustomer()
270 const [loading, setLoading] = useState(false)
271 const [selectedAddress, setSelectedAddress] = useState(customer?.addresses[0]?.id || "")
272
273 useEffect(() => {
274 if (!customer) {
275 // TODO you can redirect here to another page or component that shows the address form
276 }
277 setSelectedAddress(customer?.addresses[0]?.id || "")
278 }, [customer])
279
280 const updateAddress = (
281 e: React.MouseEvent<HTMLButtonElement, MouseEvent>
282 ) => {
283 e.preventDefault()
284
285 const customerAddress = customer?.addresses.find((address) => address.id === selectedAddress)
286 if (!cart || !customerAddress) {
287 return
288 }
289 setLoading(true)
290
291 const address = {
292 first_name: customerAddress.first_name || "",
293 last_name: customerAddress.last_name || "",
294 address_1: customerAddress.address_1 || "",
295 company: customerAddress.company || "",
296 postal_code: customerAddress.postal_code || "",
297 city: customerAddress.city || "",
298 country_code: customerAddress.country_code || cart.region?.countries?.[0].iso_2,
299 province: customerAddress.province || "",
300 phone: customerAddress.phone || "",
301 }
302
303 sdk.store.cart.update(cart.id, {
304 shipping_address: address,
305 billing_address: address,
306 })
307 .then(({ cart: updatedCart }) => {
308 setCart(updatedCart)
309 })
310 .finally(() => setLoading(false))
311 }
312
313 return (
314 <form>
315 {!cart && <span>Loading...</span>}
316 {!customer?.addresses.length && <span>Customer doesn't have addresses</span>}
317 <select value={selectedAddress} onChange={(e) => setSelectedAddress(e.target.value)}>
318 {customer?.addresses.map((address) => (
319 <option value={address.id} key={address.id}>{address.country_code}</option>
320 ))}
321 </select>
322 <button
323 disabled={!cart || loading || !selectedAddress}
324 onClick={updateAddress}
325 >
326 Save
327 </button>
328 </form>
329 )
330 }
331 ```
332
333 </CodeTab>
334 <CodeTab label="JS SDK" value="js-sdk">
335
336 export const fetch2Highlights = [
337 ["1", "cartId", "Assuming the cart's ID is stored in the local storage."],
338 ["3", "retrieveCustomerAddresses", "Retrieve the customer's addresses from Medusa."],
339 ["11", "updateCartAddress", "Update the cart's address with the selected customer address."],
340 ["12", "address", "Map the customer address to the expected cart address."],
341 ["25", "shipping_address", "Pass the selected address as a shipping address."],
342 ["26", "billing_address", "Pass the selected address as a billing address."],
343 ]
344
345 ```ts highlights={fetch2Highlights}
346 const cartId = localStorage.getItem("cart_id")
347
348 const retrieveCustomerAddresses = () => {
349 sdk.store.customer.listAddress()
350 .then(({ addresses }) => {
351 // use addresses...
352 console.log(addresses)
353 })
354 }
355
356 const updateCartAddress = (customerAddress: Record<string, unknown>) => {
357 const address = {
358 first_name: customerAddress.first_name || "",
359 last_name: customerAddress.last_name || "",
360 address_1: customerAddress.address_1 || "",
361 company: customerAddress.company || "",
362 postal_code: customerAddress.postal_code || "",
363 city: customerAddress.city || "",
364 country_code: customerAddress.country_code || cart.region?.countries?.[0].iso_2,
365 province: customerAddress.province || "",
366 phone: customerAddress.phone || "",
367 }
368
369 sdk.store.cart.update(cart.id, {
370 shipping_address: address,
371 billing_address: address,
372 })
373 .then(({ cart: updatedCart }) => {
374 // use cart...
375 console.log(cart)
376 })
377 }
378 ```
379
380 </CodeTab>
381 </CodeTabs>
382
383 In the example above, you retrieve the customer's addresses and, when the customer selects an address, you update the cart's shipping and billing addresses with the selected address.
384
385 <Note title="Tip">
386
387 The JS SDK automatically sends an authenticated request as the logged-in customer as explained in the [Login Customer guide](../../customers/login/page.mdx). If you're using the Fetch API, you can either use `credentials: include` if the customer is already authenticated with a cookie session, or pass the Authorization Bearer token in the request's header.
388
389 </Note>
390
391 In the React example, you use the [Customer React Context](../../customers/context/page.mdx) to retrieve the logged-in customer, who has a list of addresses. You show a select input to select an address.
392
393 When the customer selects an address, you send a request to [Update Cart API route](!api!/store/carts/update-a-cart) passing the selected address as a shipping and billing address.