Skip to content

Astro storefront quickstart

An Astro shop for Northwilds, rendered on the server, with a product list, product pages, a cart and checkout through the storefront API and Stripe's Payment Element.

Tutorial11 min read

In about 20 minutes you build an Astro shop for Northwilds that reads its products from Commerce Orbit. Pages render on your server, forms post back to them, and the only browser JavaScript is Stripe's Payment Element on the payment step. Payment goes straight to the shop's own Stripe account.

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

Tested with: Astro 7.4.7, @astrojs/node 11.1.11, @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, in test mode while you build, so the test card 4242 4242 4242 4242 pays without charging anyone.
  • Node.js 22.23.4 or later, which Astro 7 needs.

You don't need an API key or Stripe keys of your own.

1Create the project

Shell
npm create astro@latest northwilds-shop -- --template withastro/astro/examples/minimal --install --no-git --yescd northwilds-shopnpx astro add node --yesnpm install @stripe/stripe-js

Render every page on the server, since prices, stock and the cart change all the time. Replace astro.config.mjs:

astro.config.mjsJavaScript
// @ts-checkimport { defineConfig } from 'astro/config'import node from '@astrojs/node'export default defineConfig({  output: 'server',  adapter: node({ mode: 'standalone' }),})

Add the storefront address of your shop:

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

Without a PUBLIC_ prefix, Astro keeps the setting on the server.

2Add the shop helper

src/lib/shop.tsTypeScript
import type { AstroCookies } from 'astro'const base = import.meta.env.SHOP_API_URLexport interface Product {  id: string  slug: string  title: string  description: string  images: { url: string; alt: string }[]  price: { min: number | null; currency: string }  available: boolean  variants: { id: string; title: string; price: number | null; available: boolean }[]  seo: { title: string; description: string }}export 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; total: number; problem: string | null }[]  shippingChoices: { kind: 'rate' | 'pickup'; id: string; name: string; price: number }[]  shipping: { kind: 'rate' | 'pickup'; rateId?: string; locationId?: string } | null  totals: { subtotal: number; discountTotal: number; shippingTotal: number; total: number } | null  problems: string[]}export class ShopError extends Error {  constructor(message: string, readonly status: number) {    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),  })  const json = await response.json()  if (!response.ok) throw new ShopError(json.error?.message ?? `The shop answered ${response.status}`, response.status)  return json.data as T}export const price = (amount: number | null, currency: string) =>  amount === null ? '' : new Intl.NumberFormat('en-GB', { style: 'currency', currency }).format(amount / 100)export async function readCart(cookies: AstroCookies): Promise<Cart | null> {  const token = cookies.get('cart')?.value  return token ? shop<Cart>(`/carts/${token}`).catch(() => null) : null}export async function changeCart(cookies: AstroCookies, change: Record<string, unknown>): Promise<Cart> {  const token = cookies.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 cart = await shop<Cart>('/carts', { body: change })  cookies.set('cart', cart.token, { path: '/', httpOnly: true, sameSite: 'lax', secure: import.meta.env.PROD, maxAge: 60 * 60 * 24 * 30 })  return cart}
  • shop calls the storefront API, unwraps data and turns an error into a ShopError with the status.
  • Amounts are whole minor units: 3500 with EUR is €35.00. price formats them.
  • changeCart starts a cart with POST/carts the first time, and changes it with PATCH/carts/{token} after that. A cart that is gone (404) or already ordered (409) is replaced by a new one.
  • The types hold only the fields this guide uses. The storefront API lists them all.

3Add a layout and list the products

Astro
---// src/layouts/Shop.astroconst { title = 'Northwilds', description } = Astro.props---<html lang="en">  <head>    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width" />    <title>{title}</title>    {description ? <meta name="description" content={description} /> : null}  </head>  <body>    <header><a href="/">Northwilds</a> <a href="/cart">Cart</a></header>    <main><slot /></main>  </body></html>

Replace src/pages/index.astro:

Astro
---// src/pages/index.astroimport Shop from '../layouts/Shop.astro'import { price, shop, type Product } from '../lib/shop'const products = await shop<Product[]>('/products?limit=24')Astro.response.headers.set('Cache-Control', 'public, max-age=30')---<Shop title="Gear">  <h1>Gear</h1>  <ul>    {products.map((product) => (      <li>        <a 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>        </a>        <p>{product.available ? price(product.price.min, product.price.currency) : 'Sold out'}</p>      </li>    ))}  </ul></Shop>

