1 ---
2 tags:
3 - cart
4 - storefront
5 - fulfillment
6 products:
7 - cart
8 - fulfillment
9 ---
10
11 import { CodeTabs, CodeTab } from "docs-ui"
12
13 export const metadata = {
14 title: `Checkout Step 3: Choose Shipping Method`,
15 }
16
17 # {metadata.title}
18
19 In this guide, you'll learn how to implement the third step of the checkout flow, where the customer chooses the shipping method to receive their order's items. While this is typically the third step of the checkout flow, you can change the steps of the checkout flow as you see fit.
20
21 ## Shipping Flow in Storefront Checkout
22
23 To allow the customer to choose a shipping method, you:
24
25 ![Diagram showing the different steps of the shipping flow in storefront checkout](https://res.cloudinary.com/dza7lstvk/image/upload/v1743085465/Medusa%20Resources/shipping-checkout-flow_mfzdsh.jpg)
26
27 1. Retrieve the available shipping options for the cart using the [List Shipping Options API route](!api!/store/shipping-options/list-shipping-options-for-cart) and show them to the customer.
28 2. For shipping options whose `price_type=calculated`, you retrieve their calculated price using the [Calculate Shipping Option Price API Route](!api!/store/shipping-options/calculate-shipping-option-price).
29 - The Medusa application calculates the price using the associated fulfillment provider's logic, which may require sending a request to a third-party service.
30 3. When the customer chooses shipping option(s), you use the [Add Shipping Method to Cart API route](!api!/store/carts/add-shipping-method) to add the cart's shipping method(s). You can add a single shipping method or multiple methods in one request.
31
32 ---
33
34 ## How to Implement the Shipping Flow in Storefront Checkout?
35
36 For example:
37
38 <Note title="Tip">
39
40 - This example uses the `useCart` hook defined in the [Cart React Context guide](../../cart/context/page.mdx).
41 - Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx).
42
43 </Note>
44
45 <CodeTabs group="store-request">
46 <CodeTab label="React" value="react">
47
48 export const highlights = [
49 ["4", "useCart", "The `useCart` hook was defined in the Cart React Context documentation."],
50 ["26", "listCartOptions", "Retrieve available shipping methods of the customer's cart."],
51 ["42", "calculate", "Retrieve the price of every shipping method that has a calculated price."],
52 ["44", "data", "Pass in this property any data relevant to the fulfillment provider."],
53 ["72", "addShippingMethod", "Set the cart's shipping method using the selected shipping option."],
54 ["74", "data", "Pass in this property any data relevant to the fulfillment provider."]
55 ]
56
57 ```tsx highlights={highlights}
58 "use client" // include with Next.js 13+
59
60 import { useCallback, useEffect, useState } from "react"
61 import { useCart } from "@/providers/cart"
62 import { HttpTypes } from "@medusajs/types"
63 import { sdk } from "@/lib/sdk"
64
65 export default function CheckoutShippingStep() {
66 const { cart, setCart } = useCart()
67 const [loading, setLoading] = useState(false)
68 const [shippingOptions, setShippingOptions] = useState<
69 HttpTypes.StoreCartShippingOption[]
70 >([])
71 const [calculatedPrices, setCalculatedPrices] = useState<
72 Record<string, number>
73 >({})
74 const [
75 selectedShippingOption,
76 setSelectedShippingOption,
77 ] = useState<string | undefined>()
78
79 useEffect(() => {
80 if (!cart) {
81 return
82 }
83 sdk.store.fulfillment.listCartOptions({
84 cart_id: cart.id,
85 })
86 .then(({ shipping_options }) => {
87 setShippingOptions(shipping_options)
88 })
89 }, [cart])
90
91 useEffect(() => {
92 if (!cart || !shippingOptions.length) {
93 return
94 }
95
96 const promises = shippingOptions
97 .filter((shippingOption) => shippingOption.price_type === "calculated")
98 .map((shippingOption) =>
99 sdk.store.fulfillment.calculate(shippingOption.id, {
100 cart_id: cart.id,
101 data: {
102 // pass any data useful for calculation with third-party provider.
103 },
104 })
105 )
106
107 if (promises.length) {
108 Promise.allSettled(promises).then((res) => {
109 const pricesMap: Record<string, number> = {}
110 res
111 .filter((r) => r.status === "fulfilled")
112 .forEach((p) => (pricesMap[p.value?.shipping_option.id || ""] = p.value?.shipping_option.amount))
113
114 setCalculatedPrices(pricesMap)
115 })
116 }
117 }, [shippingOptions, cart])
118
119 const setShipping = (
120 e: React.MouseEvent<HTMLButtonElement, MouseEvent>
121 ) => {
122 if (!cart || !selectedShippingOption) {
123 return
124 }
125
126 e.preventDefault()
127 setLoading(true)
128
129 sdk.store.cart.addShippingMethod(cart.id, {
130 option_id: selectedShippingOption,
131 data: {
132 // TODO add any data necessary for
133 // fulfillment provider
134 },
135 })
136 .then(({ cart: updatedCart }) => {
137 setCart(updatedCart)
138 })
139 .finally(() => setLoading(false))
140 }
141
142 const formatPrice = (amount: number): string => {
143 return new Intl.NumberFormat("en-US", {
144 style: "currency",
145 currency: cart?.currency_code,
146 })
147 .format(amount)
148 }
149
150 const getShippingOptionPrice = useCallback((shippingOption: HttpTypes.StoreCartShippingOption) => {
151 if (shippingOption.price_type === "flat") {
152 return formatPrice(shippingOption.amount)
153 }
154
155 if (!calculatedPrices[shippingOption.id]) {
156 return
157 }
158
159 return formatPrice(calculatedPrices[shippingOption.id])
160 }, [calculatedPrices])
161
162 return (
163 <div>
164 {loading || !cart && <span>Loading...</span>}
165 <form>
166 <select
167 value={selectedShippingOption}
168 onChange={(e) => setSelectedShippingOption(
169 e.target.value
170 )}
171 >
172 {shippingOptions.map((shippingOption) => {
173 const price = getShippingOptionPrice(shippingOption)
174
175 return (
176 <option
177 key={shippingOption.id}
178 value={shippingOption.id}
179 disabled={price === undefined}
180 >
181 {shippingOption.name} - {price}
182 </option>
183 )
184 })}
185 </select>
186 <button
187 disabled={loading || !cart}
188 onClick={setShipping}
189 >
190 Save
191 </button>
192 </form>
193 </div>
194 )
195 }
196 ```
197
198 </CodeTab>
199 <CodeTab label="JS SDK" value="js-sdk">
200
201 export const fetchHighlights = [
202 ["5", "retrieveShippingOptions", "This function retrieves the shipping options of the customer's cart."],
203 ["13", "calculateShippingOptionPrices", "This function retrieves the prices of shipping options of type `calculated`."],
204 ["19", "data", "Pass in this property any data relevant to the fulfillment provider."],
205 ["39", "formatPrice", "This function formats a price based on the cart's currency."],
206 ["48", "getShippingOptionPrice", "This function gets the price of a shipping option based on its type."],
207 ["60", "setShippingMethod", "This function sets the shipping method of the cart using the selected shipping option."],
208 ["65", "data", "Pass in this property any data relevant to the fulfillment provider."],
209 ]
210
211 ```ts highlights={fetchHighlights}
212 const cartId = localStorage.getItem("cart_id")
213 let shippingOptions = []
214 const calculatedPrices: Record<string, number> = {}
215
216 const retrieveShippingOptions = () => {
217 const { shipping_options } = await sdk.store.fulfillment.listCartOptions({
218 cart_id: cartId,
219 })
220
221 shippingOptions = shipping_options
222 }
223
224 const calculateShippingOptionPrices = () => {
225 const promises = shippingOptions
226 .filter((shippingOption) => shippingOption.price_type === "calculated")
227 .map((shippingOption) =>
228 sdk.store.fulfillment.calculate(shippingOption.id, {
229 cart_id: cartId,
230 data: {
231 // pass any data useful for calculation with third-party provider.
232 },
233 })
234 )
235
236 if (promises.length) {
237 Promise.allSettled(promises).then((res) => {
238 res
239 .filter((r) => r.status === "fulfilled")
240 .forEach(
241 (p) => (
242 calculatedPrices[p.value?.shipping_option.id || ""] =
243 p.value?.shipping_option.amount
244 )
245 )
246 })
247 }
248 }
249
250 const formatPrice = (amount: number): string => {
251 return new Intl.NumberFormat("en-US", {
252 style: "currency",
253 // assuming you have access to the cart object.
254 currency: cart?.currency_code,
255 })
256 .format(amount)
257 }
258
259 const getShippingOptionPrice = (shippingOption: HttpTypes.StoreCartShippingOption) => {
260 if (shippingOption.price_type === "flat") {
261 return formatPrice(shippingOption.amount)
262 }
263
264 if (!calculatedPrices[shippingOption.id]) {
265 return
266 }
267
268 return formatPrice(calculatedPrices[shippingOption.id])
269 }
270
271 const setShippingMethod = (
272 selectedShippingOptionId: string
273 ) => {
274 sdk.store.cart.addShippingMethod(cartId, {
275 option_id: selectedShippingOptionId,
276 data: {
277 // TODO add any data necessary for
278 // fulfillment provider
279 },
280 })
281 .then(({ cart }) => {
282 // use cart...
283 console.log(cart)
284 })
285 }
286 ```
287
288 </CodeTab>
289 </CodeTabs>
290
291 In the example above, you:
292
293 - Retrieve the available shipping options of the cart to allow the customer to select from them using the [List Shipping Options API route](!api!/store/shipping-options/list-shipping-options-for-cart).
294 - For each shipping option, you retrieve its calculated price from the Medusa application using the [Calculate Shipping Option Price API Route](!api!/store/shipping-options/calculate-shipping-option-price).
295 - Once the customer selects a shipping option, you send a request to the [Add Shipping Method to Cart API route](!api!/store/carts/add-shipping-method) to update the cart's shipping method using the selected shipping option.
296
297 ---
298
299 ## Adding Multiple Shipping Methods
300
301 <Note>
302
303 Multiple shipping methods support is available since Medusa [v2.16.0](https://github.com/medusajs/medusa/releases/tag/v2.16.0).
304
305 </Note>
306
307 The [Add Shipping Method to Cart API route](!api!/store/carts/add-shipping-method) supports adding multiple shipping methods to a cart in a single request by passing an array of shipping method objects instead of a single object.
308
309 This is useful for scenarios where:
310
311 - Items require different shipping methods based on their shipping profiles
312 - Customers want to split their order across multiple carriers
313 - Different fulfillment providers handle different product types
314
315 ```tsx
316 // Add multiple shipping methods
317 sdk.store.cart.addShippingMethod(cart.id, [
318 {
319 option_id: "standard_shipping_option",
320 data: {
321 carrier: "fedex",
322 },
323 },
324 {
325 option_id: "express_shipping_option",
326 data: {
327 carrier: "ups",
328 },
329 },
330 ])
331 .then(({ cart: updatedCart }) => {
332 // handle updated cart
333 })
334 ```
335
336 When adding multiple shipping methods, Medusa automatically:
337
338 - Removes any existing shipping methods that conflict with the new ones based on the shipping profile
339 - Validates that each shipping option can be applied to the cart
340 - Ensures pricing is calculated correctly for all methods
341
342 ### data Request Body Parameter
343
344 When calculating a shipping option's price using the [Calculate Shipping Option Price API Route](!api!/store/shipping-options/calculate-shipping-option-price), or when setting the shipping method using the [Add Shipping Method to Cart API route](!api!/store/carts/add-shipping-method), you can pass a `data` request body parameter that holds data relevant for the fulfillment provider.
345
346 For example, you may pass a custom carrier code to the `data` parameter to identify the carrier of the shipping option if your fulfillment provider requires it.
347
348 This isn't implemented here as it's different for each provider. Refer to your fulfillment provider's documentation on details of expected data, if any.