A minimal Express server that creates Stripe Checkout Sessions and returns the Checkout URL to a client (SPA or web app).
- Node.js 18+
- A Stripe account and a Secret Key
Create a .env file in the project root:
STRIPE_PRIVATE_KEY=sk_test_...
CLIENT_URL=http://localhost:5173STRIPE_PRIVATE_KEY: Your Stripe Secret Key (from the Stripe Dashboard).CLIENT_URL: Your frontend/app origin used for CORS and success/cancel redirects.
pnpm install
# or
npm install
# or
yarn installpnpm start
# or
npm startServer starts on http://localhost:4242.
POST /create-checkout-session
Creates a Stripe Checkout Session from the provided cart items and returns the Checkout URL.
Request body (JSON):
{
"items": [
{
"name": "T-Shirt",
"image": "https://example.com/tshirt.png",
"price": 1999,
"amount": 2
}
]
}priceis in the smallest currency unit (e.g., cents for USD).amountis the quantity.
Response (JSON):
{ "url": "https://checkout.stripe.com/c/session_..." }const res = await fetch("http://localhost:4242/create-checkout-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items }),
});
const { url } = await res.json();
window.location.assign(url); // or window.location.replace(url)curl -X POST http://localhost:4242/create-checkout-session \
-H 'Content-Type: application/json' \
-d '{
"items": [
{"name": "T-Shirt", "image": "https://example.com/tshirt.png", "price": 1999, "amount": 1}
]
}'The server allows requests from CLIENT_URL. Ensure your frontend runs at that origin (e.g., http://localhost:5173).
success_url and cancel_url use CLIENT_URL with query params ?success=true and ?canceled=true. Update in server.js if you need custom routes.
- This server uses dynamic
price_data; in production, prefer predefined Stripe Prices for accuracy and security. - Do not expose your Stripe Secret Key in the client.
- Consider handling Stripe webhooks for post-payment fulfillment.