Browser Security Architecture: HttpOnly Cookies, SameSite & Custom Anti-CSRF Headers
Many single-page applications still write JWT access tokens into browser localStorage because it is easy to wire into Authorization: Bearer headers. Unfortunately, any single third-party script or Cross-Site Scripting (XSS) flaw anywhere on the origin can read localStorage directly and exfiltrate persistent session credentials.
1. Why HttpOnly Cookies Protect Against Token Exfiltration
Setting authentication cookies with the HttpOnly, Secure, and SameSite=Lax flags prevents client-side JavaScript from reading the raw credential via document.cookie while still letting the browser attach credentials automatically over HTTPS—a baseline defense recommended by the OWASP HttpOnly Guidance.
2. Closing the CSRF Gap on Cookie-Authenticated APIs
Because browsers automatically send cookies on cross-site requests, cookie-authenticated mutations require Cross-Site Request Forgery (CSRF) mitigation. Modern applications enforce two complementary layers (described in the OWASP CSRF Prevention Cheat Sheet):
| Defense Mechanism | How It Blocks Attacks | Implementation Notes |
|---|---|---|
SameSite=Lax Cookie Attribute |
Blocks cookies on third-party cross-site POST forms |
Allows top-level GET link clicks cleanly without breaking logins |
Custom Request Header (X-Requested-With) |
Plain HTML forms cannot forge custom headers; CORS preflight blocks untrusted origins | Ensure Axios, fetch() wrappers, and multipart uploads attach the header uniformly |
| Explicit Origin / Referer Allowlist | Rejects mutations arriving from unverified third-party domains | Normalize host ports accurately behind reverse proxies (Nginx / Cloudflare) |
3. Common Pitfalls in Production Deployments
- Raw
fetch()bypassing Axios interceptors: Even if Axios setsX-Requested-Withglobally, a single standalonefetch('/api/campaigns', { method: 'POST' })call without the header will be rejected by strict production CSRF middleware. Wrap all network calls in a shared helper. - Missing
trust proxyconfiguration: Behind load balancers or CDN edge SSL termination, ensure Express/Laravel trusts proxy headers (X-Forwarded-Proto) soSecurecookies set reliably over HTTPS.
Mayur Kadam
Principal Software Architect · SaaS, Laravel & Distributed Systems
Leads software architecture, multi-tenant database design, and cloud security reviews for B2B web platforms, ERPs, and high-throughput APIs.