Skip to content

Next.js storefront quickstart

A Next.js App Router shop for Northwilds with a product list, product pages, a cart and checkout through the storefront API and Stripe's Payment Element.

Tutorial14 min read

In about 20 minutes you build a Next.js shop for Northwilds that reads its products from Commerce Orbit. Shoppers browse the gear, open a product, put it in a cart, choose a delivery and pay with Stripe's Payment Element. Payment goes straight to the shop's own Stripe account.

Every call to Commerce Orbit in this guide is made from your Next.js server, so you don't need to add the website to Allowed websites, and the cart token stays in an httpOnly cookie.

Tested with: Next.js 16.4.5, React 19.3, @stripe/stripe-js 10.2.1, Node.js 24, against a shop in Stripe test mode.

Before you start

You need:

  • A Commerce Orbit shop with a shop address under Settings, such as northwilds, at least one active product and a shipping zone for the countries you sell to.
  • Stripe connected under Stripe. Use test mode while you build: the test card 4242 4242 4242 4242 then pays without charging anyone.
  • Node.js 20 or later.

You don't need an API key or Stripe keys of your own. Reading the catalogue and running carts needs no key, and checkout hands you the shop's Stripe publishable key.

1Create the project

Shell
npx create-next-app@latest northwilds-shop --ts --app --eslint --no-tailwind --no-src-dir --import-alias "@/*" --no-cache-components --yescd northwilds-shoprm app/page.module.cssnpm install @stripe/stripe-js server-only

server-only makes the build fail if the shop helper is ever imported into browser code.

Add the storefront address of your shop:

.env.localShell
SHOP_API_URL=https://app.bifrostorbit.com/commerce/api/public/northwilds

2Add the shop helper

One small helper calls the storefront API, unwraps data and turns an error into an exception that keeps the status and code.

lib/shop.tsTypeScript
import 'server-only'import { cookies } from 'next/headers'const base = process.env.SHOP_API_URL!export type Money = numberexport interface Variant {  id: string  title: string  price: Money | null  available: boolean  quantity: number | null}export interface Product {  id: string  slug: string  title: string  summary: string  description: string  images: { url: string; alt: string }[]  price: { min: Money | null; max: Money | null; currency: string }  available: boolean  variants: Variant[]  seo: { title: string; description: string }}export interface Cart {  token: string  currency: string  count: number  email: string | null  name: string | null  needsShipping: boolean  country: string | null  shippingAddress: { line1: string; postalCode: string; city: string; country: string } | null  lines: { variantId: string; title: string; variantTitle: string | null; quantity: number; unitPrice: Money; total: Money; problem: string | null }[]  shippingChoices: { kind: 'rate' | 'pickup'; id: string; name: string; price: Money }[]  shipping: { kind: 'rate' | 'pickup'; rateId?: string; locationId?: string } | null  totals: { subtotal: Money; discountTotal: Money; shippingTotal: Money; taxTotal: Money; total: Money; amountDue: Money } | null  problems: string[]}export class ShopError extends Error {  constructor(message: string, readonly status: number, readonly code: string) {    super(message)  }}export async function shop<T>(path: string, init: { method?: string; body?: unknown; revalidate?: number } = {}): Promise<T> {  const response = await fetch(`${base}${path}`, {    method: init.method ?? (init.body === undefined ? 'GET' : 'POST'),    headers: init.body === undefined ? undefined : { 'Content-Type': 'application/json' },    body: init.body === undefined ? undefined : JSON.stringify(init.body),    ...(init.revalidate ? { next: { revalidate: init.revalidate } } : { cache: 'no-store' }),  })  const json = await response.json()  if (!response.ok) throw new ShopError(json.error?.message ?? `The shop answered ${response.status}`, response.status, json.error?.code ?? 'error')  return json.data as T}export const price = (amount: Money | null, currency: string) =>  amount === null ? '' : new Intl.NumberFormat('en-GB', { style: 'currency', currency }).format(amount / 100)export async function currentCart(): Promise<Cart | null> {  const token = (await cookies()).get('cart')?.value  if (!token) return null  return shop<Cart>(`/carts/${token}`).catch(() => null)}
  • Amounts are whole minor units: 72900 with EUR is €729.00. price formats them.
  • revalidate keeps catalogue answers for 30 seconds, the same time the storefront API allows them to be cached. Carts and orders are never cached.
  • The types hold only the fields this guide uses. The storefront API lists them all.

3List the products

Replace app/page.tsx:

