Develop a SvelteKit e-commerce site with shopping cart and checkout using Stripe.
- User
Develop a SvelteKit e-commerce site with shopping cart and checkout using Stripe.
- Assistant
Develop a SvelteKit e-commerce site with shopping cart and checkout using Stripe.
Planning SvelteKit E-commerce Site
The user is looking for a guided walkthrough to develop a SvelteKit e-commerce site with a shopping cart and Stripe integration. I need to include instructions on setting up the app, creating pages, and managing a cart store, while considering Stripe's best practices. I should touch on topics like routing, server endpoints, webhooks, and provide a simple product catalog. For checkout, I’ll explain using Stripe Checkout with a client-server interaction for session creation.Outlining Stripe Checkout Options
For the SvelteKit e-commerce site, there are two checkout options. Option 1 employs Stripe Checkout for simplicity, requiring success and cancel pages, alongside webhooks for order fulfillment. As we work with SvelteKit 2+, I’ll use file-based routing with +page.svelte and +server.ts. I’m leaning toward TypeScript for backend logic but might stick to JavaScript for accessibility. Don't forget to manage environment variables and implement a shopping cart using a Svelte store that can manage item totals and persist data with localStorage.Integrating Product Data in SvelteKit
I need to mention how to incorporate SvelteKit's load function for accessing product data. This can be done by either storing the product catalog in a JSON file or pulling from a database. For simplicity, I might use a static array in src/lib/data/products.ts and expose it through +page.server.js.
The flow will be straightforward: the homepage displays products with "Add to Cart" buttons, and the cart page shows items with a "Checkout" button. When the checkout button is clicked, the app will call /api/create-checkout-session, sending the cart items in JSON format. On the server, I'll map these items to their corresponding Stripe Price IDs and create a checkout session, returning the session URL for redirection.Setting Up Success Page and Webhooks
I need to discuss creating a /success page that retrieves session details for display after checkout. Also, it’s important to mention setting up webhooks in src/routes/api/stripe-webhook/+server.ts. Here, I’ll parse the Stripe signature and raw body using SvelteKit's Request objects. Although SvelteKit usually parses JSON by default, I might disable this or utilize request.text() to get the raw body for the webhook event.
Also, I'll highlight how to handle the checkout session completion event without diving into infrastructure details. Plus, I’ll explain fetching the checkout session with fetch('/api/create-checkout-session', { method: 'POST', body: JSON.stringify({ items }), headers: { 'Content-Type': 'application/json'}}). Lastly, I should mention integrating Stripe.js for smooth transactions, but since we’re using the session URL for redirection, we might not even require it!Creating a Minimal SvelteKit E-commerce Setup
I need to set up a basic SvelteKit e-commerce site using Stripe Checkout. For convenience, I’ll redirect to session.url directly, which simplifies the process since we won't need to load Stripe.js. Additionally, I’ll outline the file structure, including components for the product catalog, cart, header, and checkout success page.
I'll also ensure to provide a guide with code snippets for each file, like setting up environment variables for Stripe keys and configuring the cart store. Since the user is looking for a complete code skeleton, I’ll focus on clarity and brevity in explanations while presenting essential code for products, the cart store, and necessary functions. Overall, I’ll keep it straightforward, relying mainly on JavaScript for the components to avoid complications with TypeScript configurations.Crafting the Checkout Flow
I’m considering how to handle the import of product data for the SvelteKit e-commerce site. I can either import directly in the script or set up +page.server.js to pass data as data.products. Direct import seems simpler, allowing SvelteKit to tree-shake. For the cart page, I’ll need to ensure we validate incoming requests during checkout, mapping item IDs to our product list while using their stripePriceIds.
On the server side, I'll parse the JSON request containing item details, check product availability, and build line_items for Stripe. I’ll import Stripe and initialize it using the secret key from environment variables, but I'll avoid quoting specific API versions to stay flexible. The checkout button will trigger a POST request to create the checkout session, seamlessly redirecting users to the payment interface. I’ll also remind the user to set up their .env file with relevant keys. Since the query doesn’t mention webhooks, I’ll lightly touch on them as a potential next step without delving into details. Below is a minimal but complete SvelteKit + Stripe Checkout setup with:
You can copy these files into a new SvelteKit project and adjust as needed.
# Create a new SvelteKit app
npm create svelte@latest my-shop
cd my-shop
# Install dependencies
npm install
npm install stripe
Stripe’s Node library is server-side only; we’ll just redirect to Stripe’s hosted Checkout, so we don’t need @stripe/stripe-js for this basic setup.
Create a .env file in the project root:
STRIPE_SECRET_KEY=sk_test_********************************
You get this from the Stripe Dashboard → Developers → API keys → Secret key.
Create src/lib/data/products.js:
// src/lib/data/products.js
// Prices here are in cents (e.g. 1999 = $19.99).
// stripePriceId values must correspond to real Stripe Price objects
// you created in the Stripe Dashboard.
export const products = [
{
id: 'tshirt',
name: 'Svelte T-Shirt',
description: 'Soft cotton tee with Svelte logo.',
price: 2500,
currency: 'usd',
image: '/images/tshirt.jpg',
stripePriceId: 'price_XXXXXXXXXXXXXXXXXXXX1'
},
{
id: 'hoodie',
name: 'Svelte Hoodie',
description: 'Cozy hoodie for hackers.',
price: 5000,
currency: 'usd',
image: '/images/hoodie.jpg',
stripePriceId: 'price_XXXXXXXXXXXXXXXXXXXX2'
},
{
id: 'stickers',
name: 'Sticker Pack',
description: 'Pack of 10 high‑quality stickers.',
price: 800,
currency: 'usd',
image: '/images/stickers.jpg',
stripePriceId: 'price_XXXXXXXXXXXXXXXXXXXX3'
}
];
Adjust stripePriceId values to match your Stripe Dashboard.
Create src/lib/stores/cart.js:
// src/lib/stores/cart.js
import { writable, derived } from 'svelte/store';
import { browser } from '$app/environment';
// Initialize from localStorage in the browser
const initial = browser
? JSON.parse(localStorage.getItem('cart') ?? '[]')
: [];
export const cart = writable(initial);
if (browser) {
cart.subscribe((value) => {
localStorage.setItem('cart', JSON.stringify(value));
});
}
export const cartCount = derived(cart, (items) =>
items.reduce((sum, item) => sum + item.quantity, 0)
);
export const cartTotal = derived(cart, (items) =>
items.reduce((sum, item) => sum + item.quantity * item.price, 0)
);
export function addToCart(product, quantity = 1) {
cart.update((items) => {
const existing = items.find((i) => i.id === product.id);
if (existing) {
existing.quantity += quantity;
} else {
items.push({
id: product.id,
name: product.name,
price: product.price,
image: product.image,
quantity
});
}
return [...items];
});
}
export function removeFromCart(id) {
cart.update((items) => items.filter((i) => i.id !== id));
}
export function updateQuantity(id, quantity) {
cart.update((items) => {
return items
.map((item) =>
item.id === id ? { ...item, quantity: Math.max(quantity, 1) } : item
)
.filter((item) => item.quantity > 0);
});
}
export function clearCart() {
cart.set([]);
}
Create src/routes/+layout.svelte:
<script>
import { cartCount } from '$lib/stores/cart';
</script>
<nav class="nav">
<a href="/">My Svelte Shop</a>
<a href="/cart">
Cart ({$cartCount})
</a>
</nav>
<slot />
<style>
.nav {
display: flex;
justify-content: space-between;
padding: 1rem 2rem;
border-bottom: 1px solid #ddd;
}
a {
text-decoration: none;
color: inherit;
}
</style>
Create src/routes/+page.svelte:
<script>
import { products } from '$lib/data/products';
import { addToCart } from '$lib/stores/cart';
const formatPrice = (amount) =>
new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(amount / 100);
</script>
<h1>Products</h1>
<div class="grid">
{#each products as product}
<div class="card">
{#if product.image}
<img src={product.image} alt={product.name} />
{/if}
<h2>{product.name}</h2>
<p>{product.description}</p>
<p class="price">{formatPrice(product.price)}</p>
<button on:click={() => addToCart(product)}>Add to cart</button>
</div>
{/each}
</div>
<style>
.grid {
display: grid;
gap: 1.5rem;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
padding: 1.5rem 2rem;
}
.card {
border: 1px solid #ddd;
border-radius: 6px;
padding: 1rem;
}
.card img {
max-width: 100%;
height: auto;
margin-bottom: 0.5rem;
}
.price {
font-weight: bold;
margin: 0.5rem 0;
}
button {
cursor: pointer;
}
</style>
Create src/routes/cart/+page.svelte:
<script>
import { cart, cartTotal, updateQuantity, removeFromCart } from '$lib/stores/cart';
const formatPrice = (amount) =>
new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(amount / 100);
async function checkout() {
const items = $cart.map((item) => ({
id: item.id,
quantity: item.quantity
}));
if (!items.length) return;
const res = await fetch('/api/create-checkout-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items })
});
if (!res.ok) {
alert('Error creating checkout session');
return;
}
const data = await res.json();
if (data.url) {
window.location.href = data.url;
}
}
</script>
<h1>Your Cart</h1>
{#if $cart.length === 0}
<p>Your cart is empty.</p>
{:else}
<table>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Qty</th>
<th>Subtotal</th>
<th></th>
</tr>
</thead>
<tbody>
{#each $cart as item}
<tr>
<td>{item.name}</td>
<td>{formatPrice(item.price)}</td>
<td>
<input
type="number"
min="1"
value={item.quantity}
on:change={(e) => updateQuantity(item.id, +e.target.value)}
/>
</td>
<td>{formatPrice(item.price * item.quantity)}</td>
<td>
<button on:click={() => removeFromCart(item.id)}>Remove</button>
</td>
</tr>
{/each}
</tbody>
</table>
<p class="total">
Total: <strong>{formatPrice($cartTotal)}</strong>
</p>
<button class="checkout" on:click={checkout}>Checkout with Stripe</button>
{/if}
<style>
table {
width: 100%;
border-collapse: collapse;
margin: 1rem 0;
}
th, td {
border-bottom: 1px solid #eee;
padding: 0.5rem;
text-align: left;
}
.total {
margin-top: 1rem;
font-size: 1.1rem;
}
.checkout {
margin-top: 0.5rem;
cursor: pointer;
}
input[type='number'] {
width: 3rem;
}
</style>
Create src/routes/api/create-checkout-session/+server.js:
// src/routes/api/create-checkout-session/+server.js
import Stripe from 'stripe';
import { STRIPE_SECRET_KEY } from '$env/static/private';
import { products } from '$lib/data/products';
const stripe = new Stripe(STRIPE_SECRET_KEY);
/** @type {import('./$types').RequestHandler} */
export async function POST({ request, url }) {
try {
const { items } = await request.json();
if (!Array.isArray(items) || items.length === 0) {
return new Response(JSON.stringify({ error: 'No items' }), {
status: 400
});
}
// Map cart items (by our internal product id) to Stripe price IDs
const line_items = items.map((item) => {
const product = products.find((p) => p.id === item.id);
if (!product || !product.stripePriceId) {
throw new Error(`Invalid product id: ${item.id}`);
}
return {
price: product.stripePriceId,
quantity: item.quantity ?? 1
};
});
const session = await stripe.checkout.sessions.create({
mode: 'payment',
line_items,
success_url: `${url.origin}/checkout-success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${url.origin}/cart`,
// Optionally:
// customer_email: 'customer@example.com',
// metadata: { custom: 'data' }
});
return new Response(JSON.stringify({ url: session.url }), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
} catch (err) {
console.error(err);
return new Response(
JSON.stringify({ error: 'Stripe checkout session failed' }),
{ status: 500 }
);
}
}
This endpoint:
products file.session.url for redirect.Create src/routes/checkout-success/+page.svelte:
<script>
export let url;
const sessionId = url.searchParams.get('session_id');
</script>
<h1>Thank you for your purchase!</h1>
<p>Your payment was successful.</p>
{#if sessionId}
<p>Stripe session ID: <code>{sessionId}</code></p>
{/if}
<a href="/">Back to store</a>
For a production site you’d typically:
For real e‑commerce you should listen for checkout.session.completed to create/fulfill orders.
Skeleton (you will need to configure a webhook endpoint in Stripe and set STRIPE_WEBHOOK_SECRET):
// src/routes/api/stripe-webhook/+server.js
import Stripe from 'stripe';
import { STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET } from '$env/static/private';
const stripe = new Stripe(STRIPE_SECRET_KEY);
/** @type {import('./$types').RequestHandler} */
export async function POST({ request }) {
const sig = request.headers.get('stripe-signature');
const payload = await request.text(); // raw body
let event;
try {
event = stripe.webhooks.constructEvent(payload, sig, STRIPE_WEBHOOK_SECRET);
} catch (err) {
console.error('Webhook signature verification failed', err.message);
return new Response('Bad signature', { status: 400 });
}
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
// TODO: fulfill order, mark as paid, etc.
}
return new Response('ok', { status: 200 });
}
You also need to tell SvelteKit (or your adapter/proxy) not to mangle the raw body on this route; how you do that depends on your deployment platform.
npm run dev
Visit http://localhost:5173 (or whatever Vite chooses):
/cart/checkout-successIf you tell me your deployment target (Node server, Vercel, Netlify, etc.), I can add deployment‑specific notes (especially for webhooks).