Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 33 ยท The APIs

The Store API

Learn the Medusa Store API: publishable keys, regions, product queries with fields, carts, shipping and payment sessions, completing a cart, customers and the JS SDK.

Every Medusa storefront, whether it is the Next.js starter, a mobile app or a kiosk, talks to the same HTTP interface: the Store API. It lives under /store, it is meant to be called from untrusted places such as browsers, and it exposes exactly what a shopper may do: browse products, build a cart, pick shipping and payment, place an order, and manage their own account.

This lesson walks the API in the order a shopper uses it. The real server needs Node, Postgres and a Medusa project, so the real requests are shown read-only. The runnable parts are stand-ins: a small HTTP server on loopback that mimics the shape of the flow, and a client wrapper that behaves like the JS SDK. They are not Medusa, and they say so wherever it matters. For the order of the checkout steps in general, see Checkout Flow.

The publishable API key

Store API routes require a publishable API key in the x-publishable-api-key header. You create it in the Admin and attach one or more sales channels to it. The key does two jobs:

  1. It identifies which storefront is calling, so Medusa knows the sales channel (and therefore the stock locations, see Inventory, Stock Locations and Sales Channels).
  2. It scopes catalog reads: products not in the key's sales channels are not returned.

A publishable key is not a secret. It ships in your frontend code and anyone can read it. It limits what a caller can see, not who they are. Anything sensitive is protected by customer authentication or by the Admin API, never by this key. More on this in Security and Performance.

HTTP
GET /store/regions
x-publishable-api-key: pk_01HXYZ...

If the header is missing or unknown, the API answers with a 400-class error and does no work.

Regions and reading products

A region groups countries that share a currency, tax behavior and payment and shipping setup (see Prices, Currencies and Regions). The storefront fetches regions first, lets the shopper choose a country, and then uses that region for prices.

Product lists accept query parameters. Two matter most:

  • fields selects which properties come back. Medusa's default response is small, so you ask for more explicitly: *variants adds relations, +variants.inventory_quantity adds a field to the defaults, -description removes one.
  • region_id (with country_code or province for taxes) tells the Pricing Module to compute calculated_price for each variant.
HTTP
GET /store/products?limit=12&offset=0&region_id=reg_eu
    &fields=id,title,handle,*variants,+variants.calculated_price
x-publishable-api-key: pk_01HXYZ...

The response contains products, count, limit and offset. Always page through large catalogs with limit and offset, and ask only for the fields the page really shows. Fetching *variants.prices for a grid of cards is the most common cause of slow storefronts. The same field syntax is used in the backend's query.graph (see Query: Fields, Filters and Pagination).

Carts and line items

A cart is created with a region (and optionally email, currency and sales channel). Everything after that targets the cart's ID:

HTTP
POST /store/carts
{ "region_id": "reg_eu" }

POST /store/carts/cart_01.../line-items
{ "variant_id": "variant_01...", "quantity": 2 }

POST /store/carts/cart_01...
{ "email": "[email protected]",
  "shipping_address": { "first_name": "Ada", "address_1": "1 Main St", "city": "Berlin", "country_code": "de", "postal_code": "10115" } }

The server owns the numbers. The response is the full cart with subtotal, tax_total, shipping_total and total, recalculated every time. The client must never compute prices itself: it displays what the server returns. This is the cart rule from Cart Design applied to an API. Store the cart ID in a cookie or local storage so the shopper keeps their cart (the starter storefront does this with a cookie).

Shipping and payment

After the address, the shopper chooses how the order travels and how it is paid:

HTTP
GET  /store/shipping-options?cart_id=cart_01...
POST /store/carts/cart_01.../shipping-methods
{ "option_id": "so_01..." }

POST /store/payment-collections
{ "cart_id": "cart_01..." }

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

A payment collection is the amount to collect for the cart, and a payment session is one attempt with one provider. Creating the session asks the provider (for example Stripe) to prepare a payment and returns the data your frontend needs to finish it, such as a client secret. The card details never touch Medusa. See Payment Providers for what happens behind this call and Payments Overview for the model.

Completing the cart

HTTP
POST /store/carts/cart_01.../complete

The response says what happened. On success it is { "type": "order", "order": { ... } }; when something blocks the order (for example the payment was not authorized or stock ran out) it returns { "type": "cart", "cart": { ... }, "error": { ... } } and the cart stays open. Completion runs a server-side workflow that authorizes payment, reserves stock and creates the order, rolling back if a step fails (built-in workflows). Because a shopper can double-click, the endpoint must be safe to call twice, which is the idempotency idea from Idempotency.