Cache-Control lets a CDN in front of your server keep the list for 30 seconds, the same time the storefront API allows.

Check it: run npm run dev and open http://localhost:4321. You see the shop's active products with their photos and prices, such as the Glacier 750 flask at €35.00.

4Show a product and add it to the cart

Astro
---// src/pages/products/[slug].astroimport Shop from '../../layouts/Shop.astro'import { changeCart, price, shop, ShopError, type Product } from '../../lib/shop'if (Astro.request.method === 'POST') {  const form = await Astro.request.formData()  await changeCart(Astro.cookies, { add: [{ variantId: String(form.get('variantId')), quantity: 1 }] })  return Astro.redirect('/cart', 303)}let product: Producttry {  product = await shop<Product>(`/products/${encodeURIComponent(Astro.params.slug!)}`)} catch (error) {  if (error instanceof ShopError && error.status === 404) return new Response(null, { status: 404 })  throw error}const buyable = product.variants.filter((variant) => variant.available && variant.price !== null)---<Shop title={product.seo.title} description={product.seo.description}>  {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 set:html={product.description} />  {buyable.length ? (    <form method="post">      {buyable.length > 1 ? (        <label>          Choose          <select name="variantId">            {buyable.map((variant) => <option 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>  )}</Shop>
  • A GET shows the product. An address that doesn't exist answers 404.
  • A POST from the form adds the chosen variant to the cart and sends the shopper to it.
  • seo is filled from the title and summary when the shop left it empty.
  • Variants without a price in the shop's currency, or with nothing left, are left out of the choice.

5Build the cart and take payment

The cart page handles two forms: the shopper's details and delivery, and the start of payment.

Astro
---// src/pages/cart.astroimport Shop from '../layouts/Shop.astro'import { changeCart, price, readCart, shop, ShopError } from '../lib/shop'let payment: { clientSecret: string; publishableKey: string; returnUrl: string } | null = nulllet message = ''if (Astro.request.method === 'POST') {  const form = await Astro.request.formData()  const text = (name: string) => String(form.get(name) ?? '').trim()  if (text('step') === 'details') {    const [kind, id] = text('shipping').split(':')    await changeCart(Astro.cookies, {      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 } } : {}),    })    return Astro.redirect('/cart', 303)  }  const token = Astro.cookies.get('cart')?.value  try {    const order = await shop<{ reference: string; payment: { clientSecret: string; publishableKey: string } | null }>(`/carts/${token}/checkout`, { body: { method: 'card' } })    const cart = await shop<{ email: string }>(`/carts/${token}`)    const orderPage = new URL(`/orders/${order.reference}?email=${encodeURIComponent(cart.email)}`, Astro.url).toString()    if (!order.payment) return Astro.redirect(orderPage, 303)    payment = { ...order.payment, returnUrl: orderPage }  } catch (error) {    message = error instanceof ShopError ? error.message : 'Something went wrong. Try again.'  }}const cart = await readCart(Astro.cookies)const address = cart?.shippingAddressconst chosen = cart?.shipping ? `${cart.shipping.kind}:${cart.shipping.rateId ?? cart.shipping.locationId}` : ''---<Shop title="Your cart">  {!cart || cart.count === 0 ? (    <>      <h1>Your cart is empty</h1>      <a href="/">See the gear</a>    </>  ) : (    <>      <h1>Your cart</h1>      <ul>        {cart.lines.map((line) => (          <li>            {line.quantity} × {line.title}{line.variantTitle ? ` (${line.variantTitle})` : ''}: {price(line.total, cart.currency)}            {line.problem ? <strong> {line.problem}</strong> : null}          </li>        ))}      </ul>      <form method="post">        <input type="hidden" name="step" value="details" />        <input name="email" type="email" placeholder="Email" value={cart.email ?? ''} required />        <input name="name" placeholder="Full name" value={cart.name ?? ''} required />        <input name="line1" placeholder="Address" value={address?.line1 ?? ''} required />        <input name="postalCode" placeholder="Postcode" value={address?.postalCode ?? ''} required />        <input name="city" placeholder="Town or city" value={address?.city ?? ''} required />        <input name="country" placeholder="Country, such as NO" maxlength="2" value={address?.country ?? cart.country ?? 'NO'} required />        {cart.shippingChoices.length ? (          <fieldset>            <legend>Delivery</legend>            {cart.shippingChoices.map((choice) => (              <label>                <input type="radio" name="shipping" value={`${choice.kind}:${choice.id}`} checked={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>{problem}</li>)}</ul>      ) : payment ? (        <div id="payment" data-key={payment.publishableKey} data-secret={payment.clientSecret} data-return={payment.returnUrl}>          <div id="payment-element"></div>          <button type="button" id="pay">Pay now</button>          <p id="payment-message" role="alert"></p>        </div>      ) : (        <form method="post">          <input type="hidden" name="step" value="pay" />          {message ? <p role="alert">{message}</p> : null}          <button type="submit">Continue to payment</button>        </form>      )}    </>  )}</Shop><script>  import { loadStripe } from '@stripe/stripe-js'  const box = document.getElementById('payment')  if (box) {    const { key, secret, return: returnUrl } = box.dataset    const stripe = await loadStripe(key!)    if (stripe) {      const elements = stripe.elements({ clientSecret: secret! })      elements.create('payment').mount('#payment-element')      document.getElementById('pay')!.addEventListener('click', async () => {        const { error } = await stripe.confirmPayment({ elements, confirmParams: { return_url: returnUrl! } })        if (error) document.getElementById('payment-message')!.textContent = error.message ?? 'The payment did not go through.'      })    }  }</script>
  • shippingChoices come from the shop's shipping zones for the country, such as Standard delivery 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.
  • problems lists what stops checkout, such as "Choose how you'd like it delivered". Show them as they are.
  • Continue to payment calls POST/carts/{token}/checkout, which creates the order and a Stripe PaymentIntent for exactly its total. The page then shows the Payment Element with the shop's publishable key and the client secret. Calling checkout again before paying cancels the earlier unpaid order.
  • return_url is your order page. Stripe sends the shopper there after paying, also after 3D Secure or a bank's own page.

