Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 33 ยท Storefront

The Next.js Starter Storefront

Tour the Medusa Next.js starter storefront: JS SDK setup, publishable key, server components and caching, region and cart cookies, product pages and checkout steps.

Medusa has no built-in shop front. It is headless, so you choose how the shop looks, and the most common starting point is the Next.js starter storefront that the Medusa team maintains. It is a complete shop (catalog, product pages, cart, checkout, account area) written with Next.js and the Medusa JS SDK. You can use it as is, restyle it or study it and build your own.

This lesson explains how the starter is organized and the ideas that are worth copying into any storefront: one SDK instance, the publishable key, server components with careful caching, a region chosen from the URL, and a cart id remembered in a cookie. File names and helper functions in the starter change between versions, so the code below is a read-only sketch of the patterns, not a copy of the starter. The runnable stand-in implements the cart-cookie and region resolver logic in plain Node.

What the starter contains

Roughly, a starter checkout has:

TEXT
src/
  app/
    [countryCode]/
      (main)/
        page.tsx                  home
        products/[handle]/        product page
        store/                    product list
        cart/                     cart page
        account/                  customer area
      (checkout)/checkout/        checkout steps
  lib/
    config.ts                     JS SDK instance
    data/                         server functions: products, cart, regions, customer
  middleware.ts                   region detection and cookie setup
  modules/                        UI components grouped by feature

The important design decision is that the URL begins with a country code (/de/products/alpine-tent). The country code selects a region in Medusa, and the region carries the currency, tax settings and available payment providers (see Prices, Currencies and Regions). Putting it in the URL makes pages cacheable per region and shareable.

One SDK, one publishable key

Every request to the Store API needs a publishable API key, which identifies the sales channel(s) the storefront may use. The key is public by design: it goes into the browser bundle, and it does not grant admin access. See The Store API and Security and Performance for the difference between publishable keys and secrets.

The starter creates one SDK instance:

TypeScript
// src/lib/config.ts
import Medusa from "@medusajs/js-sdk"

export const sdk = new Medusa({
  baseUrl: process.env.MEDUSA_BACKEND_URL || "http://localhost:9000",
  debug: process.env.NODE_ENV === "development",
  publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
})

Two environment variables matter: the backend URL and the publishable key. A missing or wrong key is the classic first error: the products list comes back empty or the API answers with an error, because no sales channel is attached to the request. Create the key in the Admin (Settings, Publishable API Keys) and link it to a sales channel that contains your products and stock locations (Inventory, Stock Locations and Sales Channels).

Server components and caching

Most starter pages are server components. They fetch from Medusa on the server and send HTML, so shoppers download little JavaScript and search engines see real content. The data functions live in one place and call the SDK:

TypeScript
// src/lib/data/products.ts  (sketch)
import { sdk } from "@lib/config"

export async function listProducts({ regionId, countryCode, limit = 12 }) {
  const { products, count } = await sdk.store.product.list(
    {
      limit,
      region_id: regionId,
      fields: "*variants.calculated_price,+variants.inventory_quantity,*variants.images,+metadata",
    },
    { next: { tags: ["products"] } },
  )
  return { products, count }
}

Note three things:

  • region_id and fields: prices are only calculated for a region, and the fields string asks for exactly what the page shows (see Query: Fields, Filters and Pagination).
  • next: { tags: [...] }: Next.js caches fetch results and lets you invalidate them by tag. Catalog data is the same for everybody, so it is cacheable.
  • Cart and customer data must not be shared: anything tied to the signed-in shopper or their cart is fetched without shared caching and with the shopper's credentials. A wrongly cached cart page is a privacy bug.

The same rule holds for any caching layer: public, anonymous data may be cached; per-user data may not. After you change products in the Admin you have to refresh the cache, either by time (revalidate) or by calling revalidateTag("products") from a webhook or subscriber (Events and Subscribers).

Regions and the middleware

The middleware runs before every request. Its job is to make sure the URL has a valid country code and the shopper has a cart-related cookie. In outline:

flowchart TD
    A["Request /products/tent"] --> B{"URL starts with<br/>a known country code?"}
    B -->|"no"| C["Pick country:<br/>cookie, geo header, default"]
    C --> D["Redirect to /de/products/tent"]
    B -->|"yes"| E["Continue"]
    E --> F["Region map<br/>country to region id"]
    F --> G["Page renders with the region's currency and prices"]