Customers and authentication

Guests can check out with just an email. Registered customers authenticate through the Auth Module. In short: the storefront calls an auth route for the customer actor type with the emailpass provider, receives a JWT, and sends it as Authorization: Bearer <token> on later requests. The same ideas, from the admin side, are in The Admin API and Authentication. Customer-only routes such as GET /store/customers/me and order history are rejected without a valid token.

The JS SDK

Writing raw fetch calls with headers everywhere is tedious, so Medusa ships a JS SDK. You create one client, give it the base URL and the publishable key, and call methods grouped by area (read-only; check method names for your version):

TypeScript
import Medusa from "@medusajs/js-sdk"

export const sdk = new Medusa({
  baseUrl: process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL!,
  publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
})

const { regions } = await sdk.store.region.list()
const { products } = await sdk.store.product.list({
  region_id: regions[0].id,
  fields: "id,title,*variants,+variants.calculated_price",
  limit: 12,
})
const { cart } = await sdk.store.cart.create({ region_id: regions[0].id })
await sdk.store.cart.createLineItem(cart.id, { variant_id: products[0].variants[0].id, quantity: 1 })

The SDK adds the key, handles JSON, throws on error responses and keeps the types in sync with the server. It does nothing magical: every call is one of the HTTP requests above.

sequenceDiagram
    participant S as Storefront
    participant A as Store API
    S->>A: GET /store/regions (publishable key)
    S->>A: GET /store/products?region_id=...
    S->>A: POST /store/carts
    S->>A: POST .../line-items
    S->>A: POST .../shipping-methods
    S->>A: POST /store/payment-collections + session
    S->>A: POST .../complete
    A-->>S: type order

Seven calls take a shopper from landing page to an order; each response is the whole updated resource.

Stand-in 1: publishable keys and field selection

The first stand-in is plain JavaScript, not Medusa. It shows the two behaviors that surprise newcomers: a key that scopes products to a sales channel, and a fields string that adds and removes properties on top of the defaults.

Node.js Publishable key scoping and field selection

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.

Notice that the outlet key sees only one product, and a missing key never reaches the product code. In real Medusa the same scoping is done by the framework, from the sales channels attached to the key in the Admin.

Stand-in 2: a loopback store server and an SDK-like client

The second stand-in starts a real HTTP server on the loopback address, with routes named like Store API routes, and a small client that behaves like the JS SDK: it adds the key, parses JSON and throws on errors. The server recalculates totals itself, rejects an incomplete cart on completion, and is safe to complete twice.

Node.js A full cart flow against a loopback server

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.

What is real and what is not: the routes, the key header, the "complete returns type order or type cart" contract and the server-side totals mirror the real API. The data store is a Map, there are no regions, taxes, payment collections or authentication, and the real server runs workflows. Treat it as a map of the conversation, not an implementation.

Common mistakes

  • Treating the publishable key as a secret and trying to hide it, or as a security control and relying on it to protect private data.
  • Calculating totals in the browser. Always render the server's totals; they include tax, promotions and shipping rules you do not have.
  • Fetching everything. Request only the fields a view needs and page with limit.
  • Forgetting the region. Without region_id the products come back without a calculated_price.
  • Ignoring type: "cart" on completion. HTTP 200 does not mean an order exists; check type.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the publishable API key identify?

    The key ties a request to sales channels. It is safe to ship in frontend code because it limits what can be seen and does not authenticate a person.
  2. 2. How do you get calculated prices in a product list?

    The Pricing Module needs a context such as the region to calculate a price. Pass region_id (and country or province for taxes) and request the price field.
  3. 3. A complete-cart request returns HTTP 200 with type "cart" and an error. What does that mean?

    Completion reports blocking problems in the body. Only type "order" means an order exists, so the client must check type and show the error.
  4. 4. Which part of a payment does the Medusa server never see in a Stripe checkout?

    Card data goes from the shopper's browser directly to the payment provider. Medusa works with a payment session and provider references.

Summary

  • Store API calls carry a publishable key that scopes the sales channel but is not a secret.
  • Use fields, limit, offset and region_id to ask for exactly the products and prices a page needs.
  • Carts, line items, addresses, shipping methods, payment collections and sessions are separate steps, and the server recalculates totals every time.
  • Completing a cart returns type: "order" on success and type: "cart" with an error otherwise, and must be safe to repeat.
  • The JS SDK is a thin, typed wrapper around these HTTP calls.

Next, look at the other side of the backend: The Admin API and Authentication.