app/page.tsxTypeScript
import Link from 'next/link'import { price, shop, type Product } from '@/lib/shop'export const revalidate = 30export default async function Home() {  const products = await shop<Product[]>('/products?limit=24', { revalidate: 30 })  return (    <main>      <h1>Gear</h1>      <ul className="products">        {products.map((product) => (          <li key={product.id}>            <Link href={`/products/${product.slug}`}>              {product.images[0] ? <img src={product.images[0].url} alt={product.images[0].alt} width={320} height={320} /> : null}              <span>{product.title}</span>            </Link>            <p>{product.available ? price(product.price.min, product.price.currency) : 'Sold out'}</p>          </li>        ))}      </ul>    </main>  )}

Check it: run npm run dev and open http://localhost:3000. You see the shop's active products with their photos and prices, such as the Arctic 3 tent at €729.00. A product with nothing left to buy says "Sold out".

next build reads the products to build this page, so the shop must be reachable from where you build.

4Show a product

app/products/[slug]/page.tsxTypeScript
import type { Metadata } from 'next'import { notFound } from 'next/navigation'import { addToCart } from '@/app/cart/actions'import { price, shop, ShopError, type Product } from '@/lib/shop'type Props = { params: Promise<{ slug: string }> }export const revalidate = 30export function generateStaticParams() {  return []}async function load({ params }: Props) {  const { slug } = await params  try {    return await shop<Product>(`/products/${encodeURIComponent(slug)}`, { revalidate: 30 })  } catch (error) {    if (error instanceof ShopError && error.status === 404) notFound()    throw error  }}export async function generateMetadata(props: Props): Promise<Metadata> {  const product = await load(props)  return { title: product.seo.title, description: product.seo.description }}export default async function ProductPage(props: Props) {  const product = await load(props)  const buyable = product.variants.filter((variant) => variant.available && variant.price !== null)  return (    <main>      {product.images[0] ? <img src={product.images[0].url} alt={product.images[0].alt} width={640} height={640} /> : null}      <h1>{product.title}</h1>      <p>{price(product.price.min, product.price.currency)}</p>      <div dangerouslySetInnerHTML={{ __html: product.description }} />      {buyable.length ? (        <form action={addToCart}>          {buyable.length > 1 ? (            <label>              Choose              <select name="variantId">                {buyable.map((variant) => (                  <option key={variant.id} value={variant.id}>                    {variant.title}, {price(variant.price, product.price.currency)}                  </option>                ))}              </select>            </label>          ) : (            <input type="hidden" name="variantId" value={buyable[0].id} />          )}          <button type="submit">Add to cart</button>        </form>      ) : (        <p>Sold out</p>      )}    </main>  )}
  • /products/{slug} finds a product by its address. An address that doesn't exist answers 404, which shows Next.js's not found page.
  • seo is filled from the title and summary when the shop left it empty, so every product has a title and description.
  • description is HTML written by the shop's team in Commerce Orbit.
  • Variants without a price in the shop's currency, or with nothing left, are left out of the choice.

The form calls addToCart, which you write in the next step.

5Build the cart

Server actions start the cart, add to it and save the shopper's details:

app/cart/actions.tsTypeScript
'use server'import { cookies } from 'next/headers'import { redirect } from 'next/navigation'import { shop, ShopError, type Cart } from '@/lib/shop'async function changeCart(change: Record<string, unknown>) {  const jar = await cookies()  const token = jar.get('cart')?.value  if (token) {    try {      return await shop<Cart>(`/carts/${token}`, { method: 'PATCH', body: change })    } catch (error) {      if (!(error instanceof ShopError && (error.status === 404 || error.status === 409))) throw error    }  }  const created = await shop<Cart>('/carts', { body: change })  jar.set('cart', created.token, { httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV === 'production', maxAge: 60 * 60 * 24 * 30 })  return created}export async function addToCart(formData: FormData) {  await changeCart({ add: [{ variantId: String(formData.get('variantId')), quantity: 1 }] })  redirect('/cart')}export async function saveDetails(formData: FormData) {  const text = (name: string) => String(formData.get(name) ?? '').trim()  const [kind, id] = text('shipping').split(':')  await changeCart({    email: text('email'),    name: text('name'),    country: text('country'),    shippingAddress: { name: text('name'), line1: text('line1'), postalCode: text('postalCode'), city: text('city'), country: text('country') },    ...(id ? { shipping: kind === 'pickup' ? { kind, locationId: id } : { kind, rateId: id } } : {}),  })  redirect('/cart')}export type Checkout =  | { reference: string; email: string; payment: { clientSecret: string; publishableKey: string } | null }  | { error: string }export async function startCheckout(): Promise<Checkout> {  const token = (await cookies()).get('cart')?.value  if (!token) return { error: 'Your cart is empty.' }  try {    const cart = await shop<Cart>(`/carts/${token}`)    const order = await shop<{ reference: string; status: 'pay' | 'placed'; payment: { clientSecret: string; publishableKey: string } | null }>(      `/carts/${token}/checkout`,      { body: { method: 'card' } },    )    return { reference: order.reference, email: cart.email ?? '', payment: order.payment }  } catch (error) {    return { error: error instanceof ShopError ? error.message : 'Something went wrong. Try again.' }  }}export async function forgetCart() {  (await cookies()).delete('cart')}
  • The first change starts a cart with POST/carts. Later changes go to PATCH/carts/{token} with only what changes.
  • A cart that is gone (404) or already ordered (409) is replaced by a new one, so a shopper who comes back after paying starts afresh.
  • The country sets which delivery choices and VAT apply before checkout.
  • startCheckout creates the order and the Stripe PaymentIntent. Calling it again before the order is paid cancels the earlier unpaid order and makes a new one.

