web-ecommerce
E-commerce patterns for Next.js 14 App Router with Stripe. Covers Checkout Sessions, Payment Intents, cart state, webhooks, subscriptions, and order management.
1. Architecture Overview
Choose the right Stripe integration for your use case:
| Use Case | Integration | When to Use | |
|---|
| Simple buy now / cart checkout | Checkout Session | Fastest path to production; Stripe hosts the payment page | |
| Custom payment UI embedded in your site | Payment Intents + Elements | You own the checkout UI; full design control | |
| Subscriptions / recurring billing | Subscription + Checkout Session | SaaS, memberships, recurring plans | |
| Marketplace / platform payments | Connect + Payment Intents | Multi-vendor, split payments | |
Decision rule: Start with Checkout Session. Move to Payment Intents only when you need a fully embedded, custom-designed payment form. Never build custom card input without Stripe Elements — PCI scope explodes.
Request flow (Checkout Session):
Client (cart) → POST /api/checkout → Stripe API → session.url
→ redirect to Stripe-hosted page → webhook payment_intent.succeeded
→ fulfill order → redirect to /success?session_id=
Request flow (Payment Intents):
Client (cart) → POST /api/payment-intent → { clientSecret }
→ Stripe Elements confirmPayment() → webhook payment_intent.succeeded
→ fulfill order → client shows success state
2. Stripe Setup
Install
bash
npm install stripe @stripe/stripe-js @stripe/react-stripe-js zod
Environment variables
bash
# .env.local
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
NEXT_PUBLIC_BASE_URL=http://localhost:3000
Server-side Stripe instance
typescript
// lib/stripe/server.ts
import Stripe from 'stripe'
if (!process.env.STRIPE_SECRET_KEY) {
throw new Error('STRIPE_SECRET_KEY is not set')
}
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2024-06-20',
typescript: true,
})
Client-side Stripe instance
typescript
// lib/stripe/client.ts
import { loadStripe } from '@stripe/stripe-js'
const key = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
if (!key) {
throw new Error('NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY is not set')
}
// Singleton — loadStripe must not be called inside a render
export const stripePromise = loadStripe(key)
3. Product Catalog
Data model
typescript
// lib/types/product.ts
export type Price = {
id: string // Stripe Price ID: price_...
unitAmount: number // cents
currency: string // 'usd'
interval?: 'month' | 'year' // only for subscriptions
}
export type Product = {
id: string // Stripe Product ID: prod_...
name: string
description: string
images: string[]
prices: Price[]
metadata: Record<string, string>
}
Fetch products from Stripe (no CMS)
typescript
// lib/products.ts
import { stripe } from './stripe/server'
import type { Product } from './types/product'
export async function getProducts(): Promise<Product[]> {
const { data: stripeProducts } = await stripe.products.list({
active: true,
expand: ['data.default_price'],
})
const products: Product[] = await Promise.all(
stripeProducts.map(async (p) => {
const { data: prices } = await stripe.prices.list({
product: p.id,
active: true,
})
return {
id: p.id,
name: p.name,
description: p.description ?? '',
images: p.images,
prices: prices.map((price) => ({
id: price.id,
unitAmount: price.unit_amount ?? 0,
currency: price.currency,
interval: price.recurring?.interval as Price['interval'],
})),
metadata: p.metadata,
}
})
)
return products
}
export async function getProduct(id: string): Promise<Product | null> {
try {
const p = await stripe.products.retrieve(id, {
expand: ['default_price'],
})
const { data: prices } = await stripe.prices.list({ product: id, active: true })
return {
id: p.id,
name: p.name,
description: p.description ?? '',
images: p.images,
prices: prices.map((price) => ({
id: price.id,
unitAmount: price.unit_amount ?? 0,
currency: price.currency,
interval: price.recurring?.interval as Price['interval'],
})),
metadata: p.metadata,
}
} catch {
return null
}
}
Product page with image optimization
typescript
// app/products/[id]/page.tsx
import Image from 'next/image'
import { getProduct } from '@/lib/products'
import { AddToCartButton } from '@/components/cart/AddToCartButton'
import { notFound } from 'next/navigation'
import { formatCurrency } from '@/lib/utils/currency'
type Props = { params: { id: string } }
export default async function ProductPage({ params }: Props) {
const product = await getProduct(params.id)
if (!product) notFound()
const price = product.prices[0]
return (
<main className="max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-2 gap-12">
<div className="relative aspect-square rounded-xl overflow-hidden bg-neutral-100">
{product.images[0] ? (
<Image
src={product.images[0]}
alt={product.name}
fill
sizes="(max-width: 768px) 100vw, 50vw"
priority
className="object-cover"
/>
) : (
<div className="flex items-center justify-center h-full text-neutral-400">
No image
</div>
)}
</div>
<div className="flex flex-col gap-6">
<h1 className="text-3xl font-bold">{product.name}</h1>
<p className="text-2xl font-semibold">
{price ? formatCurrency(price.unitAmount, price.currency) : 'Contact for pricing'}
</p>
<p className="text-neutral-600 leading-relaxed">{product.description}</p>
{price && (
<AddToCartButton
product={{ id: product.id, name: product.name, priceId: price.id, unitAmount: price.unitAmount, currency: price.currency, image: product.images[0] }}
/>
)}
</div>
</main>
)
}
typescript
// lib/utils/currency.ts
export function formatCurrency(amount: number, currency: string): string {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency.toUpperCase(),
}).format(amount / 100)
}
4. Cart State (Zustand)
typescript
// lib/store/cart.ts
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
export type CartItem = {
productId: string
priceId: string
name: string
unitAmount: number
currency: string
image?: string
quantity: number
}
type CartState = {
items: CartItem[]
addItem: (item: Omit<CartItem, 'quantity'>) => void
removeItem: (priceId: string) => void
updateQuantity: (priceId: string, quantity: number) => void
clearCart: () => void
totalItems: () => number
totalAmount: () => number
}
export const useCartStore = create<CartState>()(
persist(
(set, get) => ({
items: [],
addItem: (incoming) => {
set((state) => {
const existing = state.items.find((i) => i.priceId === incoming.priceId)
if (existing) {
return {
items: state.items.map((i) =>
i.priceId === incoming.priceId
? { ...i, quantity: i.quantity + 1 }
: i
),
}
}
return { items: [...state.items, { ...incoming, quantity: 1 }] }
})
},
removeItem: (priceId) => {
set((state) => ({
items: state.items.filter((i) => i.priceId !== priceId),
}))
},
updateQuantity: (priceId, quantity) => {
if (quantity <= 0) {
get().removeItem(priceId)
return
}
set((state) => ({
items: state.items.map((i) =>
i.priceId === priceId ? { ...i, quantity } : i
),
}))
},
clearCart: () => set({ items: [] }),
totalItems: () => get().items.reduce((sum, i) => sum + i.quantity, 0),
totalAmount: () =>
get().items.reduce((sum, i) => sum + i.unitAmount * i.quantity, 0),
}),
{
name: 'cart-storage',
storage: createJSONStorage(() => localStorage),
}
)
)
AddToCartButton component
typescript
// components/cart/AddToCartButton.tsx
'use client'
import { useCartStore } from '@/lib/store/cart'
import type { CartItem } from '@/lib/store/cart'
type Props = {
product: Omit<CartItem, 'quantity'>
}
export function AddToCartButton({ product }: Props) {
const addItem = useCartStore((s) => s.addItem)
return (
<button
onClick={() => addItem(product)}
className="rounded-lg bg-black text-white px-6 py-3 font-medium hover:bg-neutral-800 transition-colors"
>
Add to Cart
</button>
)
}
Cart drawer component
typescript
// components/cart/CartDrawer.tsx
'use client'
import { useCartStore } from '@/lib/store/cart'
import { formatCurrency } from '@/lib/utils/currency'
import { CheckoutButton } from './CheckoutButton'
export function CartDrawer() {
const { items, removeItem, updateQuantity, totalAmount } = useCartStore()
if (items.length === 0) {
return <p className="text-neutral-500 p-6">Your cart is empty.</p>
}
return (
<div className="flex flex-col gap-4 p-6">
{items.map((item) => (
<div key={item.priceId} className="flex items-center gap-4">
<div className="flex-1">
<p className="font-medium">{item.name}</p>
<p className="text-sm text-neutral-500">
{formatCurrency(item.unitAmount, item.currency)} each
</p>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => updateQuantity(item.priceId, item.quantity - 1)}
className="w-8 h-8 rounded border flex items-center justify-center"
>
−
</button>
<span className="w-6 text-center">{item.quantity}</span>
<button
onClick={() => updateQuantity(item.priceId, item.quantity + 1)}
className="w-8 h-8 rounded border flex items-center justify-center"
>
+
</button>
</div>
<button
onClick={() => removeItem(item.priceId)}
className="text-red-500 text-sm hover:underline"
>
Remove
</button>
</div>
))}
<div className="border-t pt-4 flex items-center justify-between">
<p className="font-semibold text-lg">
Total: {formatCurrency(totalAmount(), items[0]?.currency ?? 'usd')}
</p>
<CheckoutButton />
</div>
</div>
)
}
5. Stripe Checkout Session
API route — create session
typescript
// app/api/checkout/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { stripe } from '@/lib/stripe/server'
import { z } from 'zod'
const LineItemSchema = z.object({
priceId: z.string().startsWith('price_'),
quantity: z.number().int().min(1).max(100),
})
const CheckoutSchema = z.object({
items: z.array(LineItemSchema).min(1).max(50),
})
export async function POST(req: NextRequest) {
try {
const body = await req.json()
const { items } = CheckoutSchema.parse(body)
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL