🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Astro Themes••By Komal Nakrani

Astro Ecommerce Tutorial: Build an Online Store

An Astro ecommerce tutorial: product collection, product pages, a lightweight cart, Stripe Checkout through an Astro Action, Product schema and the right architecture.

#Astro#Ecommerce#Stripe#Tutorial

This Astro ecommerce tutorial builds a small online store the fast way: products in a typed Content Collection, static product and category pages, a cart kept in the browser with a tiny shared store, and payment handled by Stripe Checkout through a single on-demand Astro Action. Catalog pages stay static HTML, so they load instantly, and the only server code is the one endpoint that creates a checkout session.

Key Takeaways

  • Keep the catalog static and send payment to a hosted checkout (Stripe Checkout, Shopify, Snipcart, Lemon Squeezy); never build card handling yourself.
  • Products live in a Content Collection with a schema for price, images, variants and stock status.
  • The cart can be a few lines of script plus localStorage, or a Nano Store shared between islands.
  • One Astro Action, on an on-demand route with an adapter, creates the checkout session server-side so prices can’t be tampered with.
  • For large catalogs or live inventory, use a headless commerce platform as the source of truth.

Choose the architecture first

There are three common ways to run a store on Astro. Pick one before writing code.

Approach Catalog Cart and checkout Best for
Static catalog + hosted checkout Content Collection in the repo Stripe Checkout or Payment Links Small shops, a few to a few hundred products
Headless commerce Shopify, BigCommerce or similar, loaded at build time Platform’s cart and checkout Larger catalogs, inventory, staff using an admin
Drop-in cart Static pages with buy buttons Snipcart, Shopify Buy Button, Lemon Squeezy Fastest setup, minimal code

This tutorial uses the first approach because it teaches every piece. The product pages and cart work the same way with the other two; only the data source and the checkout call change.

npm create astro@latest small-batch -- --template minimal
cd small-batch
npx astro add tailwind node
npm install stripe nanostores

The Node adapter is needed for the one on-demand checkout action. If you deploy to Cloudflare, Netlify or Vercel, add that adapter instead.

Define the product collection

// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const products = defineCollection({
  loader: glob({ pattern: '**/*.md', base: './src/content/products' }),
  schema: ({ image }) =>
    z.object({
      name: z.string(),
      priceId: z.string().startsWith('price_'), // Stripe Price ID
      price: z.number().positive(), // display price in dollars
      category: z.enum(['mugs', 'bowls', 'plates']),
      images: z.array(image()).min(1),
      inStock: z.boolean().default(true),
      featured: z.boolean().default(false),
    }),
});

export const collections = { products };
---
# src/content/products/speckled-mug.md
name: Speckled stoneware mug
priceId: price_1QExampleMug
price: 28
category: mugs
images:
  - ./images/speckled-mug-1.jpg
  - ./images/speckled-mug-2.jpg
inStock: true
featured: true
---

Wheel-thrown in small batches. Holds 350 ml. Dishwasher safe.

The real price lives in Stripe as a Price object; price here is only for display. The checkout action uses priceId, so a visitor editing the page can’t change what they pay. The Content Collections guide covers schemas and image fields.

Product and category pages

Product pages are prerendered from the collection. Because the project now has an adapter, mark static pages explicitly if your output mode is server; with the default static output they are prerendered automatically.

---
// src/pages/products/[id].astro
import { getCollection, render } from 'astro:content';
import { Image } from 'astro:assets';
import Base from '../../layouts/Base.astro';

export async function getStaticPaths() {
  const products = await getCollection('products');
  return products.map((product) => ({ params: { id: product.id }, props: { product } }));
}

const { product } = Astro.props;
const { Content } = await render(product);
const { name, price, images, inStock, priceId } = product.data;
const money = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });

