To build an Astro Shopify storefront, create a Storefront API access token with Shopify’s Headless channel, query products with GraphQL from your Astro pages at build time, generate one static page per product with getStaticPaths(), and create a cart with the cartCreate mutation that returns a Shopify checkoutUrl. Shopify handles payments, tax and orders; Astro handles fast, static product and content pages.
This guide builds that setup end to end with Astro 7: config, a small API client, the product listing, product pages and an add-to-cart button that sends shoppers to checkout.
Key Takeaways
- The Storefront API is GraphQL at
https://<store>.myshopify.com/api/<version>/graphql.jsonwith anX-Shopify-Storefront-Access-Tokenheader.- Fetch products at build time for static pages; rebuild with a webhook or deploy hook when products change.
cartCreatereturns acheckoutUrl. Redirect to it; you never build checkout yourself.- The public Storefront token is designed for browser use, so the cart button can call the API directly.
- For a few products, Shopify’s Buy Button embed is simpler than a full headless build.
How an Astro Shopify storefront works
A headless Shopify store splits the work. Shopify stays the commerce back end: products, inventory, prices, checkout, payments, orders and customer accounts. Astro becomes the front end, rendering product listings, product pages, collections and all the content around them.
At build time, Astro calls the Storefront API and writes static HTML for every product. In the browser, a small script creates a cart and redirects to Shopify’s hosted checkout. The result is a storefront that loads like a static site, with Shopify’s checkout and order system behind it.
If you are comparing this with Shopify’s own React framework, Astro vs Shopify Hydrogen covers the trade-offs.
Set up the Storefront API token
- In your Shopify admin, install the Headless sales channel.
- Create a storefront in it and copy the public access token.
- In the storefront’s API permissions, enable read access to products and write access to carts.
- Note your store domain, for example
your-store.myshopify.com.
Add the values to .env:
# .env
PUBLIC_SHOPIFY_DOMAIN=your-store.myshopify.com
PUBLIC_SHOPIFY_STOREFRONT_TOKEN=your-public-storefront-token
Declare them with astro:env so a missing value fails the build with a clear error:
// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
export default defineConfig({
site: 'https://shop.example.com',
image: { domains: ['cdn.shopify.com'] },
env: {
schema: {
PUBLIC_SHOPIFY_DOMAIN: envField.string({ context: 'client', access: 'public' }),
PUBLIC_SHOPIFY_STOREFRONT_TOKEN: envField.string({ context: 'client', access: 'public' }),
},
},
});
The image.domains entry lets Astro’s <Image /> component optimise product images served from Shopify’s CDN. The environment variables guide explains astro:env contexts in detail.
A small Storefront API client
One function handles every request. Shopify versions the API by quarter; use a current stable version from Shopify’s docs and update it a few times a year.
// src/lib/shopify.ts
import { PUBLIC_SHOPIFY_DOMAIN, PUBLIC_SHOPIFY_STOREFRONT_TOKEN } from 'astro:env/client';
const API_VERSION = '2026-10';
const endpoint = `https://${PUBLIC_SHOPIFY_DOMAIN}/api/${API_VERSION}/graphql.json`;
export async function shopify<T>(query: string, variables: Record<string, unknown> = {}): Promise<T> {
const res = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': PUBLIC_SHOPIFY_STOREFRONT_TOKEN,
},
body: JSON.stringify({ query, variables }),
});
const json = await res.json();
if (!res.ok || json.errors) {
throw new Error(`Shopify API error: ${JSON.stringify(json.errors ?? res.status)}`);
}
return json.data as T;
}
export interface Product {
handle: string;
title: string;
description: string;
featuredImage: { url: string; altText: string | null; width: number; height: number } | null;
priceRange: { minVariantPrice: { amount: string; currencyCode: string } };
variants: { nodes: { id: string; title: string; availableForSale: boolean }[] };
}
const PRODUCT_FIELDS = `
handle
title
description
featuredImage { url altText width height }
priceRange { minVariantPrice { amount currencyCode } }
variants(first: 20) { nodes { id title availableForSale } }
`;
export async function getProducts(first = 100) {
const data = await shopify<{ products: { nodes: Product[] } }>(
`query Products($first: Int!) { products(first: $first) { nodes { ${PRODUCT_FIELDS} } } }`,
{ first },
);
return data.products.nodes;
}
export function formatPrice({ amount, currencyCode }: { amount: string; currencyCode: string }) {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: currencyCode }).format(Number(amount));
}
For catalogues over 250 products, paginate with pageInfo { hasNextPage endCursor } and the after argument.
Build the product listing page
---
// src/pages/shop/index.astro
import { Image } from 'astro:assets';
import BaseLayout from '../../layouts/BaseLayout.astro';
import { getProducts, formatPrice } from '../../lib/shopify';
const products = await getProducts();
---
<BaseLayout title="Shop">
<h1>Shop</h1>
<ul class="grid">
{products.map((p) => (
<li>
<a href={`/shop/${p.handle}/`}>
{p.featuredImage && (
<Image
src={p.featuredImage.url}
alt={p.featuredImage.altText ?? p.title}
width={600}
height={Math.round((600 * p.featuredImage.height) / p.featuredImage.width)}
/>
)}
<h2>{p.title}</h2>
<p>{formatPrice(p.priceRange.minVariantPrice)}</p>
</a>
</li>
))}
</ul>
</BaseLayout>
Because this page is prerendered, the GraphQL request runs once during astro build, not on every visit.
Static product pages with getStaticPaths
---
// src/pages/shop/[handle].astro
import { Image } from 'astro:assets';
import BaseLayout from '../../layouts/BaseLayout.astro';
import AddToCart from '../../components/AddToCart.astro';
import { getProducts, formatPrice, type Product } from '../../lib/shopify';
export async function getStaticPaths() {
const products = await getProducts();
return products.map((product) => ({ params: { handle: product.handle }, props: { product } }));
}
const { product } = Astro.props as { product: Product };
---
<BaseLayout title={product.title}>
{product.featuredImage && (
<Image src={product.featuredImage.url} alt={product.featuredImage.altText ?? product.title} width={900} height={900} />
)}
<h1>{product.title}</h1>
<p>{formatPrice(product.priceRange.minVariantPrice)}</p>
<p>{product.description}</p>
<AddToCart variants={product.variants.nodes} />
</BaseLayout>
getStaticPaths() fetches the product list once and passes each product as props, so there is no second request per page. More on this pattern in the getStaticPaths guide.
Add to cart and send shoppers to checkout
The cart button runs in the browser. It calls cartCreate with the selected variant and redirects to the returned checkoutUrl. A plain <script> is enough; no framework island is needed.
---
// src/components/AddToCart.astro
interface Props {
variants: { id: string; title: string; availableForSale: boolean }[];
}
const { variants } = Astro.props;
---
<form class="add-to-cart">
{variants.length > 1 && (
<select name="variant">
{variants.map((v) => (
<option value={v.id} disabled={!v.availableForSale}>{v.title}</option>
))}
</select>
)}
{variants.length === 1 && <input type="hidden" name="variant" value={variants[0].id} />}
<button type="submit">Buy now</button>
</form>
<script>
import { shopify } from '../lib/shopify';
const CART_CREATE = `
mutation CartCreate($lines: [CartLineInput!]!) {
cartCreate(input: { lines: $lines }) {
cart { checkoutUrl }
userErrors { field message }
}
}`;
document.querySelectorAll<HTMLFormElement>('form.add-to-cart').forEach((form) => {
form.addEventListener('submit', async (event) => {
event.preventDefault();
const merchandiseId = new FormData(form).get('variant') as string;
const data = await shopify<{
cartCreate: { cart: { checkoutUrl: string } | null; userErrors: { message: string }[] };
}>(CART_CREATE, { lines: [{ merchandiseId, quantity: 1 }] });
if (data.cartCreate.cart) {
window.location.href = data.cartCreate.cart.checkoutUrl;
} else {
alert(data.cartCreate.userErrors.map((e) => e.message).join('\n'));
}
});
});
</script>
This is a “buy now” flow. For a persistent multi-item cart, store the cart ID in localStorage after the first cartCreate, then use cartLinesAdd with that ID and show the count in the header.
Keep the static store in sync
Static pages show prices and stock from the last build. Two ways to keep them current:
- Rebuild on change. Create a deploy hook in Cloudflare Pages, Netlify or Vercel, and point a Shopify webhook (product create, update, delete) or a Shopify Flow at it.
- Render volatile data on demand. Keep product pages static, but make price and availability a server island or an on-demand route with an adapter. The Astro server islands guide shows the pattern.
Checkout always uses live Shopify data, so a slightly stale page never charges the wrong price. Shopify recalculates at checkout.
Astro Shopify alternatives
- Shopify Buy Button: paste an embed for a handful of products. No API work, less control.
- Snipcart: cart and checkout in a script, products defined in your HTML. See Snipcart on an Astro site.
- Stripe Checkout: for simple catalogues without inventory management. See Stripe Checkout with Astro.
For the pages a store needs around the catalogue, use the e-commerce page checklist, and if you want a designed starting point, there are Astro themes for retail and e-commerce that you can wire to the client above.
FAQ
Can Astro work with Shopify?
Yes. Astro fetches products from the Shopify Storefront API, renders static product pages, and hands carts to Shopify’s hosted checkout. Shopify remains the back end for orders and payments.
Is the Shopify Storefront API token safe to expose?
The public Storefront access token is intended for client-side use and only grants the unauthenticated scopes you enable. Never expose an Admin API token or a private Storefront token in browser code.
Do I need SSR for an Astro Shopify store?
No. Product and collection pages can be fully static, with rebuilds triggered when products change. Add an adapter only if you need live prices, customer accounts or server-side logic on your own domain.
Does checkout happen on my Astro site?
No. The cart redirects to Shopify’s checkout via checkoutUrl. Shopify handles payment, tax, shipping and order confirmation.
Is Astro better than Shopify Hydrogen?
They suit different teams. Hydrogen is Shopify’s React-based framework with deep commerce primitives. Astro is lighter and content-first, shipping no JavaScript by default. Content-heavy stores with modest catalogues often fit Astro well.