Summarizing full Stripe webhook integration plan
The user wants a SvelteKit checkout example that verifies Stripe webhook signatures with raw request bodies and implements idempotency to prevent duplicate order fulfillment. The plan includes server endpoints for creating checkout sessions, handling raw webhook requests with signature verification, and tracking processed event IDs in-memory for demonstration. This approach respects SvelteKit’s need to read the raw body via await request.text() to verify signatures properly without parsing JSON first. The final code will demonstrate these patterns with environment-variable config and minimal client-side checkout triggering.
Below is an example setup for a SvelteKit checkout flow with Stripe that includes:
- A simple checkout page/button in
+page.svelte.
- An endpoint to create a Checkout Session in
+server.js.
- A webhook endpoint that verifies the Stripe signature using the raw request body and implements idempotency checks so duplicate webhook events don’t fulfill the same order twice.
Directory structure (SvelteKit)
src/
routes/
+page.svelte
api/
create-checkout-session/+server.js
stripe-webhook/+server.js
.env
1) Checkout UI (src/routes/+page.svelte)
A minimal page with a button that calls the create-checkout-session endpoint, then redirects to Stripe Checkout:
<script lang="ts">
import { onMount } from 'svelte';
let loading = false;
async function goToCheckout() {
loading = true;
const res = await fetch('/api/create-checkout-session', {
method: 'POST'
});
if (!res.ok) {
loading = false;
alert('Failed to create checkout session.');
return;
}
const { url } = await res.json();
if (url) {
window.location.href = url;
} else {
loading = false;
alert('No checkout URL returned.');
}
}
</script>
<button on:click={goToCheckout} disabled={loading}>
{loading ? 'Redirecting...' : 'Proceed to checkout'}
</button>
2) Create Checkout Session Endpoint (src/routes/api/create-checkout-session/+server.js)
You can customize products/prices as needed. This example uses a Price ID from your Stripe dashboard:
import Stripe from 'stripe';
import { json } from '@sveltejs/kit';
import { STRIPE_SECRET_KEY } from '$env/static/private';
const stripe = new Stripe(STRIPE_SECRET_KEY, {
apiVersion: '2022-11-15'
});
export const POST = async () => {
try {
const session = await stripe.checkout.sessions.create({
mode: 'payment',
payment_method_types: ['card'],
line_items: [
{
// Replace with your actual price ID
price: 'price_ABC123',
quantity: 1
}
],
success_url: 'http://localhost:5173/?success=true',
cancel_url: 'http://localhost:5173/?canceled=true'
});
return json({ url: session.url });
} catch (err) {
console.error('Error creating checkout session:', err);
return new Response('Error creating checkout session', { status: 500 });
}
};
3) Stripe Webhook Endpoint (src/routes/api/stripe-webhook/+server.js)
This is where the verification of the webhook signature happens, using the raw request body. We also implement a simple idempotency check using an in-memory Set. In production, store processed event IDs in your database instead.
import Stripe from 'stripe';
import { STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET } from '$env/static/private';
// Initialize Stripe
const stripe = new Stripe(STRIPE_SECRET_KEY, {
apiVersion: '2022-11-15'
});
// In-memory set to track processed event IDs. Use a real DB in production.
const processedEvents = new Set();
export const POST = async ({ request }) => {
let event;
let rawBody;
const sig = request.headers.get('stripe-signature');
try {
// IMPORTANT: read raw body for signature verification
rawBody = await request.text();
event = stripe.webhooks.constructEvent(rawBody, sig, STRIPE_WEBHOOK_SECRET);
} catch (err) {
console.error('⚠️ Webhook signature verification failed:', err.message);
return new Response(`Webhook Error: ${err.message}`, { status: 400 });
}
// Idempotency check: if we’ve already processed this event, return early
if (processedEvents.has(event.id)) {
console.log(`Duplicate event ${event.id} received, skipping`);
return new Response('OK', { status: 200 });
}
// Mark this event as processed
processedEvents.add(event.id);
// Handle event types you care about
switch (event.type) {
case 'checkout.session.completed': {
const session = event.data.object;
// Example: fulfill the order
// session.id or session.payment_intent can be used
// in your own DB logic to mark the order as paid.
console.log('🔔 Payment received! Fulfilling order:', session.id);
// Example stub: call your fulfillment logic
// await fulfillOrder(session);
break;
}
// Add additional event types as needed
default:
console.log(`Unhandled event type ${event.type}`);
}
return new Response('OK', { status: 200 });
};
Notes on Raw Body in SvelteKit
- In SvelteKit server routes (
+server.js/+server.ts), you can read the unparsed body with await request.text(). Do not call request.json() before verifying; the JSON parse would alter the raw content, invalidating the signature.
- Ensure your hosting environment doesn’t automatically parse or transform the request body (e.g., some proxies or body parsers). On Vercel or Netlify with SvelteKit, the above approach with
request.text() typically works as-is.
Environment Variables
Set these in .env (or your deployment environment):
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
Idempotency Strategy
The code above uses a simple Set to track processed event IDs. In production, store event.id in a persistent database (e.g., Postgres) to avoid repeated processing across server restarts.
This setup ensures:
- The Stripe webhook is validated with the raw request body and Stripe’s webhook secret.
- Duplicate deliveries from Stripe are safely ignored using an idempotency check.
- The basic e-commerce checkout flow through Stripe Checkout is demonstrated in SvelteKit.