Skip to content

Add a cart and checkout to a CMS Orbit website

A Next.js website built with CMS Orbit that shows the products editors place on its pages, with a cart and Stripe checkout through the storefront API.

Tutorial14 min read

In about 20 minutes you add a shop to a Northwilds website built with CMS Orbit. Editors place products on any page with CMS Orbit's Product grid, Product card and Add to cart blocks. Your website draws those blocks with an Add to cart button, keeps the cart in Commerce Orbit and takes payment with Stripe's Payment Element, straight into the shop's own Stripe account.

Editors decide which products appear where, and Commerce Orbit keeps prices, stock, the cart and the order. Your website only draws them.

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

Before you start

You need:

  • A Next.js website for your CMS Orbit space, built with steps 1 to 6 of the CMS Orbit Next.js quickstart. This guide adds to that project.
  • The space connected to your shop under Configuration › Linked satellites in CMS Orbit, and a page with at least one Product grid, Product card or Add to cart block. See Products and collections from Commerce Orbit.
  • A Commerce Orbit shop with a shop address under Settings, such as northwilds, and a shipping zone for the countries you sell to.
  • Stripe connected under Stripe, in test mode while you build, so the test card 4242 4242 4242 4242 pays without charging anyone.

You don't need a Commerce Orbit API key or Stripe keys of your own.

1Install and configure

Shell
npm install @stripe/stripe-js

Add the storefront address of your shop to the settings you already have:

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

Then generate the types again, so they include the Commerce Orbit blocks:

Shell
npm run cms:types

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 Cart {  token: string  currency: string  count: number  email: string | null  name: string | null  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 } = {}): 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),    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: 21900 with EUR is €219.00. price formats them.
  • Carts are never cached. Product details come with the CMS page instead.
  • The types hold only the fields this guide uses. The storefront API lists them all.

3Build the cart actions

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

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. The token stays in an httpOnly cookie.
  • A cart that is gone (404) or already ordered (409) is replaced by a new one.
  • 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.

4Draw the Commerce Orbit blocks

CMS Orbit delivers each picked product with its live price, stock and variants, so the blocks need no call of their own. The variant ids are the ones the storefront API takes, so one form puts any of them in the cart:

components/blocks/add-to-cart-form.tsxTypeScript
import { commercePrice, type CmsCommerceProduct } from '@bifrost-orbit-cms/sdk'import { addToCart } from '@/app/cart/actions'export function AddToCartForm({ product, label }: { product: CmsCommerceProduct; label?: string }) {  const buyable = product.variants.filter((variant) => variant.available && variant.price !== null)  if (!product.inStock || buyable.length === 0) return <p>Sold out</p>  return (    <form action={addToCart}>      {buyable.length > 1 ? (        <label>          Choose          <select name="variantId">            {buyable.map((variant) => (              <option key={variant.id} value={variant.id}>                {variant.title}, {commercePrice({ price: variant.price, priceMax: variant.price, currency: product.currency })}              </option>            ))}          </select>        </label>      ) : (        <input type="hidden" name="variantId" value={buyable[0].id} />      )}      <button type="submit">{label || 'Add to cart'}</button>    </form>  )}
components/blocks/product-grid.tsxTypeScript
import { commercePrice, type CmsCommerceProduct } from '@bifrost-orbit-cms/sdk'import type { BlockProps } from '@bifrost-orbit-cms/sdk/react'import { AddToCartForm } from './add-to-cart-form'export function ProductGrid({ block }: BlockProps<'commerceProductGrid'>) {  const { items = [] } = block as { items?: CmsCommerceProduct[] }  const products = items.filter((product) => product.available)  if (products.length === 0) return null  return (    <section data-cms-id={block.id}>      {block.heading ? <h2>{block.heading}</h2> : null}      {block.intro ? <p>{block.intro}</p> : null}      <ul className="products">        {products.map((product) => (          <li key={product.id}>            {product.image ? <img src={product.image.url} alt={product.image.alt ?? ''} width={320} height={320} /> : null}            <h3>{product.name}</h3>            <p>{commercePrice(product)}</p>            <AddToCartForm product={product} />          </li>        ))}      </ul>    </section>  )}
components/blocks/product-card.tsxTypeScript
import { commercePrice } from '@bifrost-orbit-cms/sdk'import type { BlockProps } from '@bifrost-orbit-cms/sdk/react'import { AddToCartForm } from './add-to-cart-form'export function ProductCard({ block }: BlockProps<'commerceProductCard'>) {  const product = block.product  if (!product?.available) return null  return (    <article data-cms-id={block.id}>      {product.image ? <img src={product.image.url} alt={product.image.alt ?? ''} width={480} height={480} /> : null}      <h2>{block.heading || product.name}</h2>      <p>{product.summary}</p>      <p>{commercePrice(product)}</p>      <AddToCartForm product={product} label={block.buttonLabel} />    </article>  )}
components/blocks/add-to-cart.tsxTypeScript
import type { BlockProps } from '@bifrost-orbit-cms/sdk/react'import { AddToCartForm } from './add-to-cart-form'export function AddToCart({ block }: BlockProps<'commerceAddToCart'>) {  if (!block.product?.available) return null  return (    <div data-cms-id={block.id}>      <AddToCartForm product={block.product} label={block.label} />    </div>  )}
  • available: false means the product is not on sale, or Commerce Orbit could not be reached. The blocks then draw nothing.
  • inStock: false means nothing can be bought now, and the form says "Sold out".
  • items is the grid's products: the ones the editor picked, or the picked collection's when none are picked, up to the block's limit. It is not in the generated types, so read it as shown.
  • commercePrice formats the price, as a range when variants cost different amounts.

Register the blocks. Add them to cms/registry.tsx next to your own components:

cms/registry.tsxTypeScript
import '@/cms/types'import type { CmsRegistry } from '@bifrost-orbit-cms/sdk/react'import { AddToCart } from '@/components/blocks/add-to-cart'import { ProductCard } from '@/components/blocks/product-card'import { ProductGrid } from '@/components/blocks/product-grid'export const registry: CmsRegistry = {  commerceProductGrid: ProductGrid,  commerceProductCard: ProductCard,  commerceAddToCart: AddToCart,}

Check it: run npm run dev and open the page with the blocks. Each product shows its photo, name, price and an Add to cart button, with a choice of size for a product such as the Fjell GTX boot. A sold-out product, such as the Arctic 3 tent when none are left, says "Sold out".

5Show the cart

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="/gear">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, delivery and VAT, so the cart's prices can differ from those on the page.
  • problems lists what stops checkout, such as "Choose how you'd like it delivered". Show them as they are.
  • "See the gear" links to /gear. Point it at a page of your own.

Add 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>  )}

This guide was tested without the preview steps of the CMS Orbit quickstart. If you added CmsBridge to the layout in step 7, keep it in the body.

Check it: select Add to cart on a product. 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.
  • 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. 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.
  • 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/NW1016?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.

Keep prices and stock fresh

The page route keeps each CMS page for up to 60 seconds. When a product's price, stock or availability changes in Commerce Orbit, CMS Orbit sends content.published for every live page that shows it, so the revalidate route from step 8 of the CMS Orbit quickstart refreshes those pages straight away. The cart takes its prices and stock from Commerce Orbit itself, never from the page.

Next steps

Was this page helpful?

Read next