🔥 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)
CMS & Integrations••By Komal Nakrani

Astro Snipcart Setup: Add a Cart to a Static Astro Site

Add Snipcart to Astro: load the cart script, define products in a Content Collection, render buy buttons with data attributes, and pass Snipcart's price check.

#Astro#Astro Snipcart#Snipcart#E-commerce#Static Sites

To use Snipcart with Astro, load Snipcart’s script and stylesheet in your base layout with your public API key, then mark up each product as a button with the snipcart-add-item class and data-item-* attributes (id, name, price, url). Snipcart adds the cart drawer and checkout on top of your static pages, and it re-reads the product page at data-item-url to confirm the price before charging.

That makes the Astro Snipcart combination one of the simplest ways to sell from a fully static site: no adapter, no server, no database. This guide sets it up with products in a Content Collection so price changes happen in one place.

Key Takeaways

  • Snipcart is a script plus HTML attributes. Astro’s static output works with it unchanged.
  • Add the Snipcart tags with is:inline so Astro does not try to bundle the external script.
  • Keep products in a Content Collection and render buttons from it, so the price in the button and on the page always match.
  • Snipcart’s crawler fetches data-item-url and checks the price. The URL must be public and the button must appear in its HTML.
  • Use the test API key until the whole flow works, then switch to live.

How Snipcart works on an Astro site

Snipcart runs entirely in the browser. When a visitor clicks a button with the snipcart-add-item class, Snipcart reads the button’s data attributes and adds the item to a cart it stores for that visitor. Checkout happens in Snipcart’s overlay, with payments through the gateway you connect in the Snipcart dashboard.

To stop someone editing a price in their browser, Snipcart validates every order. It fetches the page at data-item-url, finds a button with the same data-item-id, and compares the price. If they differ, the order fails. This is why the product definition must live in your pages, and why static Astro output fits well: the HTML the crawler gets is exactly what you built.

Load Snipcart in your base layout

Get your public API key from the Snipcart dashboard (test and live keys are separate). Expose it through astro:env so it is declared and type-checked:

// astro.config.mjs
import { defineConfig, envField } from 'astro/config';

export default defineConfig({
  site: 'https://www.example-shop.com',
  env: {
    schema: {
      PUBLIC_SNIPCART_API_KEY: envField.string({ context: 'client', access: 'public' }),
    },
  },
});
# .env
PUBLIC_SNIPCART_API_KEY=your-test-public-api-key

Then add Snipcart to the layout. Use the version shown in Snipcart’s current installation docs; the paths below follow the v3 pattern.

---
// src/layouts/ShopLayout.astro
import { PUBLIC_SNIPCART_API_KEY } from 'astro:env/client';
const { title } = Astro.props;
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{title}</title>
    <link rel="preconnect" href="https://app.snipcart.com" />
    <link rel="preconnect" href="https://cdn.snipcart.com" />
    <link rel="stylesheet" href="https://cdn.snipcart.com/themes/v3.2.1/default/snipcart.css" />
  </head>
  <body>
    <header>
      <a href="/">Shop</a>
      <button class="snipcart-checkout" type="button">
        Cart (<span class="snipcart-items-count">0</span>)
      </button>
    </header>
    <slot />
    <script is:inline async src="https://cdn.snipcart.com/themes/v3.2.1/default/snipcart.js"></script>
    <div hidden id="snipcart" data-api-key={PUBLIC_SNIPCART_API_KEY}></div>
  </body>
</html>

is:inline tells Astro to leave the script tag exactly as written. Without it, Astro processes <script> tags as modules for bundling, which is not what you want for a third-party script. The Astro script tag guide explains the difference.

The snipcart-checkout class opens the cart, and snipcart-items-count is filled in by Snipcart with the current item count.

Define products in a Content Collection

Store products as data, not as hard-coded buttons. A Content Collection with a schema catches a missing price at build time.

// 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(),
      price: z.number().positive(),
      description: z.string().max(200),
      image: image(),
      sizes: z.array(z.string()).optional(),
      weight: z.number().int().positive().optional(), // grams, for shipping rates
    }),
});