const schema = {
  '@context': 'https://schema.org',
  '@type': 'Product',
  name,
  image: images.map((img) => new URL(img.src, Astro.site).toString()),
  offers: {
    '@type': 'Offer',
    price: price.toFixed(2),
    priceCurrency: 'USD',
    availability: inStock ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock',
    url: new URL(`/products/${product.id}/`, Astro.site).toString(),
  },
};
---
<Base title={`${name} | Small Batch`} description={`${name}, ${money.format(price)}. Handmade stoneware, shipped in 3 days.`}>
  <script type="application/ld+json" set:html={JSON.stringify(schema)} />
  <div class="grid gap-10 md:grid-cols-2">
    <Image src={images[0]} alt={name} widths={[480, 800, 1200]} sizes="(min-width: 768px) 50vw, 100vw" loading="eager" fetchpriority="high" />
    <div>
      <h1 class="text-3xl font-bold">{name}</h1>
      <p class="mt-2 text-2xl">{money.format(price)}</p>
      <Content />
      <button
        type="button"
        class="add-to-cart mt-6 rounded-lg bg-zinc-900 px-6 py-3 text-white disabled:opacity-50"
        data-id={product.id}
        data-name={name}
        data-price={price}
        data-price-id={priceId}
        disabled={!inStock}
      >
        {inStock ? 'Add to cart' : 'Sold out'}
      </button>
    </div>
  </div>
</Base>

Category pages filter the same collection, for example getCollection('products', ({ data }) => data.category === 'mugs') inside a [category].astro route.

A lightweight cart

The cart only needs to store line items in the browser and show a count in the header. A Nano Store with localStorage persistence does that in a few lines and works from plain scripts or framework islands.

// src/stores/cart.ts
import { atom } from 'nanostores';

export type Line = { id: string; name: string; price: number; priceId: string; qty: number };

const saved = typeof localStorage !== 'undefined' ? localStorage.getItem('cart') : null;
export const cart = atom<Line[]>(saved ? JSON.parse(saved) : []);

cart.subscribe((lines) => {
  if (typeof localStorage !== 'undefined') localStorage.setItem('cart', JSON.stringify(lines));
});

export function addToCart(item: Omit<Line, 'qty'>) {
  const lines = cart.get();
  const existing = lines.find((l) => l.id === item.id);
  cart.set(existing
    ? lines.map((l) => (l.id === item.id ? { ...l, qty: l.qty + 1 } : l))
    : [...lines, { ...item, qty: 1 }]);
}

Wire the button and header count with a component script:

---
// src/components/CartCount.astro
---
<a href="/cart/" class="cart-link">Cart (<span id="cart-count">0</span>)</a>

<script>
  import { cart, addToCart } from '../stores/cart';

  const count = document.getElementById('cart-count')!;
  cart.subscribe((lines) => {
    count.textContent = String(lines.reduce((n, l) => n + l.qty, 0));
  });

  document.querySelectorAll<HTMLButtonElement>('.add-to-cart').forEach((btn) => {
    btn.addEventListener('click', () => {
      const { id, name, price, priceId } = btn.dataset;
      addToCart({ id: id!, name: name!, price: Number(price), priceId: priceId! });
    });
  });
</script>

If you later build a cart drawer as a React or Svelte island, it can read the same store with @nanostores/react or Svelte’s store syntax.

Create the checkout with an Astro Action

The server creates a Stripe Checkout Session from price IDs and quantities, then returns its URL. Prices come from Stripe, not from the browser.

// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';
import Stripe from 'stripe';

const stripe = new Stripe(import.meta.env.STRIPE_SECRET_KEY);

export const server = {
  checkout: defineAction({
    input: z.object({
      lines: z.array(z.object({ priceId: z.string().startsWith('price_'), qty: z.number().int().min(1).max(20) })).min(1),
    }),
    handler: async ({ lines }, context) => {
      const origin = context.url.origin;
      const session = await stripe.checkout.sessions.create({
        mode: 'payment',
        line_items: lines.map((l) => ({ price: l.priceId, quantity: l.qty })),
        shipping_address_collection: { allowed_countries: ['US', 'CA'] },
        success_url: `${origin}/thanks/?session_id={CHECKOUT_SESSION_ID}`,
        cancel_url: `${origin}/cart/`,
      });
      if (!session.url) throw new ActionError({ code: 'INTERNAL_SERVER_ERROR', message: 'No checkout URL' });
      return { url: session.url };
    },
  }),
};