Check it: add a product, fill in the address with country NO, select Save, pick a delivery and select Save again. Select Continue to payment, choose Card, enter 4242 4242 4242 4242, any future expiry date and any CVC, and select Pay now.

6Show the order

Astro
---// src/pages/orders/[reference].astroimport Shop from '../../layouts/Shop.astro'import { price, shop, ShopError } from '../../lib/shop'type Order = {  reference: string  paymentStatus: 'pending' | 'paid' | 'failed' | 'invoiced' | 'partiallyRefunded' | 'refunded'  currency: string  lines: { title: string; quantity: number; total: number }[]  total: number}const email = Astro.url.searchParams.get('email') ?? ''let order: Ordertry {  order = await shop<Order>(`/orders/${encodeURIComponent(Astro.params.reference!)}?email=${encodeURIComponent(email)}`)} catch (error) {  if (error instanceof ShopError && error.status === 404) return new Response(null, { status: 404 })  throw error}if (order.paymentStatus === 'paid') Astro.cookies.delete('cart', { path: '/' })const heading = order.paymentStatus === 'paid' ? 'Thank you for your order' : order.paymentStatus === 'pending' ? 'We are confirming your payment' : 'Your order'---<Shop title={`Order ${order.reference}`}>  <h1>{heading}</h1>  <p>Order {order.reference}</p>  <ul>    {order.lines.map((line) => <li>{line.quantity} × {line.title}: {price(line.total, order.currency)}</li>)}  </ul>  <p>Total {price(order.total, order.currency)}</p></Shop>
  • The order needs the email it was placed with. Any other email answers 404.
  • pending right after paying means Stripe's message hasn't arrived yet. Commerce Orbit asks Stripe itself when you read the order, so a reload a few seconds later shows paid.
  • The cart cookie is removed once the order is paid, so the next visit starts a new cart.

Check it: after paying, you land on /orders/NW1015?email=… with the order's lines and its total. The order is in Orders in Commerce Orbit, marked as paid.

Next steps

Was this page helpful?

Read next