Now the cart page:

app/cart/page.tsxTypeScript
import Link from 'next/link'import { currentCart, price } from '@/lib/shop'import { saveDetails } from './actions'import { Payment } from './payment'export const dynamic = 'force-dynamic'export default async function CartPage() {  const cart = await currentCart()  if (!cart || cart.count === 0) {    return (      <main>        <h1>Your cart is empty</h1>        <Link href="/">See the gear</Link>      </main>    )  }  const address = cart.shippingAddress  const chosen = cart.shipping ? `${cart.shipping.kind}:${cart.shipping.rateId ?? cart.shipping.locationId}` : ''  return (    <main>      <h1>Your cart</h1>      <ul>        {cart.lines.map((line) => (          <li key={line.variantId}>            {line.quantity} × {line.title}{line.variantTitle ? ` (${line.variantTitle})` : ''}: {price(line.total, cart.currency)}            {line.problem ? <strong> {line.problem}</strong> : null}          </li>        ))}      </ul>      <form action={saveDetails}>        <input name="email" type="email" placeholder="Email" defaultValue={cart.email ?? ''} required />        <input name="name" placeholder="Full name" defaultValue={cart.name ?? ''} required />        <input name="line1" placeholder="Address" defaultValue={address?.line1 ?? ''} required />        <input name="postalCode" placeholder="Postcode" defaultValue={address?.postalCode ?? ''} required />        <input name="city" placeholder="Town or city" defaultValue={address?.city ?? ''} required />        <input name="country" placeholder="Country, such as NO" maxLength={2} defaultValue={address?.country ?? cart.country ?? 'NO'} required />        {cart.shippingChoices.length ? (          <fieldset>            <legend>Delivery</legend>            {cart.shippingChoices.map((choice) => (              <label key={choice.id}>                <input type="radio" name="shipping" value={`${choice.kind}:${choice.id}`} defaultChecked={chosen === `${choice.kind}:${choice.id}`} />                {choice.name}, {price(choice.price, cart.currency)}              </label>            ))}          </fieldset>        ) : null}        <button type="submit">Save</button>      </form>      {cart.totals ? (        <dl>          <dt>Subtotal</dt>          <dd>{price(cart.totals.subtotal, cart.currency)}</dd>          <dt>Discounts</dt>          <dd>{price(-cart.totals.discountTotal, cart.currency)}</dd>          <dt>Delivery</dt>          <dd>{price(cart.totals.shippingTotal, cart.currency)}</dd>          <dt>Total</dt>          <dd>{price(cart.totals.total, cart.currency)}</dd>        </dl>      ) : null}      {cart.problems.length ? (        <ul>          {cart.problems.map((problem) => (            <li key={problem}>{problem}</li>          ))}        </ul>      ) : (        <Payment />      )}    </main>  )}
  • shippingChoices come from the shop's shipping zones for the country, such as Standard delivery, Express and collection from the Bergen store. Save the address first, then pick one.
  • totals is worked out by Commerce Orbit, with discounts such as an automatic "10% off when you spend 150 euros", delivery and VAT.
  • problems lists what stops checkout, such as "Choose how you'd like it delivered" or "Only 2 of Tind 2 tent are left". Show them as they are.

Finally, add a header with a link to the cart. Replace app/layout.tsx:

app/layout.tsxTypeScript
import type { Metadata } from 'next'import Link from 'next/link'import './globals.css'export const metadata: Metadata = { title: 'Northwilds' }export default function RootLayout({ children }: LayoutProps<'/'>) {  return (    <html lang="en">      <body>        <header>          <Link href="/">Northwilds</Link> <Link href="/cart">Cart</Link>        </header>        {children}      </body>    </html>  )}

Check it: open a product and select Add to cart. The cart shows the line and its total. Fill in the address with country NO, select Save, pick a delivery and select Save again: the delivery appears in the totals.

6Take payment

The payment step runs in the browser. It asks your server action for the checkout, shows the Payment Element with the shop's publishable key and client secret, and confirms with Stripe:

