To add Stripe Checkout to an Astro site, either paste Stripe Payment Links into your static pages (no server needed), or add an adapter and an on-demand endpoint that calls stripe.checkout.sessions.create() with your secret key and redirects the visitor to the returned session.url. Confirm paid orders with a webhook for checkout.session.completed, never with the success page alone.
Both routes keep card handling on Stripe’s hosted checkout page, so your Astro site never touches card numbers. This guide shows each, with Astro 7 code for the endpoint, environment variables and webhook.
Key Takeaways
- Payment Links are plain URLs. Use them for a fixed set of products on a fully static site.
- Checkout Sessions need a secret key, so they must run on the server:
export const prerender = falseplus an adapter.- Declare
STRIPE_SECRET_KEYwithastro:envascontext: 'server', access: 'secret'so it can never reach client code.- Redirect with status 303 to
session.url; Stripe hosts the payment form.- Fulfil orders in a webhook handler that verifies the signature from the raw request body.
Two ways to use Stripe with Astro
| Payment Links | Checkout Sessions | |
|---|---|---|
| Server needed | No | Yes (adapter, on-demand route) |
| Setup | Create link in Stripe dashboard, paste URL | Endpoint plus secret key |
| Dynamic prices or carts | No | Yes |
| Pass your own metadata | Limited | Full control |
| Best for | A few fixed products, donations, deposits | Carts, variable quantities, per-customer data |
If your shop sells a handful of fixed items, start with Payment Links and keep the site static. Move to Checkout Sessions when you need a cart, computed totals or to attach your own order data.
Option 1: Stripe Payment Links on a static site
Create a product and a Payment Link in the Stripe dashboard, then link to it. Nothing else is required.
---
// src/components/BuyLink.astro
interface Props {
href: string; // https://buy.stripe.com/...
label: string;
}
const { href, label } = Astro.props;
---
<a class="button" href={href} rel="noopener">{label}</a>
---
// src/pages/workshop.astro
import BaseLayout from '../layouts/BaseLayout.astro';
import BuyLink from '../components/BuyLink.astro';
---
<BaseLayout title="Print workshop">
<h1>Screen printing workshop</h1>
<BuyLink href="https://buy.stripe.com/test_XXXXXXXX" label="Book a seat" />
</BaseLayout>
You can set the after-payment redirect to a page on your site (for example /thanks/) in the Payment Link settings. The build stays fully static and deploys to any host.
Option 2: Checkout Sessions with an on-demand endpoint
For anything dynamic, your site has to call Stripe’s API with a secret key. That code must run on a server, so add an adapter for your host. With Cloudflare:
npx astro add cloudflare
npm install stripe
Keep the default static output. Only the checkout endpoint opts out of prerendering, so the rest of the site is still static HTML. The Astro adapters guide covers the choice of adapter per host.
Declare the secret key with astro:env
// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';
export default defineConfig({
site: 'https://www.example.com',
adapter: cloudflare(),
env: {
schema: {
STRIPE_SECRET_KEY: envField.string({ context: 'server', access: 'secret' }),
STRIPE_WEBHOOK_SECRET: envField.string({ context: 'server', access: 'secret' }),
},
},
});
# .env (never commit this file)
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxx
Importing from astro:env/server in client code fails the build, which is the protection you want for a key that can move money. More in the Astro environment variables guide.
The checkout endpoint
Keep prices in Stripe and accept only a known list of price IDs from the browser. Never trust an amount sent by the client.
// src/pages/api/checkout.ts
import type { APIRoute } from 'astro';
import Stripe from 'stripe';
import { STRIPE_SECRET_KEY } from 'astro:env/server';
export const prerender = false;
const stripe = new Stripe(STRIPE_SECRET_KEY);
// Allow-list of prices this site sells, mapped from your own product IDs
const PRICES: Record<string, string> = {
'linen-tote': 'price_1AbCdEfGhIjKlMnO',
'canvas-apron': 'price_1PqRsTuVwXyZaBcD',
};
export const POST: APIRoute = async ({ request, url }) => {
const form = await request.formData();
const product = String(form.get('product') ?? '');
const quantity = Math.min(Math.max(Number(form.get('quantity') ?? 1), 1), 10);
const price = PRICES[product];
if (!price) {
return new Response('Unknown product', { status: 400 });
}
const session = await stripe.checkout.sessions.create({
mode: 'payment',
line_items: [{ price, quantity }],
success_url: `${url.origin}/thanks/?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${url.origin}/shop/${product}/`,
metadata: { product },
});
return Response.redirect(session.url!, 303);
};
{CHECKOUT_SESSION_ID} is a literal placeholder that Stripe replaces with the real session ID when it redirects back. Because the string is inside a template literal, the braces stay in the URL as Stripe expects.
The buy form
A plain HTML form posts to the endpoint. No client JavaScript is needed, and it works with JavaScript disabled.
---
// src/components/CheckoutForm.astro
interface Props {
product: string;
}
const { product } = Astro.props;
---
<form method="POST" action="/api/checkout">
<input type="hidden" name="product" value={product} />
<label>
Quantity
<input type="number" name="quantity" value="1" min="1" max="10" />
</label>
<button type="submit">Checkout</button>
</form>
Product pages that use this form can stay prerendered. Only /api/checkout runs on demand. The Astro API endpoints guide explains how static pages and on-demand endpoints coexist.
Confirm payments with a webhook
The success page is not proof of payment. A visitor can open /thanks/ directly, or close the tab before the redirect. Stripe’s webhook is the reliable signal.
// src/pages/api/stripe-webhook.ts
import type { APIRoute } from 'astro';
import Stripe from 'stripe';
import { STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET } from 'astro:env/server';
export const prerender = false;
const stripe = new Stripe(STRIPE_SECRET_KEY);
export const POST: APIRoute = async ({ request }) => {
const signature = request.headers.get('stripe-signature');
const body = await request.text(); // raw body, required for signature check
let event: Stripe.Event;
try {
event = await stripe.webhooks.constructEventAsync(body, signature!, STRIPE_WEBHOOK_SECRET);
} catch {
return new Response('Invalid signature', { status: 400 });
}
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
if (session.payment_status === 'paid') {
// Fulfil: send the download link, email the team, record the order
console.log('Paid order', session.id, session.metadata?.product);
}
}
return new Response(null, { status: 200 });
};
Read the body with request.text(), not request.json(). The signature is computed over the exact bytes Stripe sent. constructEventAsync uses the Web Crypto API, which works on edge runtimes such as Cloudflare Workers as well as Node.js.
Register the endpoint URL in the Stripe dashboard under Webhooks, select checkout.session.completed, and copy the signing secret into STRIPE_WEBHOOK_SECRET. For local testing, the Stripe CLI forwards events:
stripe listen --forward-to localhost:4321/api/stripe-webhook
A thank-you page that reads the session
The success page can show order details by retrieving the session. It must be on-demand because it reads a query parameter per request.
---
// src/pages/thanks.astro
import Stripe from 'stripe';
import { STRIPE_SECRET_KEY } from 'astro:env/server';
import BaseLayout from '../layouts/BaseLayout.astro';
export const prerender = false;
const stripe = new Stripe(STRIPE_SECRET_KEY);
const id = Astro.url.searchParams.get('session_id');
const session = id ? await stripe.checkout.sessions.retrieve(id).catch(() => null) : null;
---
<BaseLayout title="Thank you">
{session?.payment_status === 'paid'
? <h1>Thanks, {session.customer_details?.name ?? 'your order is confirmed'}.</h1>
: <h1>We could not find that order.</h1>}
</BaseLayout>
Show details here, but keep fulfilment in the webhook so it runs exactly once.
Security checklist for Astro Stripe integrations
- The secret key only appears in
astro:env/serverimports, in on-demand routes. - The browser sends product IDs, never prices.
- Webhook signatures are verified with the raw body.
- Test mode keys locally and in previews; live keys only in production environment settings.
- Restricted API keys, if you want to limit what the server key can do.
When to use something else
For a full catalogue with inventory, carts and order management, a commerce platform does more of the work; see the Astro Shopify Storefront guide. For a cart on a static site with no server at all, Snipcart on Astro is an option. And if you want a designed storefront to start from, there are Astro themes for retail and e-commerce that work with either Payment Links or the endpoint above.
The official Stripe Checkout documentation and the Astro on-demand rendering docs are the references for the APIs used here.
FAQ
Can I use Stripe on a static Astro site?
Yes, with Payment Links. They are hosted URLs created in the Stripe dashboard, so a fully static site can link to them. Checkout Sessions need a server because they use your secret key.
Do I need SSR for Stripe Checkout in Astro?
Only for the endpoint that creates the session and the webhook. Add an adapter and set export const prerender = false on those routes. Everything else can stay prerendered.
Where do I store the Stripe secret key in Astro?
In an environment variable declared with envField.string({ context: 'server', access: 'secret' }) and read from astro:env/server. Set it in your host’s environment settings, never in committed files.
How do I know a Stripe payment succeeded?
Listen for the checkout.session.completed webhook and check payment_status is paid. Do not rely on a visitor reaching the success page.
Can I use Astro Actions instead of an API endpoint for Stripe?
Yes. An Action can create the Checkout Session and return session.url for the client to redirect to. A plain endpoint is simpler when you want a no-JavaScript form that redirects directly.