export const collections = { products };
---
# src/content/products/linen-tote.md
name: "Linen Tote Bag"
price: 34
description: "Heavyweight natural linen tote with an inside pocket."
image: "./linen-tote.jpg"
sizes: ["Standard", "Large"]
weight: 300
---
Woven from undyed European linen and stitched in small batches.

Render the buy button

One component turns a product entry into a Snipcart button. Snipcart reads only the attributes, so the button can look however your design needs.

---
// src/components/BuyButton.astro
import type { CollectionEntry } from 'astro:content';

interface Props {
  product: CollectionEntry<'products'>;
}
const { product } = Astro.props;
const { name, price, description, image, sizes, weight } = product.data;
const url = new URL(`/products/${product.id}/`, Astro.site).href;
---
<button
  type="button"
  class="snipcart-add-item"
  data-item-id={product.id}
  data-item-name={name}
  data-item-price={price.toFixed(2)}
  data-item-url={url}
  data-item-description={description}
  data-item-image={new URL(image.src, Astro.site).href}
  data-item-weight={weight}
  data-item-custom1-name={sizes ? 'Size' : undefined}
  data-item-custom1-options={sizes?.join('|')}
>
  Add to cart, ${price.toFixed(2)}
</button>

Astro omits attributes whose value is undefined, so products without sizes or weight produce a clean button.

Product pages that pass Snipcart’s price check

Each product needs a public page that contains its button, because that page is what Snipcart crawls.

---
// src/pages/products/[id].astro
import { getCollection, render } from 'astro:content';
import { Image } from 'astro:assets';
import ShopLayout from '../../layouts/ShopLayout.astro';
import BuyButton from '../../components/BuyButton.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);
---
<ShopLayout title={product.data.name}>
  <Image src={product.data.image} alt={product.data.name} width={800} />
  <h1>{product.data.name}</h1>
  <Content />
  <BuyButton product={product} />
</ShopLayout>

You can also show BuyButton on a listing page. The validation still works, because data-item-url points at the product page, which always has the button.

Common causes of “price mismatch” or “product not found” errors:

  • site in astro.config.mjs does not match the deployed domain, so data-item-url points somewhere else.
  • The page is behind a password or preview protection the crawler cannot pass.
  • You changed a price but did not redeploy, so the live page still shows the old one.
  • A trailing slash difference causes a redirect that the crawler does not follow as expected. Keep URLs consistent, as described in the trailing slash tip.

Test, then go live

  1. Run npm run build && npm run preview and click through: add to cart, change size, open the cart.
  2. Deploy to a public URL with the test key, because the crawler cannot reach localhost.
  3. In the Snipcart dashboard, add the deployed domain under allowed domains.
  4. Place a test order with the gateway’s test card.
  5. Replace PUBLIC_SNIPCART_API_KEY with the live key in your host’s environment settings and redeploy.

The deploy guide for Astro covers setting environment variables on each major host.

When Snipcart is the right choice

Snipcart suits small to mid-sized catalogues where the site is mostly content: makers, studios, publishers, event tickets, digital downloads. You keep a static site and avoid running a commerce back end.

For large catalogues with complex inventory, a headless platform fits better; see the Astro Shopify Storefront guide. For one or two products or a simple payment link, Stripe Checkout on Astro is lighter still. If you need a designed shop front to start from, browse Astro themes for retail and e-commerce.

FAQ

Does Snipcart work with static Astro sites?

Yes. Snipcart only needs HTML buttons with data attributes and its script. A fully static Astro build with no adapter works, as long as product pages are publicly reachable for price validation.

Why does Snipcart say the product price does not match?

Snipcart compares the button price with the price on the page at data-item-url. A mismatch usually means the live site has not been redeployed, site points to a different domain, or the URL redirects.

Can I use Snipcart with Astro Content Collections?

Yes. Define products in a collection with a Zod schema, then render the snipcart-add-item button from each entry. Prices then live in one file per product.

Do I need is:inline for the Snipcart script?

Yes, use is:inline for the external Snipcart script. It keeps Astro from processing the tag, so it loads exactly as Snipcart’s docs describe.

How do I add product options like size in Snipcart?

Use custom fields: data-item-custom1-name="Size" and data-item-custom1-options="Small|Medium|Large". Snipcart shows them in the cart and includes them in the order.