Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 33 ยท Storefront

Building the Checkout Flow

Build a Medusa checkout step by step: address, shipping method, payment session, complete cart, error states, guest vs customer checkout and idempotent submit.

Checkout is the one flow in a shop where every mistake costs money. Medusa breaks it into small Store API calls: set the email and address, choose shipping, start a payment session, and finally complete the cart, which turns it into an order. Each call changes the cart, and the cart tells you what is still missing.

This lesson follows those calls in order, explains what can go wrong at each step, compares guest and signed-in checkout, and shows how to make the final submit safe against double clicks. Real calls need a Medusa server, so the HTTP and SDK examples are read-only. The runnable stand-in is a checkout state machine in plain Node that enforces the same ordering rules. For the design thinking behind checkout see Checkout Design and Flow and Idempotency.

The steps at a glance

flowchart LR
    A["Cart with items"] --> B["Email and addresses"]
    B --> C["Shipping method"]
    C --> D["Payment collection<br/>and session"]
    D --> E["Browser confirms<br/>with the gateway"]
    E --> F["Complete cart"]
    F -->|"type: order"| G["Order confirmation"]
    F -->|"type: cart + error"| B

Completion either returns an order or returns the cart with an error, and the storefront sends the shopper back to the step that needs attention.

Prerequisites: a cart in a region with items, a publishable key and a configured payment provider (The Next.js Starter Storefront, Payment Providers). The requests below use the Store API; with the JS SDK they are methods under sdk.store.cart, sdk.store.fulfillment and sdk.store.payment. Check method names in the SDK version you install.

Step 1: email and addresses

HTTP
POST /store/carts/{cart_id}
x-publishable-api-key: pk_...
Content-Type: application/json

{
  "email": "[email protected]",
  "shipping_address": {
    "first_name": "Dana", "last_name": "Fox",
    "address_1": "12 Harbor Road", "city": "Hamburg",
    "postal_code": "20457", "country_code": "de"
  },
  "billing_address": { "...": "same shape, or copy the shipping address" }
}

The country code matters twice: it must be one of the countries in the cart's region, and it decides which shipping options and tax rates apply (Fulfillment, Shipping and Tax Providers). Validate fields in the browser for speed, but remember the server has the final word: an invalid address returns an error that you must show next to the form.

Step 2: shipping options and method

Ask which options are available for this cart:

HTTP
GET /store/shipping-options?cart_id={cart_id}

The result lists options whose service zone covers the address and whose shipping profile matches the items. For options with calculated prices, the response can include a calculated_price once the provider has computed it. After the shopper picks one:

HTTP
POST /store/carts/{cart_id}/shipping-methods
{ "option_id": "so_01..." }

This adds a shipping method to the cart and updates totals. If the shopper changes the address afterwards, the available options can change, so re-fetch options whenever the address changes and make sure the chosen method is still valid. A cart with items from two shipping profiles needs a method per profile.

Step 3: the payment session

First make sure the cart has a payment collection, then start a session with the chosen provider:

HTTP
POST /store/payment-collections
{ "cart_id": "{cart_id}" }

POST /store/payment-collections/{payment_collection_id}/payment-sessions
{ "provider_id": "pp_stripe_stripe" }

The session's data holds what the gateway's browser script needs (for Stripe, a client secret). The starter then renders the gateway's card element, and when the shopper presses "Place order" the browser confirms the payment with the gateway first. Card data goes straight from the browser to the gateway (PCI Scope, 3-D Secure and SCA). If the amount changes after the session was created (a new shipping method, say), the payment session has to be refreshed so the gateway amount matches the cart total. Most storefronts simply start a new session when moving to the payment step.

Step 4: complete the cart

HTTP
POST /store/carts/{cart_id}/complete

The response has a type:

  • "order": success, with the order object. Redirect to a confirmation page.
  • "cart": something blocked the completion, with an error. Show it, return the shopper to the right step and keep the cart.

Behind this one call, a workflow validates the cart, authorizes the payment through the provider, reserves inventory and creates the order, as a unit with compensation if a step fails (Hooks and Built-in Workflows, Compensation, Rollback and Long-Running Workflows). That is why the storefront does not create orders itself: the order, the reservation and the payment authorization either all happen or none do.