Call it from the cart page:

---
// src/pages/cart.astro
import Base from '../layouts/Base.astro';
---
<Base title="Your cart | Small Batch" description="Review the items in your cart and check out securely with Stripe.">
  <h1>Your cart</h1>
  <ul id="lines"></ul>
  <button id="checkout" type="button">Check out</button>
</Base>

<script>
  import { actions } from 'astro:actions';
  import { cart } from '../stores/cart';

  const list = document.getElementById('lines')!;
  cart.subscribe((lines) => {
    list.replaceChildren(...lines.map((l) => {
      const li = document.createElement('li');
      li.textContent = `${l.qty} × ${l.name}`;
      return li;
    }));
  });

  document.getElementById('checkout')!.addEventListener('click', async () => {
    const lines = cart.get().map(({ priceId, qty }) => ({ priceId, qty }));
    const { data, error } = await actions.checkout({ lines });
    if (error) return alert('Checkout is unavailable, please try again.');
    window.location.href = data.url;
  });
</script>

Actions run on demand, which is why the project needs an adapter; every other page is still prerendered. Use Stripe webhooks (an API endpoint that verifies the signature) to record orders and send fulfilment emails, rather than trusting the success page. The Astro Actions docs cover input validation and errors.

Store SEO and performance

  • Every product page has a unique title, description and Product structured data with price and availability, as shown above.
  • Product photos go through <Image />; only the main image loads eagerly.
  • Category pages get real intro copy, not just a grid.
  • Generate a sitemap with @astrojs/sitemap, and exclude /cart/ and /thanks/.

The Astro SEO guide covers canonical URLs and sitemaps, and the Astro image cheatsheet lists every <Image /> option.

When to move to headless commerce

The static approach works well until you need inventory tracking across channels, discount rules, tax handling in many regions, or staff managing products in an admin. At that point, make a commerce platform the source of truth. Load products at build time with a Content Collection loader (or render product pages on demand if stock changes constantly), and send shoppers to the platform’s cart and checkout. Your Astro pages, components and styles stay the same. The headless CMS guide explains loaders for external data.

Using a store template

If you want a finished storefront design to wire up, Komal Nakrani’s retail and e-commerce category holds shop themes for fashion, accessories, home goods and more. One example is Toonhub, a collectibles storefront organised by numbered drops with a product page per figure. Like all Komal themes, these are static Astro sites with no server or payment layer included, so you connect Stripe, Snipcart or a commerce platform yourself as shown above. Free alternatives include community store starters on astro.build/themes.

FAQ

Can you build an ecommerce site with Astro?

Yes. Astro handles the storefront (catalog, product pages, content and SEO) as fast static HTML, and you add checkout through a hosted service such as Stripe Checkout, Shopify, Snipcart or Lemon Squeezy. For dynamic needs like order handling, Astro Actions and API endpoints run on demand with an adapter.

Does an Astro store need a server?

Only for the parts that must run securely, such as creating a checkout session or receiving payment webhooks. Those run as on-demand routes with an adapter, while product pages stay prerendered. With a drop-in cart like Snipcart or Payment Links, you can run a store with no server code at all.

Is Astro good for Shopify?

Astro works well as a headless Shopify storefront. Load products from the Shopify Storefront API at build time or on demand, render fast product pages in Astro, and hand the cart to Shopify’s checkout. You keep Shopify’s admin, inventory and payments.

How do I add a cart to a static Astro site?

Store cart lines in the browser with a small Nano Store persisted to localStorage, update a header count with a component script, and send the lines to a checkout action or service when the shopper is ready. No framework is required.

How many products can an Astro store handle?

A static Astro build handles hundreds to thousands of product pages comfortably, though build time grows with page and image count. For very large catalogs or stock that changes constantly, render product pages on demand from a commerce API instead of prebuilding them.