The region map comes from Medusa's region list, cached in the middleware so it does not call the backend on every request.

The country list is built from GET /store/regions, where each region has countries[]. A region such as "Europe" can contain Germany, France and Italy, so many country codes map to one region id. If the URL has an unknown code, the middleware falls back to a default (often from a geo header supplied by the host or CDN, then a configured default region).

A shopper's cart is created on the server and its id is stored in a cookie so that it survives navigation and page reloads. The starter uses a cookie named like _medusa_cart_id; a signed-in shopper also has an auth cookie holding their token. The pattern:

TypeScript
// sketch of cart retrieval
export async function getOrSetCart(countryCode: string) {
  const region = await getRegion(countryCode)
  let cartId = cookies().get("_medusa_cart_id")?.value
  let cart = cartId ? await retrieveCart(cartId) : null

  if (!cart) {
    const created = await sdk.store.cart.create({ region_id: region.id })
    cart = created.cart
    cookies().set("_medusa_cart_id", cart.id, {
      maxAge: 60 * 60 * 24 * 7,
      httpOnly: true,
      sameSite: "strict",
      secure: process.env.NODE_ENV === "production",
    })
  }

  if (cart.region_id !== region.id) {
    await sdk.store.cart.update(cart.id, { region_id: region.id })
  }
  return cart
}

Notice the final step. If the shopper moves from /de to /us, the cart's region must change too, because prices, currency and shipping options are region-dependent. Cookies are httpOnly so page scripts cannot read the cart id, and sameSite helps against cross-site request abuse. Carts expire: if the cookie points to a deleted or completed cart, retrieval fails and the code creates a fresh cart.

Product pages and checkout

A product page is a server component for /[countryCode]/products/[handle]. It looks the product up by handle with the region id, renders images and a variant selector, and an "Add to cart" server action calls sdk.store.cart.createLineItem(cartId, { variant_id, quantity }). Variant choice is local state: the option values the shopper picks map to one variant, exactly like the matrix from Products, Variants and Options. Out-of-stock states come from inventory_quantity and the manage_inventory and allow_backorder flags.

Checkout is a sequence of steps on one page (address, delivery, payment, review), and each step makes a Store API call. The next lesson, Building the Checkout Flow, takes those calls apart in order and models the process as a state machine.

The stand-in is not the starter. It reproduces the decision logic of the middleware and getOrSetCart as pure functions, so you can see every branch: unknown country, a country in a region with several countries, a first visit without a cart, a returning visit, a stale cart id and a cross-region move.

Node.js Country, region and cart-cookie resolution

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.

The first two redirects show that the original path is kept and only the country prefix is added. The cart log shows the two situations that bite real storefronts: a stale cookie (the code creates a new cart instead of failing) and a region switch (the existing cart is moved instead of keeping the wrong currency).

Customizing the starter

When you adapt the starter, change it in this order:

  1. Set the environment variables and confirm the product list loads.
  2. Restyle: Tailwind classes and the components in modules/. Keep server components for pages and add client components only for interactions (variant picker, cart drawer).
  3. Replace the payment step UI with the provider you configured (Payment Providers).
  4. Add your own features through custom API routes and call them from lib/data.
  5. Check the cache tags: anything per-user must not be cached.

If you upgrade the starter, compare against your changes in version control; treat it as your code after you copy it, not as a dependency.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the starter put a country code at the start of the URL?

    A region carries currency, tax settings and providers. Resolving it from the URL makes pages cacheable per region and shareable.
  2. 2. What is true about the publishable API key?

    Publishable keys are public by design. They scope requests to sales channels but do not authorize admin actions.
  3. 3. A shopper moves from /de to /us with an existing cart. What must happen?

    Prices and shipping options depend on the region, so the cart is updated to the new region (and recalculated) when the shopper switches.
  4. 4. Which data may be cached with shared tags in a server component?

    Public catalog data is the same for everyone and can be cached and revalidated by tag. Anything tied to a person or a cart must not be shared across users.

Summary

  • The Next.js starter is a full storefront built on server components and the Medusa JS SDK; copy its patterns, not its exact file names.
  • One SDK instance with the backend URL and publishable key serves every Store API call.
  • Region comes from the country code in the URL, resolved by middleware against GET /store/regions.
  • The cart id lives in an httpOnly cookie; handle stale carts and update the cart's region when the shopper switches.
  • Cache public catalog data by tag; never cache per-user data.

Next, follow every API call of a purchase in Building the Checkout Flow.