1 ---
2 tags:
3 - storefront
4 - cart
5 - product
6 - payment
7 - fulfillment
8 - order
9 - region
10 - checkout
11 - example
12 products:
13 - cart
14 - product
15 - payment
16 - fulfillment
17 - order
18 - region
19 - sales channel
20 ---
21
22 import { Card, Prerequisites, Details } from "docs-ui"
23 import { Github } from "@medusajs/icons"
24
25 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1739360151/Medusa%20Resources/Express_Checkout_Guide_2025_yizn34.jpg"
26
27 export const metadata = {
28 title: `Implement Express Checkout with Medusa`,
29 openGraph: {
30 images: [
31 {
32 url: ogImage,
33 width: 800,
34 height: 450,
35 type: "image/jpeg"
36 }
37 ],
38 },
39 twitter: {
40 images: [
41 {
42 url: ogImage,
43 width: 800,
44 height: 450,
45 type: "image/jpeg"
46 }
47 ]
48 }
49 }
50
51 # {metadata.title}
52
53 In this guide, you'll learn how to create an express checkout storefront with Medusa.
54
55 When you install a Medusa application, you get a fully-fledged commerce server and an admin dashboard to manage the commerce store's data. As for the storefront, you can either install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), or create a custom storefront with your preferred tech stack, design, and features. Medusa's [architecture](!docs!/learn/introduction/architecture) is flexible and customizable, allowing you to build a storefront that fits your use case.
56
57 An express checkout storefront is a streamlined shopping experience that focuses on reducing friction during the checkout process, allowing customers to quickly and easily buy products with minimal input. When you have an express checkout storefront, you share a link to purchase one of your products, either through social media, blog posts, or other promotional campaigns, and the customer can complete the purchase with minimal effort.
58
59 ### Summary
60
61 In this guide, you'll learn how to:
62
63 - Install and set up Medusa.
64 - Create a custom express checkout storefront with Next.js.
65
66 ![Express checkout storefront interface showing a single-page checkout flow with product selection](https://res.cloudinary.com/dza7lstvk/image/upload/v1739344861/Medusa%20Resources/Screenshot_2025-02-12_at_9.20.09_AM_ufqdi3.png)
67
68 You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
69
70 <Card
71 title="Example Repository"
72 text="Find the full code of the guide in this repository."
73 href="https://github.com/medusajs/examples/tree/main/express-checkout-storefront"
74 icon={Github}
75 />
76
77 ---
78
79 ## Step 1: Install a Medusa Application
80
81 <Prerequisites items={[
82 {
83 text: "Node.js v20.19.0+ or v22.12.0+",
84 link: "https://nodejs.org/en/download"
85 },
86 {
87 text: "Git CLI tool",
88 link: "https://git-scm.com/downloads"
89 },
90 {
91 text: "PostgreSQL",
92 link: "https://www.postgresql.org/download/"
93 }
94 ]} />
95
96 Start by installing the Medusa application on your machine with the following command:
97
98 ```bash npx2yarnExec
99 npx create-medusa-app@latest
100 ```
101
102 You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js Starter Storefront, choose `N` for no. You'll create a custom storefront instead.
103
104 Afterwards, the installation process will start, which will install the Medusa application in a directory with your project's name. Once the installation finishes successfully, the Medusa Admin dashboard will open in your browser at `http://localhost:9000/app` with a form to create a new user. Enter the user's credential and submit the form.
105
106 Afterwards, you can login with the new user and explore the dashboard.
107
108 <Note title="Ran to Errors?">
109
110 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
111
112 </Note>
113
114 ### Change CORS Configurations
115
116 The Medusa application enforces Cross Origin Resource Sharing (CORS) security, which means you can only access the Medusa API from configured origins.
117
118 The Next.js development server will run on port `3000` by default, which isn't a configured origin in the Medusa application. To add it to configured origins, change the value of `STORE_CORS` and `AUTH_CORS` in the Medusa application's `.env` file to the following:
119
120 ```plain title=".env"
121 STORE_CORS=http://localhost:3000
122 AUTH_CORS=http://localhost:5173,http://localhost:9000,http://localhost:3000
123 ```
124
125 You can add other origins as well if necessary.
126
127 Learn more about CORS configurations in [this guide](!docs!/learn/configurations/medusa-config#httpauthcors).
128
129 ### Allow Cart Variant Option Fields
130
131 Medusa restricts the fields that you can request from a Store API route through an allowed-fields list. Later in this guide, you'll retrieve a cart with its line items' variant options and its products' options, which the cart routes don't allow by default. Medusa omits any field that isn't allowed from the response.
132
133 To allow those fields, create the file `src/api/middlewares.ts` in the Medusa application with the following content:
134
135 ```ts title="src/api/middlewares.ts"
136 import {
137 allowFields,
138 defineMiddlewares,
139 } from "@medusajs/framework/http"
140
141 export default defineMiddlewares({
142 routes: [
143 {
144 matcher: "/store/carts",
145 middlewares: [
146 allowFields(
147 "items.variant.options",
148 "items.product.options"
149 ),
150 ],
151 },
152 ],
153 })
154 ```
155
156 <Note>
157
158 `allowFields` is available since Medusa [v2.21.0](https://github.com/medusajs/medusa/releases/tag/v2.21.0). In earlier versions, write the middleware yourself, as explained in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields#how-to-override-allowed-fields-of-medusas-api-routes) documentation.
159
160 </Note>
161
162 <Note>
163
164 The Store Cart API routes expand at most three levels of relations, so you can't request `items.variant.options.option` to get an option's title. Instead, you allow `items.product.options`, which holds the same titles at three levels, and match each variant option to its product option in the storefront. Learn more in the [storeRelationsLimit](!docs!/learn/configurations/medusa-config#httpstorerelationslimit) configuration.
165
166 </Note>
167
168 <Note title="Important">
169
170 Don't add a `method` or `methods` key to the middleware's object. Medusa runs a method-scoped middleware after it validates the query parameters, so it has no effect there.
171
172 </Note>
173
174 Learn more about allowed fields and how to override them in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields) documentation.
175
176 ---
177
178 ## Step 2: Install Next.js Project
179
180 You'll create the express checkout storefront using Next.js. So, to create a Next.js project, run the following command in a directory separate from the Medusa application:
181
182 ```bash npx2yarnExec
183 npx create-next-app@latest express-checkout
184 ```
185
186 Answer the installation prompts by choosing the default values:
187
188 ```bash
189 Would you like to use TypeScript? Yes
190 Would you like to use ESLint? Yes
191 Would you like to use Tailwind CSS? Yes
192 Would you like your code inside a `src/` directory? No
193 Would you like to use App Router? (recommended) Yes
194 Would you like to use Turbopack for `next dev`? No
195 Would you like to customize the import alias (`@/*` by default)? No
196 ```
197
198 After the installation finishes, your Next.js project is installed in an `express-checkout` directory.
199
200 ---
201
202 ## Step 3: Install Medusa Dependencies
203
204 Before you start implementing the express checkout flow, you'll install the dependencies necessary for your storefront development.
205
206 ### Install Medusa UI
207
208 Medusa provides a [UI Library](!ui!) that provides the primitives to build applications based on Medusa's design system. To install the UI library, run the following command in your Next.js project:
209
210 ```bash npm2yarn
211 npm install @medusajs/ui@latest @medusajs/ui-preset@latest @medusajs/icons@latest
212 ```
213
214 You install three packages:
215
216 - `@medusajs/ui`: The main [UI library](!ui!).
217 - `@medusajs/ui-preset`: The design and style presets for the UI library.
218 - `@medusajs/icons`: A package that has [Medusa icons](!ui!/icons/overview) you can use in your application.
219
220 Next, to use Medusa's design system in your storefront, change the content of `tailwind.config.ts` to the following:
221
222 ```ts title="tailwind.config.ts"
223 import path from "path"
224 import type { Config } from "tailwindcss"
225
226 // get the path of the dependency "@medusajs/ui"
227 const medusaUI = path.join(
228 path.dirname(require.resolve("@medusajs/ui")),
229 "**/*.{js,jsx,ts,tsx}"
230 )
231
232 export default {
233 presets: [require("@medusajs/ui-preset")],
234 content: [
235 "./app/**/*.{js,ts,jsx,tsx}",
236 "./components/**/*.{js,ts,jsx,tsx}",
237 "@/providers/**/*.{js,ts,jsx,tsx}",
238 medusaUI,
239 ],
240 darkMode: "class",
241 theme: {
242 extend: {},
243 },
244 plugins: [],
245 } satisfies Config
246 ```
247
248 This adds Medusa's UI presets to Tailwind CSS's presets and includes the Medusa UI components in the Tailwind CSS content, ensuring that the styles of the UI components aren't removed by tree-shaking.
249
250 ### Install Medusa JS SDK
251
252 To interact with the [Medusa API](!api!/store) in your storefront, you'll use the [Medusa JS SDK](../../../js-sdk/page.mdx). Install the SDK by running the following command in your Next.js project:
253
254 ```bash npm2yarn
255 npm install @medusajs/js-sdk@latest @medusajs/types@latest
256 ```
257
258 Aside from the SDK, you also install the `@medusajs/types` package, which provides TypeScript types useful for your development with the SDK.
259
260 Next, to use the SDK, you'll export a configured instance and re-use it across your application. So, create the file `lib/sdk.ts` with the following content:
261
262 ![Project directory structure showing the newly created 'lib' folder containing the 'sdk.ts' file, which exports a configured Medusa SDK instance for connecting to the backend API](https://res.cloudinary.com/dza7lstvk/image/upload/v1735815487/Medusa%20Resources/express-checkout-1_vrudhk.jpg)
263
264 export const sdkHighlights = [
265 ["6", "NEXT_PUBLIC_MEDUSA_BACKEND_URL", "Set the backend URL from an environment variable."],
266 ["12", "NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY", "Set the publishable API key from an environment variable."],
267 ]
268
269 ```ts title="lib/sdk.ts" highlights={sdkHighlights}
270 import Medusa from "@medusajs/js-sdk"
271
272 export let MEDUSA_BACKEND_URL = "http://localhost:9000"
273
274 if (process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL) {
275 MEDUSA_BACKEND_URL = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL
276 }
277
278 export const sdk = new Medusa({
279 baseUrl: MEDUSA_BACKEND_URL,
280 debug: process.env.NODE_ENV === "development",
281 publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
282 })
283 ```
284
285 This file exports a configured instance of the Medusa SDK that you can use to send requests to the Medusa application. To configure the SDK, you use the following environment variables:
286
287 - `NEXT_PUBLIC_MEDUSA_BACKEND_URL`: The URL of the Medusa application server. By default, it's set to `http://localhost:9000`.
288 - `NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY`: The publishable API key of the Medusa application. You can find this key in the Medusa Admin dashboard under Settings -> Publishable API Keys.
289
290 ![Navigation path in Medusa Admin dashboard: Settings showing "Publishable API Key" option, with the publishable API key displayed and a copy button to retrieve the token for storefront configuration](https://res.cloudinary.com/dza7lstvk/image/upload/v1735810830/Medusa%20Resources/Screenshot_2025-01-02_at_11.36.20_AM_gw7i7h.png)
291
292 ---
293
294 ## Step 4: Create React Context Providers
295
296 In your storefront, you'll need to access the following resources across components:
297
298 - The selected region. In Medusa, a region represents one or more countries you serve customers in. Each region can have different settings, such as currency codes, prices, payment providers, and more. You create regions in the Medusa Admin, and you can allow the customer to choose their region in the storefront.
299 - The customer's cart, which you'll use to add the product to purchase, set shipping and payment details, and create an order.
300
301 To easily access and manage these resources, you'll wrap your storefront with two React context providers: `RegionProvider` and `CartProvider`. You'll implement these providers in this step.
302
303 ### Create Region Provider
304
305 To create the region provider, create the file `providers/region.tsx` with the following content:
306
307 ![Project directory tree showing the newly created 'providers' folder containing the 'region.tsx' file, which implements React context for managing regional settings and currency selection across the storefront](https://res.cloudinary.com/dza7lstvk/image/upload/v1735815539/Medusa%20Resources/express-checkout-2_htf5ke.jpg)
308
309 export const regionProviderHighlights1 = [
310 ["9", "region", "The region selected by the customer."],
311 ["10", "regions", "A list of regions available in the Medusa application."],
312 ["11", "setRegion", "A function to set the selected region."],
313 ]
314
315 ```tsx title="providers/region.tsx" highlights={regionProviderHighlights1}
316 "use client"
317
318 import {
319 createContext,
320 } from "react"
321 import { HttpTypes } from "@medusajs/types"
322
323 type RegionContextType = {
324 region?: HttpTypes.StoreRegion
325 regions: HttpTypes.StoreRegion[]
326 setRegion: React.Dispatch<
327 React.SetStateAction<HttpTypes.StoreRegion | undefined>
328 >
329 }
330
331 const RegionContext = createContext<RegionContextType | null>(null)
332
333 // TODO add provider component
334 ```
335
336 So far, you've created `RegionContextType` which represents the data that the provider's children can access. It holds:
337
338 - `region`: The selected region.
339 - `regions`: A list of regions available in the Medusa application.
340 - `setRegion`: A function to set the selected region.
341
342 Next, you'll create the provider component that wraps the storefront with the region context. Add the following content to the file:
343
344 export const regionProviderHighlights2 = [
345 ["16", "regions", "A state variable that will hold the list of regions available in the Medusa application."],
346 ["19", "region", "A state variable that will hold the selected region."],
347 ]
348
349 ```tsx title="providers/region.tsx" highlights={regionProviderHighlights2}
350 // other imports...
351 import {
352 // other imports...
353 useState,
354 } from "react"
355
356 // ...
357
358 type RegionProviderProps = {
359 children: React.ReactNode
360 }
361
362 export const RegionProvider = (
363 { children }: RegionProviderProps
364 ) => {
365 const [regions, setRegions] = useState<
366 HttpTypes.StoreRegion[]
367 >([])
368 const [region, setRegion] = useState<
369 HttpTypes.StoreRegion
370 >()
371
372 // TODO fetch regions
373 }
374 ```
375
376 You create a `RegionProvider` component that so far only defines two state variables:
377
378 - `regions`: A state variable that will hold the list of regions available in the Medusa application.
379 - `region`: A state variable that will hold the selected region.
380
381 Next, add the following imports to the top of the file:
382
383 ```tsx title="providers/region.tsx"
384 import {
385 // other imports...
386 useEffect,
387 } from "react"
388 import { sdk } from "@/lib/sdk"
389 ```
390
391 And replace the `TODO` in the `RegionProvider` component with the following content:
392
393 export const regionProviderHighlights3 = [
394 ["6", "list", "Retrieve the list of regions from the Medusa application."]
395 ]
396
397 ```tsx title="providers/region.tsx" highlights={regionProviderHighlights3}
398 useEffect(() => {
399 if (regions.length) {
400 return
401 }
402
403 sdk.store.region.list()
404 .then(({ regions }) => {
405 setRegions(regions)
406 })
407 }, [])
408
409 // TODO set the selected region
410 ```
411
412 When the component mounts, you fetch the regions from the Medusa application using the JS SDK. You then set the regions in the `regions` state variable.
413
414 Next, replace the new `TODO` with the following content:
415
416 export const regionProviderHighlights4 = [
417 ["2", "region", "If the region is set, set it in the local storage."],
418 ["9", "regionId", "Retrieve the selected region ID from the local storage."],
419 ["12", "setRegion", "Set the first region in the list as the selected region if no region is set."],
420 ["16", "retrieve", "Retrieve the details of the selected region from the Medusa application."],
421 ]
422
423 ```tsx title="providers/region.tsx" highlights={regionProviderHighlights4}
424 useEffect(() => {
425 if (region) {
426 // set its ID in the local storage in
427 // case it changed
428 localStorage.setItem("region_id", region.id)
429 return
430 }
431
432 const regionId = localStorage.getItem("region_id")
433 if (!regionId) {
434 if (regions.length) {
435 setRegion(regions[0])
436 }
437 } else {
438 // retrieve selected region
439 sdk.store.region.retrieve(regionId)
440 .then(({ region: dataRegion }) => {
441 setRegion(dataRegion)
442 })
443 }
444 }, [region, regions])
445
446 // TODO return the provider
447 ```
448
449 You add another `useEffect` hook that sets the selected region when the component first mounts and whenever the region changes. If the region is set, you only set its value in the local storage.
450
451 If the region isn't set in the state variable, you try to retrieve the previously selected value from the local storage. If it's not found, you set the first region in the `regions` list as the selected region. Otherwise, you retrieve the previously selected region from the Medusa application using the JS SDK.
452
453 Finally, replace the last `TODO` with the following content:
454
455 ```tsx title="providers/region.tsx"
456 return (
457 <RegionContext.Provider value={{
458 region,
459 regions,
460 setRegion,
461 }}>
462 {children}
463 </RegionContext.Provider>
464 )
465 ```
466
467 This returns the `RegionContext.Provider` component that will wraps the storefront with the region context, allowing its children to access the region data.
468
469 To simplify the usage of the region context in child components, add to the file the following custom hook that returns the region context:
470
471 ```tsx title="providers/region.tsx"
472 // other imports...
473 import {
474 // other imports...
475 useContext,
476 } from "react"
477
478 // ...
479
480 export const useRegion = () => {
481 const context = useContext(RegionContext)
482
483 if (!context) {
484 throw new Error("useRegion must be used within a RegionProvider")
485 }
486
487 return context
488 }
489 ```
490
491 You export a `useRegion` hook that returns the region context. You'll use this hook later in child components to access the region.
492
493 ### Create Cart Provider
494
495 Next, you'll create the cart provider that allows you to access the customer's cart across components. Create the file `providers/cart.tsx` with the following content:
496
497 ![Directory structure after creating cart provider file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735816212/Medusa%20Resources/express-checkout-3_ajve6d.jpg)
498
499 export const cartProviderHighlights1 = [
500 ["9", "cart", "The customer's cart."],
501 ["10", "addToCart", "A function to add a product variant to the cart."],
502 ["13", "updateCart", "A function to update the cart with new details, including shipping details."],
503 ["17", "refreshCart", "A function to create a new cart and set it in the context."],
504 ["18", "updateItemQuantity", "A function to update the quantity of an item in the cart."],
505 ["21", "unsetCart", "A function to unset the cart from local storage and state variable."],
506 ]
507
508 ```tsx title="providers/cart.tsx" highlights={cartProviderHighlights1}
509 "use client"
510
511 import {
512 createContext,
513 } from "react"
514 import { HttpTypes } from "@medusajs/types"
515
516 type CartContextType = {
517 cart?: HttpTypes.StoreCart
518 addToCart: (variantId: string, quantity: number) => Promise<
519 HttpTypes.StoreCart
520 >
521 updateCart: (data: {
522 updateData?: HttpTypes.StoreUpdateCart,
523 shippingMethodData?: HttpTypes.StoreAddCartShippingMethods
524 }) => Promise<HttpTypes.StoreCart | undefined>
525 refreshCart: () => Promise<HttpTypes.StoreCart | undefined>
526 updateItemQuantity: (itemId: string, quantity: number) => Promise<
527 HttpTypes.StoreCart
528 >
529 unsetCart: () => void
530 }
531
532 const CartContext = createContext<CartContextType | null>(null)
533
534 // TODO add provider component
535 ```
536
537 You've created `CartContextType` that represents the data that the provider's children can access. It holds:
538
539 - `cart`: The customer's cart. This will be set when the customer adds the product variant to the cart, and unset when the cart is completed.
540 - `addToCart`: A function to add a product variant to the cart.
541 - `updateCart`: A function to update the cart with new details, including shipping details.
542 - `refreshCart`: A function to create a new cart and set it in the context.
543 - `updateItemQuantity`: A function to update the quantity of an item in the cart.
544 - `unsetCart`: A function to unset the cart from local storage and state variable.
545
546 Next, you'll create the provider component that wraps the storefront with the cart context. Add the following content to the file:
547
548 export const cartProviderHighlights2 = [
549 ["15", "cart", "A state variable that will hold the customer's cart details."],
550 ["18", "region", "The selected region retrieved from the region context."],
551 ]
552
553 ```tsx title="providers/cart.tsx" highlights={cartProviderHighlights2}
554 // other imports...
555 import {
556 // other imports...
557 useState,
558 } from "react"
559 import { useRegion } from "./region"
560
561 // ...
562
563 type CartProviderProps = {
564 children: React.ReactNode
565 }
566
567 export const CartProvider = ({ children }: CartProviderProps) => {
568 const [cart, setCart] = useState<
569 HttpTypes.StoreCart
570 >()
571 const { region } = useRegion()
572
573 // TODO set cart
574 }
575 ```
576
577 You create a `CartProvider` component that defines two state variables:
578
579 - `cart` state variable that will hold the customer's cart details.
580 - `region` holding the selected region retrieved from the region context.
581
582 Next, you'll add the logic to set the customer's cart in the provider. Add the following imports to the top of the file:
583
584 ```tsx title="providers/cart.tsx"
585 import {
586 // other imports...
587 useEffect,
588 } from "react"
589 import { sdk } from "@/lib/sdk"
590 ```
591
592 And replace the `TODO` in the `CartProvider` component with the following content:
593
594 export const cartProviderHighlights3 = [
595 ["5", "cart", "If the cart is set, set its value in the local storage."],
596 ["10", "cartId", "Retrieve the cart ID from the local storage."],
597 ["13", "refreshCart", "Create a new cart if the cart is not set."],
598 ["16", "retrieve", "Retrieve the cart from the Medusa application if the cart ID is found in the local storage."],
599 ]
600
601 ```tsx title="providers/cart.tsx" highlights={cartProviderHighlights3}
602 useEffect(() => {
603 if (!region) {
604 return
605 }
606 if (cart) {
607 localStorage.setItem("cart_id", cart.id)
608 return
609 }
610
611 const cartId = localStorage.getItem("cart_id")
612 if (!cartId) {
613 // create a cart
614 refreshCart()
615 } else {
616 // retrieve cart
617 sdk.store.cart.retrieve(cartId, {
618 fields:
619 "+items.variant.*,+items.variant.options.*,+items.product.options.*",
620 })
621 .then(({ cart: dataCart }) => {
622 setCart(dataCart)
623 })
624 }
625 }, [cart, region])
626
627 // TODO update cart when region changes
628 ```
629
630 You add a `useEffect` hook that runs when the component mounts and whenever the cart is changed. If the cart is already set, you only set its value in the local storage.
631
632 If the cart isn't set, you either try to retrieve the cart set in local storage, or create a new cart.
633
634 Next, you'll add the logic to update the cart when the region changes. Replace the `TODO` with the following:
635
636 export const cartProviderHighlights4 = [
637 ["6", "update", "Update the cart's region in the Medusa application if it's changed."]
638 ]
639
640 ```tsx title="providers/cart.tsx" highlights={cartProviderHighlights4}
641 useEffect(() => {
642 if (!cart || !region || cart.region_id === region.id) {
643 return
644 }
645
646 sdk.store.cart.update(cart.id, {
647 region_id: region.id,
648 })
649 .then(({ cart: dataCart }) => {
650 setCart(dataCart)
651 })
652 }, [region])
653
654 // TODO add functions
655 ```
656
657 This `useEffect` hook runs when the region changes. If the cart is set and the region of the cart doesn't match the selected region, you update the cart with the new selected region.
658
659 You'll now implement the functions that are part of the context's value. Start by adding the `refreshCart` function in the place of the `TODO`:
660
661 export const cartProviderHighlights5 = [
662 ["6", "create", "Create the cart in the Medusa application."],
663 ["10", "setItem", "Set the cart's ID in the local storage."],
664 ["11", "setCart", "Set the cart as a state variable."]
665 ]
666
667 ```tsx title="providers/cart.tsx" highlights={cartProviderHighlights5}
668 const refreshCart = async () => {
669 if (!region) {
670 return
671 }
672
673 const { cart: dataCart } = await sdk.store.cart.create({
674 region_id: region.id,
675 })
676
677 localStorage.setItem("cart_id", dataCart.id)
678 setCart(dataCart)
679
680 return dataCart
681 }
682
683 // TODO add addToCart function
684 ```
685
686 In the `refreshCart` function, you create a new cart in the selected region using the JS SDK and set it in the context. You also set the cart ID in the local storage, and return the cart.
687
688 Next, add the `addToCart` function in the place of the `TODO`:
689
690 export const cartProviderHighlights6 = [
691 ["2", "refreshCart", "Create a new cart to add the product to."],
692 ["7", "createLineItem", "Add the product variant to the cart in the Medusa application."],
693 ["11", "setCart", "Update the cart's data in the context."]
694 ]
695
696 ```tsx title="providers/cart.tsx" highlights={cartProviderHighlights6}
697 const addToCart = async (variantId: string, quantity: number) => {
698 const newCart = await refreshCart()
699 if (!newCart) {
700 throw new Error("Could not create cart")
701 }
702
703 const { cart: dataCart } = await sdk.store.cart.createLineItem(newCart.id, {
704 variant_id: variantId,
705 quantity,
706 })
707 setCart(dataCart)
708
709 return dataCart
710 }
711
712 // TODO add updateCart function
713 ```
714
715 In the `addToCart` function, you use the `refreshCart` function to create a new cart, then add a product variant to the cart with the specified quantity using the JS SDK. You set the updated cart in the context and return the cart.
716
717 After that, replace the `TODO` with the `updateCart` function:
718
719 export const cartProviderHighlights7 = [
720 ["13", "update", "Update the cart's general details in the Medusa application."],
721 ["17", "addShippingMethod", "Set the cart's shipping method in the Medusa application."],
722 ["20", "setCart", "Update the cart's data in the context."]
723 ]
724
725 ```tsx title="providers/cart.tsx" highlights={cartProviderHighlights7}
726 const updateCart = async ({
727 updateData,
728 shippingMethodData,
729 }: {
730 updateData?: HttpTypes.StoreUpdateCart,
731 shippingMethodData?: HttpTypes.StoreAddCartShippingMethods
732 }) => {
733 if (!updateData && !shippingMethodData) {
734 return cart
735 }
736 let returnedCart = cart
737 if (updateData) {
738 returnedCart = (await sdk.store.cart.update(cart!.id, updateData)).cart
739 }
740
741 if (shippingMethodData) {
742 returnedCart = (await sdk.store.cart.addShippingMethod(cart!.id, shippingMethodData)).cart
743 }
744
745 setCart(returnedCart)
746
747 return returnedCart
748 }
749
750 // TODO add updateItemQuantity function
751 ```
752
753 In the `updateCart` function, you update the cart's general details and set the cart's shipping method using the JS SDK. You then set the updated cart in the context and return the cart.
754
755 Then, replace the `TODO` with the `updateItemQuantity` function:
756
757 export const cartProviderHighlights8 = [
758 ["2", "updateLineItem", "Update the quantity of an item in the cart in the Medusa application."],
759 ["9", "setCart", "Update the cart's data in the context."]
760 ]
761
762 ```tsx title="providers/cart.tsx" highlights={cartProviderHighlights8}
763 const updateItemQuantity = async (itemId: string, quantity: number) => {
764 const { cart: dataCart } = await sdk.store.cart.updateLineItem(
765 cart!.id,
766 itemId,
767 {
768 quantity,
769 }
770 )
771 setCart(dataCart)
772
773 return dataCart
774 }
775
776 // TODO add unsetCart function
777 ```
778
779 In the `updateItemQuantity` function, you update the quantity of an item in the cart using the JS SDK and set the updated cart in the context.
780
781 Lastly, replace the `TODO` with the `unsetCart` function:
782
783 ```tsx title="providers/cart.tsx"
784 const unsetCart = () => {
785 localStorage.removeItem("cart_id")
786 setCart(undefined)
787 }
788
789 // TODO return provider
790 ```
791
792 In the `unsetCart` function, you remove the cart ID from the local storage and unset the cart in the context.
793
794 Finally, you'll return the provider component. Replace the last `TODO` with the following content:
795
796 ```tsx title="providers/cart.tsx"
797 return (
798 <CartContext.Provider value={{
799 cart,
800 addToCart,
801 updateCart,
802 refreshCart,
803 updateItemQuantity,
804 unsetCart,
805 }}>
806 {children}
807 </CartContext.Provider>
808 )
809 ```
810
811 This returns the `CartContext.Provider` component that wraps the storefront with the cart context, allowing its children to access the cart data.
812
813 To simplify the usage of the cart context in child components, add in the same file the following custom hook that returns the cart context:
814
815 ```tsx title="providers/cart.tsx"
816 // other imports...
817 import {
818 useContext,
819 } from "react"
820
821 // ...
822
823 export const useCart = () => {
824 const context = useContext(CartContext)
825
826 if (!context) {
827 throw new Error("useCart must be used within a CartProvider")
828 }
829
830 return context
831 }
832 ```
833
834 You export a `useCart` hook that returns the cart context. You'll use this hook later in child components to access the cart.
835
836 ---
837
838 ## Step 5: Implement Storefront Layout
839
840 In this step, you'll implement the general layout of the storefront. The storefront will have a simple two-column layout, with one column showing the current page's content, and another showing the current region and allowing the customer to change it.
841
842 ### Create Second Column
843
844 Before creating the layout, you'll create the second column that's consistent across pages.
845
846 To create the component, create the file `components/SecondCol/index.tsx` with the following content:
847
848 ![Directory structure after creating second column file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735904919/Medusa%20Resources/express-checkout-4_ocan8h.jpg)
849
850 export const secondColHighlights = [
851 ["7", "region", "The selected region"],
852 ["7", "regions", "The list of regions in the Medusa application"],
853 ["7", "setRegion", "A function to set the selected region"],
854 ["29", "select", "Dropdown to change the selected region."]
855 ]
856
857 ```tsx title="components/SecondCol/index.tsx" highlights={secondColHighlights}
858 "use client"
859
860 import { clx } from "@medusajs/ui"
861 import { useRegion } from "@/providers/region"
862
863 export const SecondCol = () => {
864 const { region, regions, setRegion } = useRegion()
865
866 return (
867 <div className={clx(
868 "flex flex-col justify-center items-center gap-6",
869 "lg:w-1/2 w-full"
870 )}>
871 <div className="flex flex-col justify-center gap-1">
872 <span className="text-xs text-ui-fg-subtle">
873 Powered by
874 </span>
875 <img
876 src="https://res.cloudinary.com/dza7lstvk/image/upload/v1735642745/Medusa%20Resources/medusa-express-logo_gqu5qy.png"
877 alt="Medusa"
878 width={67}
879 height={16}
880 />
881 </div>
882 <div className="flex justify-center gap-1">
883 <span className="text-sm text-ui-fg-muted">
884 Region:
885 </span>
886 <select
887 value={region?.id}
888 onChange={(e) => {
889 const selectedRegion = regions.find(
890 (r) => r.id === e.target.value
891 )
892 setRegion(selectedRegion)
893 }}
894 className={clx(
895 "text-sm text-ui-fg-subtle",
896 "select"
897 )}
898 >
899 {regions.map((r) => (
900 <option key={r.id} value={r.id}>
901 {r.name}
902 </option>
903 ))}
904 </select>
905 </div>
906 </div>
907 )
908 }
909 ```
910
911 You create a `SecondCol` component that shows the Medusa logo and a dropdown to change the selected region. You use the `useRegion` hook to access the region context and manage region data.
912
913 When the customer changes the selected region in the dropdown, the selected region is changed in the context, which also updates the customer cart's region.
914
915 ### Add Select Styling
916
917 The `SecondCol` component uses custom styling for the `select` component using the `.select` class.
918
919 To add that styling, replace the content of `app/globals.css` with the following content:
920
921 ```css title="app/globals.css"
922 @tailwind base;
923 @tailwind components;
924 @tailwind utilities;
925
926 .select {
927 @apply appearance-none border-none bg-no-repeat pr-4;
928 background-image: url('data:image/svg+xml,<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4.6666 10L7.99994 13.3333L11.3333 10" stroke="%239CA3AF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M4.6666 5.99993L7.99994 2.6666L11.3333 5.99993" stroke="%239CA3AF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>');
929 background-size: 16px;
930 background-position: right top 50%;
931 background-color: transparent;
932 }
933 ```
934
935 ### Create Layout Component
936
937 Next, you'll create the layout component that wraps the storefront pages with the general layout. Replace the content of the file `components/Layout/index.tsx` with the following content:
938
939 export const layoutHighlights = [
940 ["31", "RegionProvider", "Wrap the storefront's pages with the region context."],
941 ["32", "CartProvider", "Wrap the storefront's pages with the cart context."],
942 ["40", "SecondCol", "Show the SecondCol component on the right side of the page."],
943 ]
944
945 ```tsx title="components/Layout/index.tsx" highlights={layoutHighlights}
946 import { clx } from "@medusajs/ui"
947 import { Inter, Roboto_Mono } from "next/font/google"
948 import { RegionProvider } from "@/providers/region"
949 import "./globals.css"
950 import { SecondCol } from "../components/SecondCol"
951 import { CartProvider } from "@/providers/cart"
952
953 export const inter = Inter({
954 subsets: ["latin"],
955 variable: "--font-inter",
956 weight: ["400", "500"],
957 })
958
959 export const robotoMono = Roboto_Mono({
960 subsets: ["latin"],
961 variable: "--font-roboto-mono",
962 })
963
964
965 export default function Layout({
966 children,
967 }: {
968 children: React.ReactNode
969 }) {
970 return (
971 <html className={clx(inter.variable, robotoMono.variable)}>
972 <body className="bg-ui-bg-subtle w-full h-full">
973 <div className={clx(
974 "flex justify-center items-center min-h-screen w-full"
975 )}>
976 <RegionProvider>
977 <CartProvider>
978 <div className={clx(
979 "flex gap-2 lg:my-16 my-4",
980 "lg:w-[758px] lg:mx-auto w-full mx-4"
981 )}>
982 <div className="flex flex-col gap-2 lg:w-1/2 w-full">
983 {children}
984 </div>
985 <SecondCol />
986 </div>
987 </CartProvider>
988 </RegionProvider>
989 </div>
990 </body>
991 </html>
992 )
993 }
994 ```
995
996 You change the layout component to wrap the storefront's components with the `RegionProvider` and `CartProvider` components. You also add two-column styling, always showing the `SecondCol` component on the right side of the page.
997
998 This layout will wrap all pages you create next.
999
1000 ---
1001
1002 ## Step 6: Create Express Checkout Page
1003
1004 The express checkout flow will have four steps:
1005
1006 - Product variant selection: The customer will first open the page to view the product's details, choose its options, then add it to the cart.
1007 - Address details: The customer will input their shipping address, which will also be used as a billing address.
1008 - Shipping method selection: The customer will choose a shipping method used to deliver their order.
1009 - Payment and cart completion: The customer will choose a payment provider to make the payment, then places the order.
1010
1011 These steps will be available within a single page whose path is the product's handle (for example, `sweatpants`), but the routing between them will depend on the cart's current state and a `step` query parameter. In this section, you'll create this page and the router component used to set the current active step.
1012
1013 <Note title="Tip">
1014
1015 Each product in Medusa has a `handle` property, which is a slug-like value that can be used on client applications to create friendly URLs.
1016
1017 </Note>
1018
1019 ### Create Router Component
1020
1021 To manage the routing between the express-checkout-flow steps, you'll create a `Router` component that will render the correct step based on the cart's state and the `step` query parameter. So, create the file `components/Router/index.tsx` with the following content:
1022
1023 ![Directory structure after creating Router component file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735819072/Medusa%20Resources/express-checkout-5_bhpx0w.jpg)
1024
1025 export const routerHighlights = [
1026 ["14", "handle", "Receive the product's handle as a prop"],
1027 ["16", "cart", "Access the customer's cart from the cart context."],
1028 ["19", "currentStep", "Retrieve the current step from the `step` query parameter."],
1029 ["21", "isCartValid", "Check whether the cart is set and has the specified product in the cart."],
1030 ["25", "activeTab", "Set the active tab based on the current step set in the query parameter, or `product` by default."],
1031 ["33", "", "If the step is anything other than `product` and the cart isn't valid, redirect to the product step."],
1032 ["37", "", "If the step is `shipping` and the cart doesn't have shipping and billing addresses, redirect to the address step."],
1033 ["41", "", "If the step is `payment` and the cart doesn't have the necessary conditions, redirect to the shipping step."],
1034 ]
1035
1036 ```tsx title="components/Router/index.tsx" highlights={routerHighlights}
1037 "use client"
1038
1039 import { useRouter, useSearchParams } from "next/navigation"
1040 import { useCart } from "@/providers/cart"
1041 import { useEffect, useMemo } from "react"
1042
1043 type ActiveTab = "product" | "address" | "shipping" | "payment"
1044
1045 type RouterProps = {
1046 handle: string
1047 }
1048
1049 export const Router = ({
1050 handle,
1051 }: RouterProps) => {
1052 const { cart } = useCart()
1053 const searchParams = useSearchParams()
1054 const router = useRouter()
1055 const currentStep = searchParams.get("step")
1056
1057 const isCartValid = useMemo(() => {
1058 return cart?.items?.[0]?.product_handle === handle
1059 }, [cart, handle])
1060
1061 const activeTab: ActiveTab = currentStep === "product" || currentStep === "address" ||
1062 currentStep === "shipping" || currentStep === "payment" ? currentStep : "product"
1063
1064 useEffect(() => {
1065 if (!cart) {
1066 return
1067 }
1068
1069 if ((activeTab !== "product") && !isCartValid) {
1070 return router.push(`/${handle}`)
1071 }
1072
1073 if (activeTab === "shipping" && (!cart?.shipping_address || !cart?.billing_address)) {
1074 return router.push(`/${handle}?step=address`)
1075 }
1076
1077 if (activeTab === "payment" && (
1078 !cart?.shipping_address || !cart?.billing_address || !cart?.shipping_methods?.length
1079 )) {
1080 return router.push(`/${handle}?step=shipping`)
1081 }
1082 }, [isCartValid, activeTab])
1083
1084 return (
1085 <>
1086 {/* TODO render components */}
1087 </>
1088 )
1089 }
1090 ```
1091
1092 You create a `Router` component that manages the routing between the product, address, shipping, and payment steps. The component uses the `useCart` hook to access the cart data, the `useSearchParams` hook to access the query parameters, and the `useRouter` hook to navigate between steps.
1093
1094 The different steps will be shown in the page as tabs or cards. The active tab is set to one of the following values:
1095
1096 - `product`: The product selection step, which is the default step.
1097 - `address`: The shipping address details step. This step is set as active if the `step` query parameter is set to `address` and the cart has the selected product. This step is also set as active if the `step` query parameter is set to `shipping` or `payment` and the cart doesn't have shipping and billing addresses set.
1098 - `shipping`: The shipping method selection step. This step is set as active if the `step` query parameter is set to `shipping` and the cart has the selected product and the shipping and billing addresses set. This step is also set as active if the `step` query parameter is set to `payment` and the cart doesn't have a selected shipping method.
1099 - `payment`: The payment and cart completion step. This step is set as active if the `step` query parameter is set to `payment` and all previous steps have been completed.
1100
1101 You'll render the components for each step as you create them next.
1102
1103 ### Create Express Checkout Page
1104
1105 To create the page that shows the express checkout page, create the file `app/[handle]/page.tsx` with the following content:
1106
1107 ![Directory structure after creating express checkout page file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735820075/Medusa%20Resources/express-checkout-6_w6qf7d.jpg)
1108
1109 ```tsx title="app/[handle]/page.tsx"
1110 import { Router } from "../../components/Router"
1111 import { Suspense } from "react"
1112
1113 type Params = {
1114 params: Promise<{ handle: string }>
1115 }
1116
1117 export default async function ExpressCheckoutPage({
1118 params,
1119 }: Params) {
1120 const handle = (await params).handle
1121
1122 return (
1123 <Suspense fallback={<></>}>
1124 <Router handle={handle} />
1125 </Suspense>
1126 )
1127 }
1128 ```
1129
1130 <Note>
1131
1132 In Next.js 15, any component that uses `useSearchParams()` must be wrapped in a `<Suspense>` boundary to enable static prerendering. Without the `<Suspense>` boundary, the build fails with: `useSearchParams() should be wrapped in a suspense boundary`.
1133
1134 </Note>
1135
1136 This page will render the `Router` component, which will manage the routing between the product, address, shipping, and payment steps. You'll add the components for these steps next.
1137
1138 ---
1139
1140 ## Step 7: Create Product Selection Step
1141
1142 The first step in the express checkout flow is the product selection step. In this step, the customer will view the product's details, choose its options, then add it to the cart.
1143
1144 ### Create Card Component
1145
1146 Before creating the component that displays the product selection step, you'll create a `Card` component that will wrap each step's components in the same styling.
1147
1148 Create the file `components/Card/index.tsx` with the following content:
1149
1150 ![Directory structure after creating Card component file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735820328/Medusa%20Resources/express-checkout-7_a8ys4g.jpg)
1151
1152 export const cardHighlights = [
1153 ["8", "title", "The title of the card."],
1154 ["9", "isActive", "Whether the card is active."],
1155 ["10", "isDone", "Whether the card is completed."],
1156 ["11", "path", "The path to navigate to when the card is clicked."],
1157 ["12", "children", "The content of the card."],
1158 ["30", "onClick", "Navigate to the card's path when the card is clicked."],
1159 ]
1160
1161 ```tsx title="components/Card/index.tsx" highlights={cardHighlights}
1162 "use client"
1163
1164 import { CheckCircle } from "@medusajs/icons"
1165 import { clx, Heading } from "@medusajs/ui"
1166 import { useRouter } from "next/navigation"
1167
1168 type CardProps = {
1169 title: string
1170 isActive: boolean
1171 isDone: boolean
1172 path: string
1173 children: React.ReactNode
1174 }
1175
1176 export const Card = ({
1177 title,
1178 isActive,
1179 isDone,
1180 path,
1181 children,
1182 }: CardProps) => {
1183 const router = useRouter()
1184
1185 return (
1186 <div className={clx(
1187 "bg-ui-bg-base rounded-lg py-4 px-6 w-full",
1188 "flex gap-4 flex-col shadow-elevation-card-rest",
1189 !isActive && "cursor-pointer"
1190 )}
1191 onClick={() => {
1192 if (isActive) {
1193 return
1194 }
1195
1196 router.push(path)
1197 }}
1198 >
1199 <Heading level="h2" className="flex justify-between items-center">
1200 <span>{title}</span>
1201 {isDone && <CheckCircle className="text-ui-tag-green-icon" />}
1202 </Heading>
1203 {isActive && children}
1204 </div>
1205 )
1206 }
1207 ```
1208
1209 You create a `Card` component that accepts the following props:
1210
1211 - `title`: The title of the card.
1212 - `isActive`: A boolean indicating whether the card is active, which is enabled based on the current step of the express checkout flow.
1213 - `isDone`: A boolean indicating whether the card is completed, which is enabled when the customer completes the step's requirements, such as select a shipping method.
1214 - `path`: The step's path.
1215 - `children`: The content of the card.
1216
1217 The card shows the step's title and a check mark if it was completed. The card's content is only shown if the step is currently active.
1218
1219 Also, when the step is completed, its card can be clicked to allow the customer to go back and make changes to their choices or input.
1220
1221 You'll wrap each step component you'll create next with this `Card` component.
1222
1223 ### Create Product Component
1224
1225 You'll now create the component that shows the product selection step.
1226
1227 Create the file `components/Product/index.tsx` with the following content:
1228
1229 ![Directory structure after creating Product component file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735821135/Medusa%20Resources/express-checkout-8_vloodv.jpg)
1230
1231 export const productHighlights1 = [
1232 ["17", "loading", "Whether an operation is loading."],
1233 ["18", "product", "The product's details retrieved from the Medusa application."],
1234 ["19", "selectedOptions", "The product options that the customer selected."],
1235 ["22", "quantity", "The quantity to add to the cart."],
1236 ["23", "region", "The selected region retrieved from the region context."],
1237 ["24", "cart", "The customer's cart retrieved from the cart context."],
1238 ["24", "addToCart", "The function to add the selected product variant to the cart."],
1239 ["25", "router", "The router instance to navigate between steps."]
1240 ]
1241
1242 ```tsx title="components/Product/index.tsx" highlights={productHighlights1}
1243 "use client"
1244
1245 import {
1246 useState,
1247 } from "react"
1248 import { HttpTypes } from "@medusajs/types"
1249 import { useRegion } from "@/providers/region"
1250 import { useCart } from "@/providers/cart"
1251 import { useRouter } from "next/navigation"
1252
1253 type ProductProps = {
1254 handle: string
1255 isActive: boolean
1256 }
1257
1258 export const Product = ({ handle, isActive }: ProductProps) => {
1259 const [loading, setLoading] = useState(true)
1260 const [product, setProduct] = useState<HttpTypes.StoreProduct>()
1261 const [selectedOptions, setSelectedOptions] = useState<
1262 Record<string, string>
1263 >({})
1264 const [quantity, setQuantity] = useState(1)
1265 const { region } = useRegion()
1266 const { cart, addToCart } = useCart()
1267 const router = useRouter()
1268
1269 // TODO get product details
1270 }
1271 ```
1272
1273 You create a `Product` component that receives as a prop the product's handle and whether the component is active.
1274
1275 The component defines the following variables:
1276
1277 - `loading`: A boolean state variable indicating whether an operation is loading, such as the product's details.
1278 - `product`: A state variable that holds the product's details, which you'll retrieve from the Medusa application.
1279 - `selectedOptions`: A state variable that holds the product options that the customer has selected, such as color or size.
1280 - `quantity`: A state variable that holds the product quantity to add to the cart.
1281 - `region`: The selected region retrieved from the region context.
1282 - `cart` and `addToCart`: The customer's cart and the function to add the selected product variant to the cart, retrieved from the cart context.
1283 - `router`: The router instance to navigate between steps.
1284
1285 #### Retrieve Product Details
1286
1287 Next, you'll retrieve the product's details from the Medusa application. Start by adding the following imports to the top of the file:
1288
1289 ```tsx title="components/Product/index.tsx"
1290 import { sdk } from "@/lib/sdk"
1291 import {
1292 // other imports...
1293 useEffect,
1294 } from "react"
1295 ```
1296
1297 Then, replace the `TODO` in the `Product` component with the following:
1298
1299 export const productHighlights2 = [
1300 ["6", "list", "Retrieve the product from the Medusa application by filtering products with the unique handle."],
1301 ["9", "fields", "The fields to retrieve along with the default product details."],
1302 ]
1303
1304 ```tsx title="components/Product/index.tsx" highlights={productHighlights2}
1305 useEffect(() => {
1306 if (product || !region) {
1307 return
1308 }
1309
1310 sdk.store.product.list({
1311 handle,
1312 region_id: region.id,
1313 fields: `*variants.calculated_price,+variants.inventory_quantity`,
1314 })
1315 .then(({ products }) => {
1316 if (products.length) {
1317 setProduct(products[0])
1318 }
1319 setLoading(false)
1320 })
1321 }, [product, region])
1322
1323 // TODO set selected variant
1324 ```
1325
1326 In the `useEffect` hook, you use the JS SDK to send a request to the [List Products](!api!/store/products/list-products) API route, passing the following query parameters:
1327
1328 - `handle`: Filter the list of products with the unique handler.
1329 - `region_id`: Set the selected region, which is necessary to retrieve the correct pricing.
1330 - `fields`: Specify comma-separated fields to retrieve along with the default fields. You pass `*variants.calculated_price` to retrieve the product variants' [price for the current context](../../products/price/page.mdx), and `+variants.inventory_quantity` to retrieve the variants' [inventory quantity](../../products/inventory/page.mdx).
1331
1332 <Note title="Tip">
1333
1334 Most of Medusa's API routes accept the `fields` query parameter, allowing you to specify the fields you need to retrieve. Learn more about its usage in [this documentation](!api!/store/select-fields-and-relations)
1335
1336 </Note>
1337
1338 The API route returns a list of products, but since you passed the unique handle as a filter, the array will have only one item if the product exists. You set the retrieved product in the `product` state variable, and set `loading` to `false`.
1339
1340 #### Set Selected Variant
1341
1342 A product has variants for each of its option combinations (such as color and size). When a customer selects the values for each of the product's options, you'll find the associated variant to show its price and add it to the cart.
1343
1344 To determine the selected variant, first, add the following import at the top of the file:
1345
1346 ```tsx title="components/Product/index.tsx"
1347 import {
1348 // other imports...
1349 useMemo,
1350 } from "react"
1351 ```
1352
1353 Then, replace the `TODO` in `Product` component with the following:
1354
1355 export const productHighlights3 = [
1356 ["1", "selectedVariant", "Define the variant that's currently selected."],
1357 ["10", "find", "Find and return the variant that matches all selected options."]
1358 ]
1359
1360 ```tsx title="components/Product/index.tsx" highlights={productHighlights3}
1361 const selectedVariant = useMemo(() => {
1362 if (
1363 !product?.variants ||
1364 !product.options ||
1365 Object.keys(selectedOptions).length !== product.options?.length
1366 ) {
1367 return
1368 }
1369
1370 return product.variants.find((variant) => variant.options?.every(
1371 (optionValue) => optionValue.id === selectedOptions[optionValue.option_id!]
1372 ))
1373 }, [selectedOptions, product])
1374
1375 // TODO set variant to retrieve its price
1376 ```
1377
1378 You create a `selectedVariant` memoized variable that holds the selected variant based on the selected options. You find the selected variant by filtering the product's variants to find the one that matches all the selected options.
1379
1380 #### Set Price to Show
1381
1382 Next, you'll set the price to show to the customer. The Medusa application returns the price as a number. To display it with currency, you'll create a utility that you'll re-use whenever you show a price.
1383
1384 Create the file `lib/price.ts` with the following content:
1385
1386 ![Directory structure after creating price utility file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735825687/Medusa%20Resources/express-checkout-9_nvhjqo.jpg)
1387
1388 ```ts title="lib/price.ts"
1389 export const formatPrice = (amount: number, currency?: string): string => {
1390 return new Intl.NumberFormat("en-US", {
1391 style: "currency",
1392 currency: currency || "usd",
1393 })
1394 .format(amount)
1395 }
1396 ```
1397
1398 The `formatPrice` utility function uses the [Intl.NumberFormat API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) to format a number with a currency code.
1399
1400 Go back to `components/Product/index.tsx` and import the utility at the top of the file:
1401
1402 ```tsx title="components/Product/index.tsx"
1403 import { formatPrice } from "../../lib/price"
1404 ```
1405
1406 Then, replace the `TODO` in the `Product` component with the following:
1407
1408 export const productHighlights4 = [
1409 ["1", "price", "The formatted price to show to the customer."],
1410 ["2", "selectedVariantPrice", "Determine the variant to show its price, which is either the selected variant or the variant with the smallest price."],
1411 ["19", "formatPrice", "Return the formatted price using the utility you created."]
1412 ]
1413
1414 ```tsx title="components/Product/index.tsx" highlights={productHighlights4}
1415 const price = useMemo(() => {
1416 const selectedVariantPrice = selectedVariant ||
1417 product?.variants?.sort((a: HttpTypes.StoreProductVariant, b: HttpTypes.StoreProductVariant) => {
1418 if (!a.calculated_price?.calculated_amount && !b.calculated_price?.calculated_amount) {
1419 return 0
1420 }
1421 if (!a.calculated_price?.calculated_amount) {
1422 return 1
1423 }
1424 if (!b.calculated_price?.calculated_amount) {
1425 return -1
1426 }
1427 return (
1428 a.calculated_price?.calculated_amount -
1429 b.calculated_price?.calculated_amount
1430 )
1431 })[0]
1432
1433 return formatPrice(
1434 selectedVariantPrice?.calculated_price?.calculated_amount || 0,
1435 region?.currency_code
1436 )
1437 }, [selectedVariant, product, region])
1438
1439 // TODO determine whether the product is in stock
1440 ```
1441
1442 In the `price` memoized variable, you first determine the variant to show its price:
1443
1444 - If a variant is selected, you show its price.
1445 - Otherwise, you show the price of the variant having the lowest price.
1446
1447 Then, you return the price formatted with the `formatPrice` utility function, passing the variant's price and the selected region's currency code as arguments.
1448
1449 #### Determine Whether Selected Variant is in Stock
1450
1451 In Medusa, each product variant has different inventory quantity. So, after the customer selects a variant, you'll check whether it's in stock before allowing them to add it to the cart.
1452
1453 To determine whether the variant is in stock, replace the `TODO` in the `Product` component with the following:
1454
1455 ```tsx title="components/Product/index.tsx"
1456 const isInStock = useMemo(() => {
1457 if (!selectedVariant) {
1458 return undefined
1459 }
1460
1461 return selectedVariant.manage_inventory === false ||
1462 (selectedVariant.inventory_quantity || 0) > 0
1463 }, [selectedVariant])
1464
1465 // TODO implement add to cart logic
1466 ```
1467
1468 You create an `isInStock` memoized variable that holds a boolean indicating whether the selected variant is in stock. A variant is considered in stock if:
1469
1470 - The variant's `manage_inventory` property is set to `false`, meaning Medusa doesn't manage the variant's inventory quantity, so, it's always considered in stock;
1471 - Or the variant's `inventory_quantity` property is greater than 0.
1472
1473 #### Implement Add to Cart Logic
1474
1475 After the customer selects the variant and quantity, they can add it to the cart. To implement the logic of adding the product to the cart, replace the `TODO` in the `Product` component with the following:
1476
1477 export const productHighlights5 = [
1478 ["2", "", "Disallow adding to the cart if no variant is selected, if variant isn't in stock, or if no quantity is set."],
1479 ["7", "addToCart", "Add the selected variant to the cart using the function from the cart context."],
1480 ["9", "push", "Navigate to the address step."]
1481 ]
1482
1483 ```tsx title="components/Product/index.tsx" highlights={productHighlights5}
1484 const handleAddToCart = () => {
1485 if (!selectedVariant || !isInStock || !quantity) {
1486 return
1487 }
1488 setLoading(true)
1489
1490 addToCart(selectedVariant.id!, quantity)
1491 .then(() => {
1492 router.push(`/${handle}?step=address`)
1493 })
1494 }
1495
1496 // TODO render product details
1497 ```
1498
1499 You add a `handleAddToCart` function that first checks that a variant is selected, that it's in stock, and that the customer has set a quantity greater than `0`.
1500
1501 If the conditions are satisfied, you set `loading` to `true`, then call the `addToCart` function from the cart context, passing the selected variant's ID and the quantity as arguments.
1502
1503 After the product is added to the cart, you navigate to the address step, which you'll create later.
1504
1505 #### Render Product Details
1506
1507 Finally, you'll add the return statement showing the product's details and allowing the customer to add the product to the cart.
1508
1509 First, add the following imports at the top of the file:
1510
1511 ```tsx title="components/Product/index.tsx"
1512 import { Card } from "../Card"
1513 import { Spinner } from "@medusajs/icons"
1514 import { Button, Input, Select } from "@medusajs/ui"
1515 ```
1516
1517 Then, replace the last `TODO` in the `Product` component with the following:
1518
1519 export const productHighlights6 = [
1520 ["8", "", "Show a spinner when loading."],
1521 ["9", "", "Show a message when the product isn't found."],
1522 ["10", "", "Show the product's details when it's found."],
1523 ["36", "map", "Loop over the product's options and show a select input for each."],
1524 ["70", "Input", "Allow the customer to set the quantity to add to the cart."],
1525 ["81", "Button", "Show a button to add the product to the cart."],
1526 ]
1527
1528 ```tsx title="components/Product/index.tsx" highlights={productHighlights6}
1529 return (
1530 <Card
1531 title="Product"
1532 isActive={isActive}
1533 isDone={cart?.items !== undefined && cart?.items?.length > 0}
1534 path={`/${handle}`}
1535 >
1536 {loading && <Spinner />}
1537 {!loading && !product && <div>Product not found</div>}
1538 {!loading && product && (
1539 <div className="flex gap-4 flex-col">
1540 <div className="flex gap-4">
1541 <img
1542 src={product.thumbnail || ""}
1543 className="rounded"
1544 width={160}
1545 height={200}
1546 />
1547 <div className="flex flex-col gap-1">
1548 {product.categories?.length && (
1549 <span className="text-xs text-ui-fg-muted">
1550 {product.categories[0].name}
1551 </span>
1552 )}
1553 <span className="text-base text-ui-fg-base">
1554 {product.title}
1555 </span>
1556 <span className="text-sm text-ui-fg-subtle">
1557 {price}
1558 </span>
1559 </div>
1560 </div>
1561 <p className="text-sm text-ui-fg-subtle">
1562 {product.description}
1563 </p>
1564 {product.options?.map((option) => (
1565 <div className="flex flex-col gap-1" key={option.id}>
1566 <span className="text-xs text-ui-fg-muted">
1567 {option.title}
1568 </span>
1569 <Select
1570 onValueChange={(value) => {
1571 setSelectedOptions((prev) => ({
1572 ...prev,
1573 [option.id!]: value,
1574 }))
1575 }}
1576 value={selectedOptions[option.id!]}
1577 >
1578 <Select.Trigger>
1579 <Select.Value placeholder={`Select ${option.title}`} />
1580 </Select.Trigger>
1581 <Select.Content>
1582 {option.values?.map((value) => (
1583 <Select.Item
1584 key={value.id}
1585 value={value.id}
1586 >
1587 {value.value}
1588 </Select.Item>
1589 ))}
1590 </Select.Content>
1591 </Select>
1592 </div>
1593 ))}
1594 <div className="flex flex-col gap-1">
1595 <span className="text-xs text-ui-fg-muted">
1596 Quantity
1597 </span>
1598 <Input
1599 name="quantity"
1600 placeholder="Quantity"
1601 type="number"
1602 min="1"
1603 max={selectedVariant?.inventory_quantity || undefined}
1604 value={quantity}
1605 onChange={(e) => setQuantity(parseInt(e.target.value))}
1606 />
1607 </div>
1608 <hr className="bg-ui-bg-subtle" />
1609 <Button
1610 disabled={!selectedVariant || !isInStock || loading}
1611 onClick={handleAddToCart}
1612 className="w-full"
1613 >
1614 {!selectedVariant && "Select Options"}
1615 {selectedVariant && !isInStock && "Out of Stock"}
1616 {selectedVariant && isInStock && "Add to Cart"}
1617 </Button>
1618 </div>
1619 )}
1620 </Card>
1621 )
1622 ```
1623
1624 You wrap the product step with the `Card` component you created earlier. In the card:
1625
1626 - If `loading` is enabled, you show a spinner icon imported from `@medusajs/icons`.
1627 - If `loading` is disabled and the product isn't found, you show a not found message.
1628 - If `loading` is disabled and the product is found, you show the product's details, including the product's image, title, price, and description.
1629
1630 You also loop over the product's options and show a select input, imported from `@medusajs/ui`, to allow the customer to select the value of each option.
1631
1632 Once the customer has selected a variant that's in stock, they can click the button to add the product to the cart, which will execute the `handleAddToCart` function you created earlier.
1633
1634 ### Add to Router Component
1635
1636 Finally, you'll add the `Product` component to the `Router` component to show the product selection step.
1637
1638 First, import the `Product` component at the top of the `components/Router/index.tsx` file:
1639
1640 ```tsx title="components/Router/index.tsx"
1641 import { Product } from "../Product"
1642 ```
1643
1644 Then, change the `return` statement of the `Router` component to the following
1645
1646 ```tsx title="components/Router/index.tsx"
1647 return (
1648 <>
1649 <Product handle={handle} isActive={activeTab === "product"} />
1650 </>
1651 )
1652 ```
1653
1654 This will show the product step and expand its details if `activeTab` is `product`.
1655
1656 ### Test it Out
1657
1658 To test out what you've implemented so far, first, start the Medusa application by running the following command in the Medusa project's directory:
1659
1660 ```bash npm2yarn
1661 npm run dev
1662 ```
1663
1664 This will run the Medusa application at `http://localhost:9000`.
1665
1666 Then, while the Medusa application is running, run the following command in the Next.js project to start the development server:
1667
1668 ```bash npm2yarn
1669 npm run dev
1670 ```
1671
1672 This will run the storefront at `http://localhost:3000`. To open the express checkout page, go to `http://localhost:3000/sweatpants`, assuming you have a product with the handle `sweatpants`.
1673
1674 <Note title="Tip">
1675
1676 When you first created the Medusa application, four products, including the `sweatpants` product, were created by default. You can view and add products to your application by going to the Medusa Admin dashboard at `http://localhost:9000/app`.
1677
1678 </Note>
1679
1680 ![Product step showing the product's details and add to cart button](https://res.cloudinary.com/dza7lstvk/image/upload/v1735828022/Medusa%20Resources/Screenshot_2025-01-02_at_4.26.40_PM_crvwsg.png)
1681
1682 You should see the product's details, including the image, title, price, description, and options. You can select the options and quantity, then click the "Add to Cart" button to add the product to the cart.
1683
1684 Once you add the product to the cart, the Product card will collapse, and the next step should be shown. You'll add it next.
1685
1686 ---
1687
1688 ## Step 8: Create Address Step
1689
1690 The second step in the express checkout flow is the address details step. In this step, the customer will input their shipping address.
1691
1692 To create the component of this step, create the file `components/Address/index.tsx` with the following content:
1693
1694 ![Directory structure after creating Address component file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735828307/Medusa%20Resources/express-checkout-10_xlfasn.jpg)
1695
1696 export const addressHighlights1 = [
1697 ["19", "cart", "The customer's cart from the cart context."],
1698 ["19", "updateCart", "The function to update the cart from the cart context."],
1699 ["20", "region", "The selected region retrieved from the region context."],
1700 ["21", "loading", "Whether an operation is loading."],
1701 ["22", "firstName", "The customer's first name in the address."],
1702 ["25", "lastName", "The customer's last name in the address."],
1703 ["28", "email", "The customer's email address."],
1704 ["29", "phone", "The customer's phone number."],
1705 ["30", "address", "The customer's address line."],
1706 ["33", "postalCode", "The customer's postal code."],
1707 ["36", "city", "The customer's city."],
1708 ["37", "country", "The customer's country code."],
1709 ["40", "router", "The router instance to navigate between steps."]
1710 ]
1711
1712 ```tsx title="components/Address/index.tsx" highlights={addressHighlights1}
1713 "use client"
1714
1715 import {
1716 useState,
1717 } from "react"
1718 import { useCart } from "@/providers/cart"
1719 import { useRegion } from "@/providers/region"
1720 import { useRouter } from "next/navigation"
1721
1722 type AddressProps = {
1723 handle: string
1724 isActive: boolean
1725 }
1726
1727 export const Address = ({
1728 handle,
1729 isActive,
1730 }: AddressProps) => {
1731 const { cart, updateCart } = useCart()
1732 const { region } = useRegion()
1733 const [loading, setLoading] = useState(false)
1734 const [firstName, setFirstName] = useState(
1735 cart?.shipping_address?.first_name || ""
1736 )
1737 const [lastName, setLastName] = useState(
1738 cart?.shipping_address?.last_name || ""
1739 )
1740 const [email, setEmail] = useState(cart?.email || "")
1741 const [phone, setPhone] = useState(cart?.shipping_address?.phone || "")
1742 const [address, setAddress] = useState(
1743 cart?.shipping_address?.address_1 || ""
1744 )
1745 const [postalCode, setPostalCode] = useState(
1746 cart?.shipping_address?.postal_code || ""
1747 )
1748 const [city, setCity] = useState(cart?.shipping_address?.city || "")
1749 const [country, setCountry] = useState(
1750 cart?.shipping_address?.country_code || region?.countries?.[0]?.iso_2 || ""
1751 )
1752 const router = useRouter()
1753
1754 // TODO set whether button is disabled
1755 }
1756 ```
1757
1758 You create an `Address` component that receives the product's handle and whether the component is active as props. The component defines the following variables:
1759
1760 - `cart` and `updateCart`: The customer's cart and the function to update the cart, retrieved from the cart context.
1761 - `region`: The selected region retrieved from the region context.
1762 - `loading`: A boolean state variable indicating whether an operation is loading.
1763 - `firstName`, `lastName`, `email`, `phone`, `address`, `postalCode`, `city`, and `country`: State variables that hold the customer's shipping and billing address details.
1764 - `router`: The router instance to navigate between steps.
1765
1766 Next, you'll define a variable that determines whether the customer can save the address and go to the next step. First, add the following import at the top of the file:
1767
1768 ```tsx title="components/Address/index.tsx"
1769 import {
1770 // other imports...
1771 useMemo,
1772 } from "react"
1773 ```
1774
1775 Then, replace the `TODO` in the `Address` component with the following:
1776
1777 ```tsx title="components/Address/index.tsx"
1778 const isButtonDisabled = useMemo(() => {
1779 return loading || !firstName || !lastName || !email ||
1780 !phone || !address || !postalCode || !city || !country
1781 }, [
1782 firstName, lastName, email, phone, address,
1783 postalCode, city, country, loading,
1784 ])
1785
1786 // TODO implement submit action logic
1787 ```
1788
1789 You create an `isButtonDisabled` memoized variable whose value is a boolean indicating whether the button to go to the next step is disabled.
1790
1791 ### Implement Submit Action Function
1792
1793 Next, you'll implement the function that will be called when the customer submits their address details.
1794
1795 Replace the `TODO` in the `Address` component with the following:
1796
1797 export const addressHighlights2 = [
1798 ["8", "updateCart", "Update the cart's shipping address, billing address, and email in the Medusa application."],
1799 ["33", "push", "Navigate to the shipping step."]
1800 ]
1801
1802 ```tsx title="components/Address/index.tsx" highlights={addressHighlights2}
1803 const handleSubmit = () => {
1804 if (isButtonDisabled) {
1805 return
1806 }
1807
1808 setLoading(true)
1809
1810 updateCart({
1811 updateData: {
1812 shipping_address: {
1813 first_name: firstName,
1814 last_name: lastName,
1815 phone,
1816 address_1: address,
1817 postal_code: postalCode,
1818 city,
1819 country_code: country,
1820 },
1821 billing_address: {
1822 first_name: firstName,
1823 last_name: lastName,
1824 phone,
1825 address_1: address,
1826 postal_code: postalCode,
1827 city,
1828 country_code: country,
1829 },
1830 email,
1831 },
1832 })
1833 .then(() => {
1834 setLoading(false)
1835 router.push(`/${handle}?step=shipping`)
1836 })
1837 }
1838
1839 // TODO render address form
1840 ```
1841
1842 In the `handleSubmit` function, if the button isn't disabled, you set `loading` to `true`, then use the `updateCart` function from the cart context to update the cart with the customer's shipping and billing addresses and email.
1843
1844 <Note>
1845
1846 You can have different forms for billing and shipping addresses.
1847
1848 </Note>
1849
1850 Once the address is saved, you redirect the customer to the next step in the flow, which is the `shipping` step.
1851
1852 ### Render Address Form
1853
1854 Lastly, you'll add the return statement that shows the address form.
1855
1856 First, add the following imports at the top of the file:
1857
1858 ```tsx title="components/Address/index.tsx"
1859 import { Card } from "../Card"
1860 import { Button, Input, Select } from "@medusajs/ui"
1861 ```
1862
1863 Then, replace the last `TODO` in the `Address` component with the following:
1864
1865 ```tsx title="components/Address/index.tsx"
1866 return (
1867 <Card
1868 title="Delivery Address"
1869 isActive={isActive}
1870 isDone={!!cart?.shipping_address}
1871 path={`/${handle}?step=address`}
1872 >
1873 <div className="flex flex-col gap-8">
1874 <div className="flex flex-col gap-2">
1875 <span className="text-xs">Contact</span>
1876 <div className="flex gap-2">
1877 <Input
1878 name="first_name"
1879 value={firstName}
1880 onChange={(e) => setFirstName(e.target.value)}
1881 placeholder="First name"
1882 />
1883 <Input
1884 name="last_name"
1885 value={lastName}
1886 onChange={(e) => setLastName(e.target.value)}
1887 placeholder="Last name"
1888 />
1889 </div>
1890 <Input
1891 name="email"
1892 value={email}
1893 onChange={(e) => setEmail(e.target.value)}
1894 placeholder="Email"
1895 />
1896 <Input
1897 name="phone"
1898 value={phone}
1899 onChange={(e) => setPhone(e.target.value)}
1900 placeholder="Phone"
1901 />
1902 </div>
1903 <div className="flex flex-col gap-2">
1904 <span className="text-xs">Delivery</span>
1905 <Input
1906 name="address"
1907 value={address}
1908 onChange={(e) => setAddress(e.target.value)}
1909 placeholder="Address"
1910 />
1911 <div className="flex gap-2">
1912 <Input
1913 name="postal_code"
1914 value={postalCode}
1915 onChange={(e) => setPostalCode(e.target.value)}
1916 placeholder="Postal code"
1917 />
1918 <Input
1919 name="city"
1920 value={city}
1921 onChange={(e) => setCity(e.target.value)}
1922 placeholder="City"
1923 />
1924 </div>
1925 <Select
1926 value={country}
1927 onValueChange={(value) => setCountry(value)}
1928 >
1929 <Select.Trigger>
1930 <Select.Value placeholder="Country" />
1931 </Select.Trigger>
1932 <Select.Content>
1933 {region?.countries?.map((country) => (
1934 <Select.Item
1935 key={country.iso_2}
1936 value={country.iso_2 || ""}
1937 >
1938 {country.display_name}
1939 </Select.Item>
1940 ))}
1941 </Select.Content>
1942 </Select>
1943 </div>
1944 <hr className="bg-ui-bg-subtle" />
1945 <Button
1946 disabled={isButtonDisabled}
1947 onClick={handleSubmit}
1948 className="w-full"
1949 >
1950 Continue
1951 </Button>
1952 </div>
1953 </Card>
1954 )
1955 ```
1956
1957 You wrap the address form with the `Card` component you created earlier. In the card, you show inputs for the address details and a button that, when clicked, executes the `handleSubmit` function you created earlier.
1958
1959 ### Add to Router Component
1960
1961 Finally, you'll add the `Address` component to the `Router` component to show the address details step.
1962
1963 First, import the `Address` component at the top of the `components/Router/index.tsx` file:
1964
1965 ```tsx title="components/Router/index.tsx"
1966 import { Address } from "../Address"
1967 ```
1968
1969 Then, change the `return` statement of the `Router` component to the following
1970
1971 ```tsx title="components/Router/index.tsx" highlights={[["4"]]}
1972 return (
1973 <>
1974 <Product handle={handle} isActive={activeTab === "product"} />
1975 <Address handle={handle} isActive={activeTab === "address"} />
1976 </>
1977 )
1978 ```
1979
1980 This will show the address details step and expand its details if `activeTab` is `address`.
1981
1982 ### Test it Out
1983
1984 While both the Medusa application and the Next.js Starter Storefront are running, if you refresh the page you had opened or go to `http://localhost:3000/sweatpants?step=address`, you should see the address form where you can input your address details.
1985
1986 ![Address step showing the address form and a continue button](https://res.cloudinary.com/dza7lstvk/image/upload/v1735831238/Medusa%20Resources/Screenshot_2025-01-02_at_5.20.22_PM_leqt17.png)
1987
1988 You can input your address details then click on the "Continue" button. The address will be saved in the cart and the Address card will collapse. The third step's details should be shown, which you'll add next.
1989
1990 ---
1991
1992 ## Step 9: Create Shipping Step
1993
1994 The third step in the express checkout flow is the shipping method selection step. In this step, the customer will choose a shipping method to deliver their order.
1995
1996 To create the component of this step, create the file `components/Shipping/index.tsx` with the following content:
1997
1998 ![Directory structure after creating Shipping component file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735831410/Medusa%20Resources/express-checkout-11_myblmq.jpg)
1999
2000 export const shippingHighlights1 = [
2001 ["19", "cart", "The customer's cart from the cart context."],
2002 ["19", "updateCart", "The function to update the cart from the cart context."],
2003 ["20", "loading", "Whether an operation is loading."],
2004 ["21", "shippingMethod", "The selected shipping method."],
2005 ["24", "shippingOptions", "The available shipping options."],
2006 ["27", "calculatedPrices", "The calculated prices for each shipping option that doesn't have a flat rate price."],
2007 ["30", "router", "The router instance to navigate between steps."]
2008 ]
2009
2010 ```tsx title="components/Shipping/index.tsx" highlights={shippingHighlights1}
2011 "use client"
2012
2013 import {
2014 useState,
2015 } from "react"
2016 import { useCart } from "@/providers/cart"
2017 import { HttpTypes } from "@medusajs/types"
2018 import { useRouter } from "next/navigation"
2019
2020 type ShippingProps = {
2021 handle: string
2022 isActive: boolean
2023 }
2024
2025 export const Shipping = ({
2026 handle,
2027 isActive,
2028 }: ShippingProps) => {
2029 const { cart, updateCart } = useCart()
2030 const [loading, setLoading] = useState(true)
2031 const [shippingMethod, setShippingMethod] = useState(
2032 cart?.shipping_methods?.[0]?.shipping_option_id || ""
2033 )
2034 const [shippingOptions, setShippingOptions] = useState<
2035 HttpTypes.StoreCartShippingOption[]
2036 >([])
2037 const [calculatedPrices, setCalculatedPrices] = useState<
2038 Record<string, number>
2039 >({})
2040 const router = useRouter()
2041
2042 // TODO retrieve shipping options
2043 }
2044 ```
2045
2046 You create a `Shipping` component that receives the product's handle and whether the component is active as props. The component defines the following variables:
2047
2048 - `cart` and `updateCart`: The customer's cart and the function to update the cart, retrieved from the cart context.
2049 - `loading`: A boolean state variable indicating whether an operation is loading.
2050 - `shippingMethod`: A state variable that holds the selected shipping method.
2051 - `shippingOptions`: A state variable that holds the available shipping options.
2052 - `calculatedPrices`: A state variable that holds the calculated prices for each shipping option that doesn't have a flat rate price.
2053 - `router`: The router instance to navigate between steps.
2054
2055 ### Retrieve Shipping Options
2056
2057 In the Medusa application, you can define shipping options for each [stock location](../../../commerce-modules/stock-location/page.mdx), [sales channel](../../../commerce-modules/sales-channel/page.mdx), or other conditions. So, during checkout, you retrieve the shipping options specific to a cart's context and allow the customer to choose from them.
2058
2059 To do that, first, add the following imports at the top of the file:
2060
2061 ```tsx title="components/Shipping/index.tsx"
2062 import {
2063 // other imports...
2064 useEffect,
2065 } from "react"
2066 import { sdk } from "@/lib/sdk"
2067 ```
2068
2069 Then, replace the `TODO` in the `Shipping` component with the following:
2070
2071 export const shippingHighlights2 = [
2072 ["6", "listCartOptions", "Retrieve the shipping options for the cart from the Medusa application."]
2073 ]
2074
2075 ```tsx title="components/Shipping/index.tsx" highlights={shippingHighlights2}
2076 useEffect(() => {
2077 if (shippingOptions.length || !cart) {
2078 return
2079 }
2080
2081 sdk.store.fulfillment.listCartOptions({
2082 cart_id: cart.id || "",
2083 })
2084 .then(({ shipping_options }) => {
2085 setShippingOptions(shipping_options)
2086 setLoading(false)
2087 })
2088 }, [shippingOptions, cart])
2089
2090 // TODO set calculated prices
2091 ```
2092
2093 In the `useEffect` hook, you use the JS SDK to send a request to the [List Shipping Options of a Cart](!api!/store/shipping-options/list-shipping-options-for-cart) API route, passing the cart's ID as a query parameter. The API route returns a list of shipping options, which you set in the `shippingOptions` state variable.
2094
2095 ### Retrieve Calculated Prices
2096
2097 Shipping options have a `price_type` property whose value is either:
2098
2099 - `flat_rate`: This value means the shipping option has a fixed price.
2100 - `calculated`: This value means the shipping option's price is calculated based on the cart's context, such as the shipping address or items in the carts. This is useful when the [fulfillment provider](../../../commerce-modules/fulfillment/fulfillment-provider/page.mdx) that's associated with a shipping option calculates the price based on these conditions.
2101
2102 So, to retrieve the prices of calculated shipping options, you use Medusa's [Calculate Shipping Option Price](!api!/store/shipping-options/calculate-shipping-option-price) API route.
2103
2104 Replace the `TODO` in the `Shipping` component with the following:
2105
2106 export const shippingHighlights3 = [
2107 ["7", "filter", "Retrieve shipping options with calculated prices only."],
2108 ["9", "fetch", "Retrieve the calculated price from the Medusa application."],
2109 ["24", "Promise.allSettled", "Wait for all calculated prices to be retrieved."],
2110 ["33", "setCalculatedPrices", "Set the calculated prices in the state variable."],
2111 ]
2112
2113 ```tsx title="components/Shipping/index.tsx" highlights={shippingHighlights3}
2114 useEffect(() => {
2115 if (!cart || !shippingOptions.length) {
2116 return
2117 }
2118
2119 const promises = shippingOptions
2120 .filter((shippingOption) => shippingOption.price_type === "calculated")
2121 .map((shippingOption) =>
2122 sdk.client.fetch(
2123 `/store/shipping-options/${shippingOption.id}/calculate`,
2124 {
2125 method: "POST",
2126 body: {
2127 cart_id: cart.id,
2128 data: {
2129 // pass any custom data useful for price calculation
2130 },
2131 },
2132 }
2133 ) as Promise<{ shipping_option: HttpTypes.StoreCartShippingOption }>
2134 )
2135
2136 if (promises.length) {
2137 Promise.allSettled(promises).then((res) => {
2138 const pricesMap: Record<string, number> = {}
2139 res
2140 .filter((r) => r.status === "fulfilled")
2141 .forEach((p) => (
2142 pricesMap[p.value?.shipping_option.id || ""] =
2143 p.value?.shipping_option.amount
2144 ))
2145
2146 setCalculatedPrices(pricesMap)
2147 })
2148 }
2149 }, [shippingOptions, cart])
2150
2151 // TODO add function to format price
2152 ```
2153
2154 In the `useEffect` hook, you filter the `shippingOptions` to get only the calculated shipping options. Then, you loop over these options to retrieve their calculated price from the Medusa application. You pass to the Calculate Shipping Option API route the cart's ID and any custom data that the fulfillment provider might need to calculate the price.
2155
2156 Once all shipping option prices are calculated, you set them in the `calculatedPrices` state variable, where the key is the shipping option's ID and the value is the calculated price.
2157
2158 ### Format Prices Function
2159
2160 When you display the shipping options and their prices, you want to format the prices with the currency code. You'll use the `formatPrice` utility function you created earlier.
2161
2162 First, add the following imports at the top of the file:
2163
2164 ```tsx title="components/Shipping/index.tsx"
2165 import {
2166 // other imports...
2167 useCallback,
2168 } from "react"
2169 import { formatPrice } from "../../lib/price"
2170 ```
2171
2172 Then, replace the `TODO` in the `Shipping` component with the following:
2173
2174 ```tsx title="components/Shipping/index.tsx"
2175 const getShippingOptionPrice = useCallback(
2176 (shippingOption: HttpTypes.StoreCartShippingOption) => {
2177 const price = shippingOption.price_type === "flat" ?
2178 shippingOption.amount : calculatedPrices[shippingOption.id]
2179
2180 return formatPrice(price || 0, cart?.currency_code)
2181 }, [calculatedPrices]
2182 )
2183
2184 // TODO add submit logic
2185 ```
2186
2187 You create a `getShippingOptionPrice` function that receives a shipping option to get its formatted price. You use the `formatPrice` utility function, passing it either the shipping option's flat or calculated price, based on its type. You return the formatted price.
2188
2189 ### Implement Submit Function
2190
2191 Next, you'll implement the function that will be called when the customer submits their shipping method selection.
2192
2193 Replace the `TODO` in the `Shipping` component with the following:
2194
2195 export const shippingHighlights4 = [
2196 ["1", "isButtonDisabled", "Whether the customer can submit their selection."],
2197 ["5", "handleSubmit", "A function to execute when the customer submits their choice."],
2198 ["12", "updateCart", "Update the cart with the selected shipping method in the Medusa application."],
2199 ["15", "data", "Pass any useful custom data for the fulfillment provider."],
2200 ["23", "router", "Redirect the customer to the next step in the flow."]
2201 ]
2202
2203 ```tsx title="components/Shipping/index.tsx" highlights={shippingHighlights4}
2204 const isButtonDisabled = useMemo(() => {
2205 return loading || !shippingMethod
2206 }, [shippingMethod, loading])
2207
2208 const handleSubmit = () => {
2209 if (isButtonDisabled) {
2210 return
2211 }
2212
2213 setLoading(true)
2214
2215 updateCart({
2216 shippingMethodData: {
2217 option_id: shippingMethod,
2218 data: {
2219 // TODO add any data necessary for
2220 // fulfillment provider
2221 },
2222 },
2223 })
2224 .then(() => {
2225 setLoading(false)
2226 router.push(`/${handle}?step=payment`)
2227 })
2228 }
2229
2230 // TODO render shipping step
2231 ```
2232
2233 You define an `isButtonDisabled` memoized variable that indicates whether the customer can submit their selection. You also define a `handleSubmit` function that uses the `updateCart` function from the cart context to update the cart with the selected shipping method.
2234
2235 Once the shipping method is saved, you redirect the customer to the next step in the flow, which is the `payment` step.
2236
2237 ### Render Shipping Step
2238
2239 Finally, you'll add the return statement showing the shipping method selection form that allows the customer to choose a shipping method.
2240
2241 First, add the following imports at the top of the file:
2242
2243 ```tsx title="components/Shipping/index.tsx"
2244 import { Card } from "../Card"
2245 import { Button, RadioGroup } from "@medusajs/ui"
2246 ```
2247
2248 Then, replace the last `TODO` in the `Shipping` component with the following:
2249
2250 export const shippingHighlights5 = [
2251 ["10", "RadioGroup", "Show a radio group with the available shipping options and their prices."],
2252 ["20", "getShippingOptionPrice", "Show the shipping option's price."],
2253 ["28", "Button", "Show a button to save the customer's choice and go to the next step."],
2254 ]
2255
2256 ```tsx title="components/Shipping/index.tsx" highlights={shippingHighlights5}
2257 return (
2258 <Card
2259 title="Shipping"
2260 isActive={isActive}
2261 isDone={!!cart?.shipping_methods?.length}
2262 path={`/${handle}?step=shipping`}
2263 >
2264 <div className="flex flex-col gap-8">
2265 <div className="flex flex-col gap-2">
2266 <RadioGroup
2267 value={shippingMethod}
2268 onValueChange={(value) => setShippingMethod(value)}
2269 >
2270 {shippingOptions.map((shippingOption) => (
2271 <div className="flex gap-1" key={shippingOption.id}>
2272 <RadioGroup.Item value={shippingOption.id} />
2273 <div className="flex justify-between w-full gap-2">
2274 <span className="text-sm">{shippingOption.name}</span>
2275 <span className="text-xs text-ui-fg-muted">{
2276 getShippingOptionPrice(shippingOption)
2277 }</span>
2278 </div>
2279 </div>
2280 ))}
2281 </RadioGroup>
2282 </div>
2283 <hr className="bg-ui-bg-subtle" />
2284 <Button
2285 disabled={isButtonDisabled}
2286 onClick={handleSubmit}
2287 className="w-full"
2288 >
2289 Go to payment
2290 </Button>
2291 </div>
2292 </Card>
2293 )
2294 ```
2295
2296 You wrap the shipping method selection form with the `Card` component you created earlier. In the card, you show a radio group with the available shipping options and their prices.
2297
2298 The customer can select a shipping option and click the "Go to payment" button to go to the next step.
2299
2300 ### Add to Router Component
2301
2302 Finally, you'll add the `Shipping` component to the `Router` component.
2303
2304 First, import the `Shipping` component at the top of the `components/Router/index.tsx` file:
2305
2306 ```tsx title="components/Router/index.tsx"
2307 import { Shipping } from "../Shipping"
2308 ```
2309
2310 Then, change the `return` statement of the `Router` component to the following
2311
2312 ```tsx title="components/Router/index.tsx" highlights={[["5"]]}
2313 return (
2314 <>
2315 <Product handle={handle} isActive={activeTab === "product"} />
2316 <Address handle={handle} isActive={activeTab === "address"} />
2317 <Shipping handle={handle} isActive={activeTab === "shipping"} />
2318 </>
2319 )
2320 ```
2321
2322 This will show the shipping method selection step and expand its details if `activeTab` is `shipping`.
2323
2324 ### Test it Out
2325
2326 While both the Medusa application and the Next.js Starter Storefront are running, if you refresh the page you had opened or go to `http://localhost:3000/sweatpants?step=shipping`, you should see the Shipping step where you can choose a shipping method.
2327
2328 ![Shipping step showing the shipping options and a go to payment button](https://res.cloudinary.com/dza7lstvk/image/upload/v1735832462/Medusa%20Resources/Screenshot_2025-01-02_at_5.40.45_PM_jplcn3.png)
2329
2330 You can select a shipping option then click on the "Go to payment" button. The shipping method will be saved in the cart and the Shipping card will collapse to show the fourth step's details, which you'll add next.
2331
2332 ---
2333
2334 ## Step 10: Create Payment Step
2335
2336 The fourth and last step in the express checkout flow is the payment method selection step. In this step, the customer will choose a payment method and complete their cart, placing an order.
2337
2338 To create the component of this step, create the file `components/Payment/index.tsx` with the following content:
2339
2340 ![Directory structure after creating Payment component file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735832586/Medusa%20Resources/express-checkout-12_j2xldp.jpg)
2341
2342 export const paymentHighlights1 = [
2343 ["19", "cart", "The customer's cart from the cart context."],
2344 ["19", "updateItemQuantity", "The function to update the quantity of an item in the cart from the cart context."],
2345 ["19", "unsetCart", "The function to unset the cart from the cart context."],
2346 ["20", "loading", "Whether an operation is loading."],
2347 ["21", "paymentProviders", "The available payment providers retrieved from the Medusa application."],
2348 ["24", "selectedPaymentProvider", "The ID of the selected payment provider."],
2349 ["25", "router", "The router instance to navigate between steps."]
2350 ]
2351
2352 ```tsx title="components/Payment/index.tsx" highlights={paymentHighlights1}
2353 "use client"
2354
2355 import {
2356 useState,
2357 } from "react"
2358 import { useCart } from "@/providers/cart"
2359 import { HttpTypes } from "@medusajs/types"
2360 import { useRouter } from "next/navigation"
2361
2362 type PaymentProps = {
2363 handle: string
2364 isActive: boolean
2365 }
2366
2367 export const Payment = ({
2368 handle,
2369 isActive,
2370 }: PaymentProps) => {
2371 const { cart, updateItemQuantity, unsetCart } = useCart()
2372 const [loading, setLoading] = useState(true)
2373 const [paymentProviders, setPaymentProviders] = useState<
2374 HttpTypes.StorePaymentProvider[]
2375 >([])
2376 const [selectedPaymentProvider, setSelectedPaymentProvider] = useState("")
2377 const router = useRouter()
2378
2379 // TODO retrieve payment providers
2380 }
2381 ```
2382
2383 You create a `Payment` component that receives the product's handle and whether the component is active as props. The component defines the following variables:
2384
2385 - `cart`, `unsetCart`, and `updateItemQuantity`: The customer's cart, the function to unset the cart, and the function to update the quantity of an item in the cart, retrieved from the cart context.
2386 - `loading`: A boolean state variable indicating whether an operation is loading.
2387 - `paymentProviders`: A state variable that holds the available payment providers in the Medusa application.
2388 - `selectedPaymentProvider`: A state variable that holds the ID of the selected payment provider.
2389 - `router`: The router instance to navigate between steps.
2390
2391 ### Retrieve Payment Providers
2392
2393 In Medusa, each region has a set of enabled payment providers. So, during checkout, you retrieve the payment providers specific to a cart's region and allow the customer to choose from them.
2394
2395 To do that, first, add the following imports at the top of the file:
2396
2397 ```tsx title="components/Payment/index.tsx"
2398 import {
2399 // other imports...
2400 useEffect,
2401 } from "react"
2402 import { sdk } from "@/lib/sdk"
2403 ```
2404
2405 Then, replace the `TODO` in the `Payment` component with the following:
2406
2407 export const paymentHighlights2 = [
2408 ["6", "listPaymentProviders", "Retrieve the payment providers of the cart's region from the Medusa application."]
2409 ]
2410
2411 ```tsx title="components/Payment/index.tsx" highlights={paymentHighlights2}
2412 useEffect(() => {
2413 if (!loading || !cart) {
2414 return
2415 }
2416
2417 sdk.store.payment.listPaymentProviders({
2418 region_id: cart.region_id || "",
2419 })
2420 .then(({ payment_providers }) => {
2421 setPaymentProviders(payment_providers)
2422 setLoading(false)
2423 })
2424 }, [loading, cart])
2425
2426 // TODO handle provider selection
2427 ```
2428
2429 In the `useEffect` hook, you use the JS SDK to send a request to the [List Payment Providers](!api!/store/payment-providers/list-payment-providers) API route, passing the cart's region ID as a query parameter.
2430
2431 The API route returns a list of payment providers, which you set in the `paymentProviders` state variable. These are the payment providers you'll allow the customer to select from.
2432
2433 ### Handle Payment Provider Selection
2434
2435 After the customer selects the payment provider, you want to save that selection in the cart, but you also may need to show UI for additional actions. For example, if the customer chooses the [Stripe payment provider](../../../commerce-modules/payment/payment-provider/stripe/page.mdx), you want to show them a credit-card form to input their details.
2436
2437 So, you'll implement the logic to first save the payment provider selection in the Medusa application, then optionally show additional UI based on the chosen provider.
2438
2439 First, add the following imports at the top of the file:
2440
2441 ```tsx title="components/Payment/index.tsx"
2442 import {
2443 // other imports...
2444 useMemo,
2445 } from "react"
2446 ```
2447
2448 Then, replace the `TODO` in the `Payment` component with the following:
2449
2450 export const paymentHighlights3 = [
2451 ["1", "handleSelectProvider", "A function to save the selected payment provider in the Medusa application."],
2452 ["8", "initiatePaymentSession", "Set the chosen payment method in the Medusa application."],
2453 ["16", "useEffect", "Trigger the `handleSelectProvider` function whenever the selected payment provider changes."],
2454 ["24", "paymentUi", "Optionally show additional UI based on the selected payment provider."],
2455 ["36", "canPlaceOrder", "Whether the customer can place an order."],
2456 ]
2457
2458 ```tsx title="components/Payment/index.tsx" highlights={paymentHighlights3}
2459 const handleSelectProvider = async () => {
2460 if (!selectedPaymentProvider || !cart) {
2461 return
2462 }
2463
2464 setLoading(true)
2465
2466 sdk.store.payment.initiatePaymentSession(cart, {
2467 provider_id: selectedPaymentProvider,
2468 })
2469 .then(() => {
2470 setLoading(false)
2471 })
2472 }
2473
2474 useEffect(() => {
2475 if (!selectedPaymentProvider || !cart) {
2476 return
2477 }
2478
2479 handleSelectProvider()
2480 }, [selectedPaymentProvider])
2481
2482 const paymentUi = useMemo(() => {
2483 if (!selectedPaymentProvider) {
2484 return
2485 }
2486
2487 switch (selectedPaymentProvider) {
2488 // TODO handle other providers
2489 default:
2490 return <></>
2491 }
2492 }, [selectedPaymentProvider])
2493
2494 const canPlaceOrder = useMemo(() => {
2495 switch (selectedPaymentProvider) {
2496 case "":
2497 return false
2498 // TODO handle other providers
2499 default:
2500 return true
2501 }
2502 }, [selectedPaymentProvider])
2503
2504 // TODO handle place order
2505 ```
2506
2507 You define a `handleSelectProvider` function that uses the JS SDK to set the selected payment provider in the cart. You call this function whenever the `selectedPaymentProvider` changes.
2508
2509 Then, you define two memoized variables:
2510
2511 - `paymentUi`: This variable holds additional UI to show based on the selected payment provider. This guide doesn't cover any specific providers, so you're free to implement this based on the payment providers you support. By default, it returns an empty node.
2512 - `canPlaceOrder`: This variable holds a boolean indicating whether the customer can place an order. You can define the logic based on the payment providers you support. By default, it returns `true`.
2513
2514 <Note title="Tip">
2515
2516 Learn how to implement payment in your storefront with Stripe in [this guide](../../checkout/payment/stripe/page.mdx).
2517
2518 </Note>
2519
2520 ### Handle Place Order Function
2521
2522 After the customer chooses a payment provider and completes any additional steps, they can complete their cart and place their order.
2523
2524 Replace the `TODO` in the `Payment` component with the following:
2525
2526 export const paymentHighlights4 = [
2527 ["7", "complete", "Complete the cart and place an order in the Medusa application."],
2528 ["13", "unsetCart", "Unset the cart from the cart context."],
2529 ["15", "router.push", "Redirect the customer to the confirmation page."],
2530 ]
2531
2532 ```tsx title="components/Payment/index.tsx" highlights={paymentHighlights4}
2533 const placeOrder = () => {
2534 if (!cart || !canPlaceOrder) {
2535 return
2536 }
2537 setLoading(true)
2538
2539 sdk.store.cart.complete(cart.id)
2540 .then((data) => {
2541 if (data.type === "cart") {
2542 alert(data.error.message)
2543 setLoading(false)
2544 } else {
2545 unsetCart()
2546 // redirect to confirmation page
2547 router.push(`/confirmation/${data.order.id}`)
2548 }
2549 })
2550 }
2551
2552 // TODO render payment step
2553 ```
2554
2555 You define a `placeOrder` function that uses the JS SDK to complete the cart by sending a request to the [Complete Cart API route](!api!/store/carts/complete-cart). If the cart is successfully completed, you unset the cart and redirect the customer to the confirmation page, which you'll implement later.
2556
2557 ### Render Payment Step
2558
2559 Finally, you'll add the return statement showing the Payment step that allows the customer to choose a payment method.
2560
2561 First, add the following imports at the top of the file:
2562
2563 ```tsx title="components/Payment/index.tsx"
2564 import { Card } from "../Card"
2565 import { Button, Input, RadioGroup } from "@medusajs/ui"
2566 ```
2567
2568 Then, replace the last `TODO` in the `Payment` component with the following:
2569
2570 ```tsx title="components/Payment/index.tsx"
2571 const getProviderTitle = (providerId: string) => {
2572 switch(true) {
2573 case providerId.startsWith("pp_system_default"):
2574 return "Cash on Delivery"
2575 default:
2576 return providerId
2577 }
2578 }
2579
2580 return (
2581 <Card
2582 title="Payment"
2583 isActive={isActive}
2584 isDone={false}
2585 path={`/${handle}?step=payment`}
2586 >
2587 <span className="text-sm">Your order</span>
2588 {cart?.items?.map((item) => (
2589 <div className="flex gap-2" key={item.id}>
2590 <img src={item.thumbnail} alt={item.title} className="w-24 h-24 rounded" />
2591 <div className="flex flex-col gap-3">
2592 <span className="text-base">{item.product_title}</span>
2593 {item.variant?.options?.map((option) => (
2594 <span className="flex gap-1 text-sm" key={option.id}>
2595 <span className="text-ui-fg-muted">
2596 {item.product?.options?.find(
2597 (productOption) => productOption.id === option.option_id
2598 )?.title}
2599 </span>
2600 <span className="text-ui-fg-base">{option.value}</span>
2601 </span>
2602 ))}
2603 <span className="flex gap-1 text-sm items-center">
2604 <span className="text-ui-fg-muted">Quantity</span>
2605 <Input
2606 type="number"
2607 value={item.quantity}
2608 onChange={(e) => {
2609 if (!e.target.value) {
2610 return
2611 }
2612 updateItemQuantity(item.id, parseInt(e.target.value))
2613 }}
2614 />
2615 </span>
2616 </div>
2617 </div>
2618 ))}
2619 <hr className="bg-ui-bg-subtle" />
2620 <div className="flex justify-between">
2621 <span className="text-sm text-ui-fg-muted">Subtotal:</span>
2622 <span className="text-sm text-ui-fg-base">{formatPrice(
2623 cart?.item_subtotal || 0,
2624 cart?.currency_code
2625 )}</span>
2626 </div>
2627 <div className="flex justify-between">
2628 <span className="text-sm text-ui-fg-muted">Shipping & handling:</span>
2629 <span className="text-sm text-ui-fg-base">{formatPrice(
2630 cart?.shipping_total || 0,
2631 cart?.currency_code
2632 )}</span>
2633 </div>
2634 <div className="flex justify-between">
2635 <span className="text-sm text-ui-fg-muted">Total:</span>
2636 <span className="text-sm text-ui-fg-base">{formatPrice(
2637 cart?.total || 0,
2638 cart?.currency_code
2639 )}</span>
2640 </div>
2641 <hr className="bg-ui-bg-subtle" />
2642 <span className="text-sm">Delivery address</span>
2643 <p className="text-xs text-ui-fg-muted">
2644 {cart?.shipping_address?.first_name} {cart?.shipping_address?.last_name}<br />
2645 {cart?.shipping_address?.address_1}<br />
2646 {cart?.shipping_address?.city}, {cart?.shipping_address?.postal_code}, {cart?.shipping_address?.country_code}<br />
2647 </p>
2648 <hr className="bg-ui-bg-subtle" />
2649 <span className="text-sm">Payment method</span>
2650 <div className="flex flex-col gap-2">
2651 <RadioGroup
2652 value={selectedPaymentProvider}
2653 onValueChange={(value) => setSelectedPaymentProvider(value)}
2654 >
2655 {paymentProviders.map((paymentProvider) => (
2656 <div className="flex gap-1" key={paymentProvider.id}>
2657 <RadioGroup.Item value={paymentProvider.id} />
2658 <div className="flex justify-between w-full gap-2">
2659 <span className="text-sm">{getProviderTitle(paymentProvider.id)}</span>
2660 </div>
2661 </div>
2662 ))}
2663 </RadioGroup>
2664 </div>
2665 {paymentUi}
2666 <hr className="bg-ui-bg-subtle" />
2667 <Button
2668 className="w-full"
2669 disabled={!canPlaceOrder || loading}
2670 onClick={placeOrder}
2671 >Pay {formatPrice(
2672 cart?.total || 0,
2673 cart?.currency_code
2674 )}</Button>
2675 </Card>
2676 )
2677 ```
2678
2679 You first define a `getProviderTitle` function that receives a payment provider ID and returns a title based on the provider. You'll use this function to show a human-readable title for each payment provider.
2680
2681 Then, in the return statement, you wrap the payment method selection form with the `Card` component you created earlier. In the card, you show the cart's details, including the items, totals, and delivery address.
2682
2683 You also show the list of payment providers, allowing the customer to select one. Once the customer chooses one, you show any additional UI to complete their payment.
2684
2685 After the customer selects an option and clicks the "Pay" button, the `placeOrder` function is called to complete the cart and place the order.
2686
2687 ### Add to Router Component
2688
2689 Finally, you'll add the `Payment` component to the `Router` component to show the payment method selection step.
2690
2691 First, import the `Payment` component at the top of the `components/Router/index.tsx` file:
2692
2693 ```tsx title="components/Router/index.tsx"
2694 import { Payment } from "../Payment"
2695 ```
2696
2697 Then, change the `return` statement of the `Router` component to the following
2698
2699 ```tsx title="components/Router/index.tsx" highlights={[["6"]]}
2700 return (
2701 <>
2702 <Product handle={handle} isActive={activeTab === "product"} />
2703 <Address handle={handle} isActive={activeTab === "address"} />
2704 <Shipping handle={handle} isActive={activeTab === "shipping"} />
2705 <Payment handle={handle} isActive={activeTab === "payment"} />
2706 </>
2707 )
2708 ```
2709
2710 This will show the payment method selection step and expand its details if `activeTab` is `payment`.
2711
2712 ### Test it Out
2713
2714 While both the Medusa application and the Next.js Starter Storefront are running, if you refresh the page you had opened or go to `http://localhost:3000/sweatpants?step=payment`, you should see the Payment step where you can choose a payment method.
2715
2716 ![Payment step showing the payment providers and a pay button](https://res.cloudinary.com/dza7lstvk/image/upload/v1735833736/Medusa%20Resources/Screenshot_2025-01-02_at_6.01.58_PM_usjlli.png)
2717
2718 Select a payment provider then click on the "Pay" button. The payment method will be saved in the cart and you'll be redirected to the confirmation page, which currently doesn't exist. You'll add this page next.
2719
2720 ---
2721
2722 ## Step 11: Create Confirmation Page
2723
2724 After the customer places an order, you redirect them to a confirmation page that shows them their general order details. In this step, you'll create this confirmation page.
2725
2726 The confirmation page will receive the order's ID as a path parameter. Then, it'll retrieve the order's details from the Medusa application and shows those details to the customer.
2727
2728 To create the confirmation page, create the file `app/confirmation/[id]/page.tsx` with the following content:
2729
2730 ![Directory structure after creating confirmation page file](https://res.cloudinary.com/dza7lstvk/image/upload/v1735890379/Medusa%20Resources/express-checkout-13_shwtvh.jpg)
2731
2732 export const confirmationHighlights = [
2733 ["11", "orderId", "Retrieve the order's ID from the path parameter."],
2734 ["13", "order", "Retrieve the order's details from the Medusa application."],
2735 ]
2736
2737 ```tsx title="app/confirmation/[id]/page.tsx" highlights={confirmationHighlights}
2738 import { clx, Heading } from "@medusajs/ui"
2739 import { sdk } from "@/lib/sdk"
2740
2741 type Params = {
2742 params: Promise<{ id: string }>
2743 }
2744
2745 export default async function ConfirmationPage({
2746 params,
2747 }: Params) {
2748 const orderId = (await params).id
2749
2750 const { order } = await sdk.store.order.retrieve(orderId)
2751
2752 return (
2753 <div className={clx(
2754 "bg-ui-bg-base rounded-lg py-4 px-6 w-full",
2755 "flex gap-4 flex-col shadow-elevation-card-rest"
2756 )}>
2757 <Heading level="h2">Thank you, {order.shipping_address?.first_name}!</Heading>
2758 <p className="text-ui-fg-subtle">Your order has been placed. We are working to get it settled.</p>
2759 <hr className="bg-ui-bg-subtle" />
2760 <div className="flex gap-2 flex-col">
2761 <span className="flex gap-1">
2762 <span className="text-sm text-ui-fg-muted">Order number:</span>
2763 <span className="text-sm text-ui-fg-base">{order.display_id}</span>
2764 </span>
2765 <span className="flex gap-1">
2766 <span className="text-sm text-ui-fg-muted">Order date:</span>
2767 <span className="text-sm text-ui-fg-base">{
2768 order.created_at.toString()
2769 }</span>
2770 </span>
2771 </div>
2772 </div>
2773 )
2774 }
2775 ```
2776
2777 The `ConfirmationPage` component receives the order ID as a path parameter. In the component, you retrieve the order's details from the Medusa application using the JS SDK.
2778
2779 Then, you show the order's details, including the order number, order date, and a thank you message.
2780
2781 ### Test it Out
2782
2783 While both the Medusa application and the Next.js Starter Storefront are running, either refresh the page you had open from the previous step, or restart the express checkout flow to place an order. You'll see the confirmation page showing the order's details.
2784
2785 ![Confirmation page showing the order's ID and date](https://res.cloudinary.com/dza7lstvk/image/upload/v1735834096/Medusa%20Resources/Screenshot_2025-01-02_at_6.07.38_PM_um4p0a.png)
2786
2787 ---
2788
2789 ## Next Steps
2790
2791 By following this guide, you now have an express checkout storefront built with Next.js that connects to a Medusa commerce application.
2792
2793 You can add more features to your storefront or commerce application. For example, you can integrate a [Notification Module Provider](../../../infrastructure-modules/notification/page.mdx) to send the customer a confirmation email when they place their order.
2794
2795 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
2796
2797 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).