app/cart/payment.tsxTypeScript
'use client'import { loadStripe, type Stripe, type StripeElements } from '@stripe/stripe-js'import { useEffect, useRef, useState } from 'react'import { startCheckout, type Checkout } from './actions'export function Payment() {  const [checkout, setCheckout] = useState<Checkout | null>(null)  const [message, setMessage] = useState('')  const stripe = useRef<{ stripe: Stripe; elements: StripeElements } | null>(null)  const mount = useRef<HTMLDivElement>(null)  const orderPage = (reference: string, email: string) => `/orders/${reference}?email=${encodeURIComponent(email)}`  useEffect(() => {    if (!checkout || 'error' in checkout) return    if (!checkout.payment) {      window.location.assign(orderPage(checkout.reference, checkout.email))      return    }    const { clientSecret, publishableKey } = checkout.payment    let live = true    loadStripe(publishableKey).then((loaded) => {      if (!live || !loaded || !mount.current) return      const elements = loaded.elements({ clientSecret })      elements.create('payment').mount(mount.current)      stripe.current = { stripe: loaded, elements }    })    return () => {      live = false    }  }, [checkout])  async function pay() {    if (!stripe.current || !checkout || 'error' in checkout) return    const { error } = await stripe.current.stripe.confirmPayment({      elements: stripe.current.elements,      confirmParams: { return_url: new URL(orderPage(checkout.reference, checkout.email), window.location.origin).toString() },    })    if (error) setMessage(error.message ?? 'The payment did not go through.')  }  if (!checkout || 'error' in checkout) {    return (      <>        {checkout ? <p role="alert">{checkout.error}</p> : null}        <button type="button" onClick={async () => setCheckout(await startCheckout())}>          Continue to payment        </button>      </>    )  }  return (    <>      <div ref={mount} />      <button type="button" onClick={pay}>        Pay now      </button>      {message ? <p role="alert">{message}</p> : null}    </>  )}
  • The publishable key comes with each checkout, so the shop can change from test to live keys without you changing code.
  • The Payment Element shows the payment methods switched on in the shop's Stripe account, such as cards and Klarna.
  • return_url is your order page. Stripe sends the shopper there after paying, also after 3D Secure or a bank's own page.
  • payment: null means the order needed no card payment, such as one paid in full by gift cards. The shopper goes straight to the order page.

Check it: in the cart, select Continue to payment. The Payment Element appears. Choose Card, enter 4242 4242 4242 4242, any future expiry date and any CVC, and select Pay now.

7Show the order

app/orders/[reference]/page.tsxTypeScript
import { notFound } from 'next/navigation'import { price, shop, ShopError } from '@/lib/shop'import { ForgetCart } from './forget-cart'type Order = {  reference: string  paymentStatus: 'pending' | 'paid' | 'failed' | 'invoiced' | 'partiallyRefunded' | 'refunded'  currency: string  lines: { title: string; variantTitle: string; quantity: number; total: number }[]  total: number}type Props = { params: Promise<{ reference: string }>; searchParams: Promise<{ email?: string }> }export const dynamic = 'force-dynamic'export default async function OrderPage({ params, searchParams }: Props) {  const { reference } = await params  const { email = '' } = await searchParams  const order = await shop<Order>(`/orders/${encodeURIComponent(reference)}?email=${encodeURIComponent(email)}`).catch((error) => {    if (error instanceof ShopError && error.status === 404) notFound()    throw error  })  return (    <main>      <h1>{order.paymentStatus === 'paid' ? 'Thank you for your order' : order.paymentStatus === 'pending' ? 'We are confirming your payment' : 'Your order'}</h1>      <p>Order {order.reference}</p>      <ul>        {order.lines.map((line, index) => (          <li key={index}>            {line.quantity} × {line.title}: {price(line.total, order.currency)}          </li>        ))}      </ul>      <p>Total {price(order.total, order.currency)}</p>      {order.paymentStatus === 'paid' ? <ForgetCart /> : null}    </main>  )}
app/orders/[reference]/forget-cart.tsxTypeScript
'use client'import { useEffect } from 'react'import { forgetCart } from '@/app/cart/actions'export function ForgetCart() {  useEffect(() => {    forgetCart()  }, [])  return null}
  • The order needs the email it was placed with. Any other email answers 404.
  • If Stripe's message hasn't arrived yet, Commerce Orbit asks Stripe itself, so paymentStatus is paid as soon as the payment went through. Show pending as "We are confirming your payment" and let the shopper reload.
  • ForgetCart removes the cart cookie once the order is paid, so the next visit starts a new cart.

Check it: after paying, you land on /orders/NW1013?email=… with "Thank you for your order", the order's lines and its total. The order is in Orders in Commerce Orbit, marked as paid, and /cart is empty again.

Next steps

Was this page helpful?

Read next