Designing an e-commerce marketplace with SSR/ISR rendering, product listing and detail pages, shopping cart with optimistic updates, multi-step checkout, image optimization at scale, and accessibility for global audiences.
FrontendX EngineeringSystem Design Series #3
0. What Are We Building?
An e-commerce marketplace where users browse millions of products, filter by category and price, view product details with images and reviews, add items to a cart, and complete purchases through a multi-step checkout. Think Amazon, eBay, or Flipkart.
This is a large-scale application, not a component. The design spans four core pages — Product Listing (PLP), Product Detail (PDP), Cart, and Checkout — each with its own rendering strategy, data dependencies, and performance constraints. We will walk through each page in detail, then zoom out to cover cross-cutting concerns like performance, security, and accessibility.
Key Insight
The frontend architecture for an e-commerce site is uniquely demanding because it must serve two masters: SEO (requiring SSR) and interactivity (requiring JS hydration). Every page load is a potential sale, so every millisecond matters. Amazon has measured that 100ms of latency costs them 1% in revenue. Design with that pressure in mind.
The live demo at the end of this article shows a working marketplace with product browsing, cart management, and a simulated checkout flow.
1. Requirements & Scoping
Before writing any code, we need to define what we are building. An e-commerce marketplace is vast, so scoping is critical.
Functional
Product browsing with search, filtering, and sorting
Product Detail Page with image gallery, reviews, recommendations
Shopping cart with optimistic updates and cross-tab sync
Resilient — cart state survives page refreshes and network errors
Accessible — WCAG 2.1 AA compliance for all user flows
Scalable — works on mobile, tablet, and desktop
Tip
A useful scoping trick: define the MVP as "a user can find a product, add it to cart, and buy it." Everything else — reviews, recommendations, wishlists — is a v2 feature. This keeps the initial architecture clean and extensible.
2. Architecture & High-Level Design
The architecture decisions here matter more than any component design. The wrong rendering strategy can tank your SEO, your performance, or both. Let us walk through the key choices.
Server-Side Rendering (SSR) with Hydration
E-commerce sites live and die by SEO. If Google cannot crawl your product pages, you do not exist. This means SSR is non-negotiable for PLP and PDP pages. The server renders the full HTML, the browser displays it immediately, and then JS hydrates the page for interactivity.
SSR vs CSR vs ISR Tradeoffs
example.js
┌─────────────────┬──────────┬──────────┬──────────┐
│ │ SSR │ CSR │ ISR │
├─────────────────┼──────────┼──────────┼──────────┤
│ SEO │ ✅ │ ❌ │ ✅ │
│ Time to First │ Fast │ Slow │ Fastest │
│ Paint │ (server)│ (client)│ (CDN) │
│ Time to │ Medium │ Fast │ Fast │
│ Interactive │ (hydrate)│ (native)│ (hydrate)│
│ Freshness │ Always │ Always │ Stale- │
│ │ fresh │ fresh │ while- │
│ │ │ │ reval │
│ Server cost │ High │ Low │ Medium │
│ Per-request │ Yes │ No │ No │
│ render │ │ │ (cached)│
└─────────────────┴──────────┴──────────┴──────────┘
For our marketplace, the strategy is a hybrid: PLP and PDP pages use ISR (Incremental Static Regeneration) via Next.js or a similar framework. Product data does not change every second, so we can serve cached HTML from the CDN and revalidate it in the background. Cart and Checkout are client-rendered — they are session-specific and cannot be cached.
Note
Amazon famously uses an MPA (Multi-Page Application) with server side rendering. Each page load hits the server, but the HTML is cached aggressively. Flipkart and Walmart use SPA + SSR with React. Both approaches work — the key is that SSR is the common denominator.
System architecture — SSR with hydration, client store shared across all pages, Image CDN for product assets, ISR for product pages
Micro-Frontends vs Monolith
For a marketplace built by a single team, a monolith is the right choice. It is simpler to develop, test, and deploy. Only when the team grows beyond ~10 engineers and the codebase exceeds 100K lines should you consider splitting into micro-frontends (one for product browse, one for checkout, one for account management).
Key Insight
The single most important architectural decision is not monolith vs micro-frontends — it is choosing SSR with ISR for product pages. Everything else follows from that. Product pages are your storefront; they must load fast and be indexable by search engines. Cart and checkout pages are transactional; they need rich interactivity and session awareness.
3. Data Model & State Shape
A marketplace has more entities than a typical app. The data model spans products, categories, carts, orders, users, reviews, and payments. Getting these right upfront avoids painful migrations later.
The client store holds data that needs to be shared across pages. Cart data lives in the client store because the navbar shows the cart count, and users expect the cart to persist as they navigate. Server data (products, categories) is cached per-page via SSR hydration.
Notice that pendingUpdates is a Map of product IDs to quantities. When the user changes a quantity, we update the UI immediately and record the pending change. If the server rejects the update, we roll back. This is the core of optimistic cart updates.
4. Interface Definition (API)
The API layer defines how the frontend talks to the backend. For a marketplace, we need endpoints for products, cart operations, and order placement. SSR hydration APIs are a special case — the server fetches data and embeds it in the HTML so the client does not need to make additional API calls on first load.
When the server renders a page, it fetches all required data and injects it into the HTML via a <script> tag. On the client, the hydration script reads this data and seeds the store. This avoids a round-trip API call on first paint.
example.js
<!-- Injected by the server during SSR -->
<script id="__NEXT_DATA__" type="application/json">
{
"page": "/products/123",
"props": {
"product": { ... },
"reviews": [ ... ],
"relatedProducts": [ ... ]
}
}
</script>
Note
This pattern — SSR with JSON hydration — is how Next.js, Remix, and Nuxt work under the hood. The server renders the first view and sends the data as JSON. The client uses that JSON to initialize the store, then takes over interactivity.
5. Product Listing Page
The Product Listing Page is the most performance-critical page in the marketplace. It is the first page most users see (via search or category browse) and it sets the expectation for the entire site. A slow PLP means lost revenue.
Rendering Strategy
PLP uses ISR with a 5-minute revalidation window. When a user visits a category page, the CDN serves the cached HTML immediately. If the cache is stale, the server regenerates the page in the background. This gives us the speed of static with the freshness of dynamic.
Filtering & Sorting
Filters and sort options are implemented as URL query parameters. This means every filter state has a unique URL, making it shareable, bookmarkable, and crawlable by search engines. The server reads the query params, fetches filtered results, and renders the page.
Offset-based pagination works well for product catalogs because the data is relatively static. Each page shows 20-48 products. We pre-fetch the next page in the background using <link rel=prefetch> so the next page navigation feels instant.
Search with Debounce
The search input uses a 300ms debounce before triggering an API call. Results are rendered as a dropdown overlay with category suggestions and top matching products. The search endpoint itself is cached at the CDN level for popular queries.
Key Insight
The key insight for PLP performance: every filter and sort change is a server-side navigation, not a client-side filter. This means the full HTML is rendered on the server, which is faster on slow devices and guarantees SEO. The tradeoff is that filter changes feel slightly slower than instant client-side filtering. To mitigate this, we use optimistic UI — show a skeleton while the server responds.
6. Product Detail Page
The PDP is where purchase decisions happen. It must convey trust through clear product images, reviews, and transparent pricing. Every element on this page either helps the user decide to buy or creates friction.
The image gallery is the most visually demanding component. Users expect to zoom in on product images to examine details. We use a three-tier image system:
Thumbnails — 80x80 WebP, lazy-loaded below the fold
Gallery images — 600x600 WebP/AVIF, displayed in the carousel
Zoom images — 1200x1200 JPEG, loaded on demand when user hovers over the main image
Zoom is implemented using the lens technique: a magnifying glass div follows the cursor and shows a cropped, zoomed portion of the high-resolution image. The zoom image is loaded only when the user activates the zoom, saving bandwidth.
Reviews are loaded lazily below the fold. They are paginated with "Load more" rather than page numbers, and each review shows a star rating, title, body, and date. Users can sort reviews by most recent, highest rating, or lowest rating.
Recommendations
A horizontal scrollable row of product cards showing "Frequently Bought Together" and "Customers Also Viewed." These are fetched from a separate API endpoint and rendered as a client component after the main product data loads. Each card is a mini-product card with a quick "Add to Cart" button.
Tip
Recommendations are an excellent candidate for client-side caching. The same user visiting multiple PDPs will see overlapping recommendations. Cache the recommendation responses in-memory with a TTL of 10 minutes to reduce API load.
Variant Selection
Products with variants (size, color, storage) use a selector-driven navigation pattern. When the user picks a variant, we update the URL to reflect the selected variant. This makes variant URLs shareable and ensures the correct variant is indexed by search engines. The variant change triggers a server re-render via ISR if the selected variant has different images or pricing.
7. Shopping Cart
The cart is the central hub of the purchasing flow. It needs to work flawlessly because any glitch here means lost sales. The three most important characteristics of a cart are persistence, optimism, and cross-tab consistency.
Optimistic Updates
When a user adds or removes an item, the UI updates immediately without waiting for the server. The actual API call happens in the background. If it fails, the UI rolls back to the previous state and shows an error toast.
example.js
async function updateCartItem(productId: string, quantity: number) {
// 1. Save previous state for rollback
const prevCart = store.getState().cart.data;
// 2. Optimistic update
store.dispatch(cartSlice.actions.optimisticUpdate({ productId, quantity }));
try {
// 3. Actual API call
const response = await fetch(`/api/cart/items/\${productId}`, {
method: "PUT",
body: JSON.stringify({ quantity }),
});
if (!response.ok) throw new Error("Failed to update");
// 4. Confirm with server state
const { cart } = await response.json();
store.dispatch(cartSlice.actions.setCart(cart));
} catch {
// 5. Rollback on failure
store.dispatch(cartSlice.actions.setCart(prevCart));
showToast("Failed to update cart. Please try again.");
}
}
Persistence
Cart state is persisted to localStorage so it survives page refreshes. On page load, the app checks localStorage for a saved cart and hydrates the store. The cart is also synced with the server on user authentication — the guest cart is merged with the server-side cart.
Cross-Tab Sync
If the user has the same site open in multiple tabs, changing the cart in one tab should update the other tabs. We use the storage event (which fires when localStorage changes in another tab) to detect changes and sync the cart state.
example.js
useEffect(() => {
const handleStorageChange = (e: StorageEvent) => {
if (e.key === "cart-state" && e.newValue) {
const remoteCart = JSON.parse(e.newValue);
// Only update if the remote cart is newer
if (remoteCart.updatedAt > localCart.updatedAt) {
store.dispatch(cartSlice.actions.setCart(remoteCart));
}
}
};
window.addEventListener("storage", handleStorageChange);
return () => window.removeEventListener("storage", handleStorageChange);
}, []);
// On every cart change, write to localStorage
store.subscribe(() => {
const cart = store.getState().cart.data;
if (cart) {
localStorage.setItem("cart-state", JSON.stringify({
...cart,
updatedAt: Date.now(),
}));
}
});
Warning
localStorage writes are synchronous and can block the main thread. Debounce writes to localStorage — do not write on every keystroke in the quantity input. Batch writes using a 500ms debounce to keep the UI responsive.
Guest Cart Merge
Users can add items to cart without logging in. When they authenticate, the guest cart (stored in localStorage) is sent to POST /api/cart/merge which merges it into the server-side cart. Duplicate items are combined (same product → sum quantities), and the merged cart is returned to the client.
8. Checkout
The checkout page is a multi-step form wizard. Each step collects a piece of the puzzle — shipping address, payment method, order review — and the user cannot proceed until the current step is valid. The state machine ensures the flow is predictable and recoverable.
Multi-step checkout state machine — cart review → shipping → payment → order review → confirmation, with failure and retry states
Address forms use real-time validation with autocomplete from a geocoding service (like Google Places or Mapbox). As the user types, we show suggestions. On submit, the address is validated against a postal code database and normalized to a standard format before saving.
Payment iframe (PCI Compliance)
The frontend never touches raw credit card data. Payment details are collected inside a hosted iframe served by the payment processor (Stripe, Braintree, etc.). The iframe posts back a payment token, which we send to our server to complete the charge. This keeps the frontend out of PCI compliance scope.
The sandbox attribute on the iframe restricts what the payment form can do. It can run scripts and communicate via postMessage, but it cannot navigate the parent page, access cookies, or open popups. This is a defence-in-depth measure beyond PCI compliance.
Order Confirmation
After the order is placed, the user sees a confirmation page with their order ID, estimated delivery date, and a summary of items purchased. The cart is cleared from localStorage and the server. The order ID is also stored in the user's order history for future reference.
9. Performance Optimization
Performance is not a bolt-on feature for e-commerce. It is the product. Every optimization directly impacts conversion rates and revenue. Here are the techniques that matter most.
Technique 1: ISR with Stale-While-Revalidate
Product pages are the lowest-hanging fruit. Use ISR to pre-render pages at build time, serve them from CDN, and revalidate in the background when they age out. The stale-while-revalidate Cache-Control directive lets the CDN serve stale content while fetching fresh content in the background.
example.js
// Next.js ISR configuration
export const revalidate = 300; // revalidate every 5 minutes
async function ProductPage({ params }: { params: { slug: string } }) {
const product = await fetchProduct(params.slug);
// If the page is stale, the user gets cached HTML
// while the server regenerates in the background
return <ProductDetail product={product} />;
}
// CDN response headers
// Cache-Control: public, s-maxage=300, stale-while-revalidate=600
Technique 2: Image Optimization
Images are the largest asset on any e-commerce page. Use an image CDN that serves WebP/AVIF, resizes on the fly, and supports responsive srcSet. Lazy-load all images below the fold. Set explicit width and height to prevent layout shift.
Key Insight
The single biggest performance win for most e-commerce sites is image optimization. Products with 10MB of uncompressed images can be reduced to 200KB of WebP at equivalent quality. This alone can cut page load time by 60% or more.
Technique 3: Code Splitting
The checkout page alone might contain 50KB of form validation logic and payment iframe code. Do not load it on the PLP or PDP. Use dynamic imports to load page-specific chunks only when needed.
example.js
// Lazy-load the checkout page chunk
const CheckoutPage = dynamic(() => import("./CheckoutPage"), {
loading: () => <CheckoutSkeleton />,
});
// Lazy-load the image gallery zoom component
const ImageZoom = dynamic(() => import("./ImageZoom"), {
ssr: false, // no need for SSR on zoom
});
Technique 4: Prefetching & Speculative Loading
Pre-fetch the next page of results when the user scrolls near the bottom of the PLP. Pre-fetch the PDP when the user hovers over a product card for more than 200ms. Use <link rel=prefetch> for same-origin navigations and <link rel=preconnect> for the image CDN and API server.
Key Insight
The performance hierarchy for e-commerce: (1) ISR at CDN edge is worth more than all other optimizations combined. (2) Image optimization is the second biggest lever. (3) Code splitting and prefetching are the fine-tuning. Do them in this order and you will get 90% of the gains with 10% of the effort.
10. Security
An e-commerce site handles sensitive user data — addresses, payment information, purchase history. A security breach here is catastrophic: financial liability, regulatory fines (GDPR, CCPA), and complete loss of user trust.
XSS in Reviews
User-generated content (reviews, Q&A) is the primary XSS vector. Never render review HTML directly. Use a sanitization library like DOMPurify to strip dangerous tags and attributes before rendering. Even better, render reviews as plain text with a safe-markdown renderer that only allows bold, italic, and links.
example.js
import DOMPurify from "dompurify";
function ReviewContent({ html }: { html: string }) {
const sanitized = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ["b", "i", "strong", "em", "a"],
ALLOWED_ATTR: ["href"],
});
return <div dangerouslySetInnerHTML={{ __html: sanitized }} />;
}
// Even better: server-side sanitization
// Sanitize reviews at write time, not just read time
CSRF for Purchases
Cart modification and order placement endpoints must be protected against Cross-Site Request Forgery. Use anti-CSRF tokens stored in cookies with the SameSite=Strict attribute. For the order placement endpoint specifically, require a one-time token that is generated when the user enters the checkout flow and invalidated after use.
Payment PCI Compliance
The golden rule: the frontend never sees a full credit card number. Use a PCI-compliant payment processor with a hosted iframe or redirect model. The iframe approach (as described in the checkout section) keeps your frontend out of PCI scope entirely.
Content Security Policy
A strict CSP header prevents injection attacks. For an e-commerce site, the CSP must allow the payment iframe origin, the image CDN, and the API server. Everything else should be blocked by default.
Never use script-src 'unsafe-inline' in production unless you absolutely need it. Use nonces or hashes for inline scripts. Strict CSP is harder to set up but worth the effort for the protection it provides against XSS.
11. Testing Strategy
Testing an e-commerce marketplace means testing user flows — not just components. A broken cart flow that lets users add items but not check out is worse than a broken button color. The testing strategy should mirror the user journey.
Unit Tests: Reducers & Validation
Test the cart reducer exhaustively: add, remove, update quantity, clear. Test the checkout state machine: every step transition, error handling, retry logic. Test address validation: valid and invalid addresses, edge cases (empty fields, special characters).
Test the complete purchase flow: browse PLP → view PDP → add to cart → update quantity → proceed to checkout → enter address → pay → confirm. Each test verifies that state persists across page navigations and that the cart badge updates correctly.
E2E Tests: Critical Paths
Cypress or Playwright tests that run against a real or mocked backend. The critical paths are: search → buy flow, adding the same product twice, removing items, guest checkout, and order confirmation page rendering.
Performance Regression Tests
Every PR that touches the PLP or PDP should run a Lighthouse performance audit. Block the PR if the LCP (Largest Contentful Paint) regresses by more than 10% or if the bundle size increases by more than 5KB gzip.
Tip
Use a dedicated test database with seeded product data. Synthetic data rarely catches edge cases — use real product data snapshots from production. This ensures your tests reflect actual usage patterns, including edge cases like products with missing images, zero prices, or very long names.
12. Accessibility
E-commerce accessibility is not just about compliance — it is about revenue. Users with disabilities represent a significant market segment, and an inaccessible checkout is a lost sale.
Skip Navigation
The very first focusable element on every page should be a "Skip to main content" link. This lets keyboard users bypass the navbar, category menu, and search bar to jump directly to the product content.
When a user adds an item to cart, screen reader users need to know about it. Use an aria-live="polite" region that announces cart updates without interrupting the current reading flow.
example.js
function CartAnnouncer({ itemCount }: { itemCount: number }) {
const [message, setMessage] = useState("");
useEffect(() => {
if (itemCount > 0) {
setMessage(`Cart has \${itemCount} \${itemCount === 1 ? "item" : "items"}`);
}
}, [itemCount]);
return (
<div aria-live="polite" aria-atomic="true" className="sr-only">
{message}
</div>
);
}
function AddToCartButton({ product }: { product: Product }) {
const addToCart = () => {
dispatch(cartSlice.actions.addItem(product));
// The announcer will read the updated count
};
return (
<button onClick={addToCart} aria-label={`Add \${product.name} to cart`}>
Add to Cart
</button>
);
}
Keyboard Product Navigation
The PLP product grid must be keyboard navigable. Arrow keys move focus between product cards. Enter/click opens the PDP. The product card itself is a single focusable element with role="article" and a descriptive aria-label.
Checkout forms must have explicit labels for every input, error messages linked via aria-describedby, and a logical tab order. Group related fields (like address lines) in fieldsets with legends. Use autocomplete attributes for address fields so browser autofill works correctly.
Color contrast: All text meets WCAG AA contrast ratios (4.5:1 for normal text, 3:1 for large text). Product price colors and sale badges are carefully chosen.
Focus indicators: Every interactive element has a visible focus ring (2px outline with 3px offset).
Reduced motion: Respect prefers-reduced-motion for image carousels and cart animations.
Tip
Test the complete purchase flow with a screen reader (VoiceOver on Mac, NVDA on Windows). If a user cannot navigate from the PLP to a product to the cart to the checkout and complete a purchase using only the keyboard, your accessibility has a gap. Fix it before shipping.
13. Key Takeaways
Building an e-commerce marketplace taught me that the frontend is not just the UI — it is the sales floor. Every design decision affects conversion. Here is what I wish I knew before starting:
SSR with ISR is non-negotiable
Product pages must load fast and be crawlable. ISR gives you the best of static (CDN speed) and dynamic (fresh content).
Optimistic cart updates with rollback
Update the UI instantly, sync with server in the background, roll back on failure. Users perceive the cart as instant.
Image CDN transforms everything
WebP/AVIF, responsive sizes, lazy loading. Images are the heaviest asset; optimizing them cuts load time by 60%+.
Checkout state machine keeps flow predictable
Every step has a defined state, transition, error, and recovery. The user can always go back without losing data.
PCI compliance means never seeing card data
Hosted iframe for payment forms. The frontend only handles tokens, never raw card numbers. Out of PCI scope.
Accessibility is a sales channel
A keyboard-accessible, screen-reader-friendly checkout converts more users. Skip nav, aria-live cart, and labeled forms are table stakes.