Error states to design for

Situation What the shopper should see
Item went out of stock Which item, with a link back to the cart
Payment declined or 3-D Secure failed A card-specific message and the chance to retry or pick another method
Shipping option no longer valid Return to the delivery step with fresh options
Address in an unsupported country Inline error on the address form
Network failure on complete "We are checking your order", then retrieve the cart before retrying

The last row deserves care. If the request to complete times out, the order may or may not exist. Do not tell the shopper "failed" and let them pay again. Retrieve the cart: if it has been completed, look up the order; otherwise show the retry button.

Guest versus signed-in checkout

A cart works without an account: set email on the cart and the order is linked to that email address. A signed-in customer (token in the request) gets the cart attached to their customer record, saved addresses can prefill the forms, and the order shows up in their account. Medusa also lets a guest create an account after the purchase, which converts better than forcing registration up front. Whichever you choose, one rule holds: never trust the client about identity. The customer comes from the verified token, not from an id in the request body (The Store API).

Making the final submit idempotent

Double clicks, retries after a timeout and back-button resubmissions all call "complete" twice. Medusa's completion is built so that completing an already-completed cart does not create a second order, but your storefront should still behave well:

  1. Disable the button and show progress as soon as the first click happens.
  2. Use one cart id and one in-flight request. Keep a flag or use the form's pending state (in Next.js, useFormStatus or a server action's pending flag).
  3. After any failure or timeout, check the cart state first, then decide whether to retry.
  4. Never create a second payment session behind the shopper's back. One gateway intent per attempt.

The principle is the one from Idempotency: a repeated request with the same intent must have the same result as one request.

Order confirmation

After success, use the returned order id to show a confirmation page: items, totals, address, shipping method and a payment summary. Clear the cart cookie, because the cart is now an order (The Next.js Starter Storefront). The confirmation email comes from a subscriber on the order placed event (Notifications, Email and File Providers), not from the browser.

Stand-in: a checkout state machine

The stand-in is not Medusa. It models the ordering rules of checkout as a state machine over a cart object: each step requires the previous ones, changing an earlier step invalidates later ones, and completion is safe to repeat.

Node.js A checkout state machine with idempotent completion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two behaviors are worth studying. Changing the address clears the shipping method and the payment session, because both depended on it; the real flow requires the same re-selection. And the second complete() returns the same order and does not increment orders, which is the property your UI should be able to rely on and also protect.

The stand-in decides everything on the client side of the example, which is fine for learning. In a real shop, never decide totals or order creation in the browser. The server computes totals, validates every step and authorizes the payment, and the storefront only displays the result.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does POST /store/carts/{id}/complete return when something blocks the order?

    Completion returns type "order" on success, or type "cart" with an error. The cart stays intact so the shopper can fix the problem and try again.
  2. 2. The shopper changes the shipping country after choosing a shipping method. What should the storefront do?

    Options and tax depend on the address, and the total changes with the method, so the method (and a payment session created for the old amount) must be re-established.
  3. 3. The complete request times out. What is the safest next action?

    The order may exist even though the response was lost. Checking the cart state first avoids double charges and duplicate orders.
  4. 4. Where does a signed-in customer's identity come from during checkout?

    Identity must come from the verified token. Values supplied in the body can be forged.
  5. 5. Who confirms a card payment with the gateway before the cart is completed?

    Card details go directly from the browser to the gateway, which keeps them off your server. Completion then asks the provider to authorize the already-confirmed payment.

Summary

  • Checkout is a sequence of Store API calls: email and addresses, shipping method, payment collection and session, gateway confirmation in the browser, then complete cart.
  • Completion returns an order or the cart with an error; design a clear message and return path for each error.
  • Changing an earlier step (address, shipping) invalidates later ones; re-fetch options and refresh the payment session.
  • Guest and signed-in carts use the same flow; identity comes from the verified token.
  • Make the submit idempotent: disable the button, keep one request in flight, and check the cart before any retry.

Next, learn how to test all of this in Testing Modules, Workflows and APIs.