Skip to content
Putting technology to work.
Insights to guide decisions and action.

Search articles

The "stop storing JWTs in localStorage" debate: Security audits for web authentication implementations in client development

Table of contents · 11 items

In May 2026, an article titled Why people say "stop storing JWTs in localStorage": A chronological overview leading to the return of cookies (Zenn 2026-05-27) trended widely. Sparked by a post on X from prominent web security expert Hiroshi Tokumaru, it highlighted that SPA architectures storing JWTs in localStorage are vulnerable to XSS. The article carefully traced the history of how Authorization header approaches briefly became standard and why there has recently been a "resurgence" toward session architectures backed by HttpOnly cookies.

At our firm, requests for client services to "audit the authentication implementation of our existing web app / SPA" have been rising. Most clients say, "It works, but we lack confidence in whether our token storage location and refresh flow design are truly secure." This article formalizes these concerns into our "web authentication implementation security audit" service, breaking down the process from diagnosis to remediation and ongoing operations. For underlying threat models, see Introduction to Web Security; for replacing the auth platform itself, consult Better Auth / Supabase / Clerk Authentication Migration for Clients.

Why "token storage location is a turning point"

The crux of the debate is "where to store access tokens." While localStorage is freely accessible via JavaScript, HttpOnly cookies cannot be read by scripts. This fundamental difference determines overall XSS resilience.

DimensionlocalStorage storage + Authorization headerHttpOnly cookie + proper flags
Token theft via XSSHigh risk of exfiltration because it is readable via JSUnreadable via JS due to HttpOnly, making theft difficult
CSRFInherently unlikely due to explicit header injectionRequires defenses using SameSite=Lax/Strict + CSRF tokens
Third-party cookie restrictionsLargely unaffectedRequires caution for cross-site use (assumes first-party)
Cross-origin API callsRelatively straightforward via CORS configurationRequires careful domain design and SameSite adjustment
Implementation complexityDeceptively simple, but hinges on robust XSS defensesRobust, but requires server-side sessions / BFF

The key takeaway is that "neither approach is a silver bullet." While the localStorage pattern can work if XSS is strictly contained through CSP and input sanitization, it possesses a single point of failure: a single XSS flaw exposes all tokens to theft. Conversely, cookie-based architectures require proper CSRF defenses and correct SameSite configuration. Our audits evaluate whether an application meets the prerequisites required by its specific threat model.

Three structural changes beneficial to custom development projects

Structural shift 1: Moving from "as long as it works" to "threat-model-driven auth design"

Whereas previously "being able to log in" was sufficient, applications are now scrutinized on whether XSS, CSRF, open redirects, and token fixation are explicitly modeled and paired with concrete countermeasures. In custom development, documenting threat models during requirement definition and preserving architectural rationales delivers clear value. The breakdown in Introduction to Web Security serves as an effective starting point for identifying threats.

Structural shift 2: From frontend-only to the resurgence of BFF and cookie sessions

There is an accelerating swing away from architectures where the SPA frontend holds tokens on its own toward setups where a Backend for Frontend (BFF) manages tokens and issues only an HttpOnly cookie session ID to the browser. In custom development, the architectural expertise to seamlessly integrate a BFF without breaking the existing SPA creates a major competitive advantage.

Structural shift 3: From one-off audits to ongoing security operations

Vulnerabilities in third-party libraries and scripts emerge continuously. Demand is rising for ongoing re-audit workflows rather than single assessments. Adopting the concepts from our SCS (Security Evaluation) Guide, we establish evaluation frameworks for regular, scheduled monitoring.

The 5 phases of client-provided "web authentication implementation security audits"

Phase 1: Current-state assessment

  • Inventory token storage locations (localStorage, sessionStorage, cookies, memory)
  • Diagram authentication flows (login, refresh, logout, revocation)
  • Review dependencies, versions, and known vulnerabilities

Phase 2: Threat evaluation

  • Inspect for XSS, CSRF, open redirects, and token fixation
  • Verify current configuration of CSP, SameSite, HttpOnly, and Secure flags
  • Evaluate refresh token expiration, rotation, and revocation mechanisms

Phase 3: Remediation design

  • Establish token storage strategy (determine need for cookie sessions / BFF)
  • Design CSP policies (evaluating nonce / strict-dynamic adoption)
  • Design refresh token rotation and revocation blocklists

Phase 4: Remediation implementation and PR review

  • Implement remediation code or review existing pull requests
  • Verify configuration of SameSite, HttpOnly, and Secure flags
  • Add automated tests (authentication flow, revocation, CSRF)

Phase 5: Re-audit and operations (ongoing)

  • Conduct post-remediation audit and differential verification
  • Perform routine monitoring of dependency vulnerabilities and CSP violation reports
  • Establish incident response playbooks for token revocation and rotation

Standard technology stack set for custom development

LayerRecommendationAlternative
Authentication methodServer sessions + BFFOIDC / OAuth 2.1 (external IdP)
Token storageHttpOnly + Secure + SameSite CookieIn-memory storage (short-lived access tokens)
CSP / headersCSP (nonce-based) + HSTS + X-Content-Type-OptionsPhased rollout starting with report-only mode
CSRF defenseSameSite + Double Submit / Synchronizer TokenCombined Origin / Referer validation
Audit and inspection toolsDependency vulnerability scanning + DAST + CSP report collectionPaired with manual code review

Tools are merely aids; "design decisions grounded in the threat model" remain paramount.

Which projects need this and which do not

Scenarios requiring an auditScenarios where an audit is excessive
SPAs storing tokens in localStorageStatic websites without authentication features
Applications handling personal data or payment detailsInternal, closed staging or testing tools
Ambiguous or undocumented refresh token architecturesFully delegated to managed IdPs with zero custom code
Applications loading numerous third-party scriptsPublic, read-only content portals

Six clauses to include in client contracts

ClauseDetailsWhat the client should verify
Audit scopeExplicit listing of target apps, domains, and out-of-scope assetsClarify whether subdomains and external APIs are included
Inspection methodologyStatic, dynamic, and manual techniques with non-destructive guaranteesFeasibility and terms for production testing
Remediation responsibilitiesReporting only versus implementation inclusionDemarcation from client in-house development tasks
Handling of PoC artifactsStorage and secure disposal of obtained credentials and PoCsConfidentiality terms and retention timelines
Critical vulnerability notificationImmediate reporting workflows based on severityCommunication channels and SLA
Re-audit termsScope and frequency of post-remediation verificationPresence or absence of additional fees

Client-side ROI estimate

BenefitEstimation rationale
Data breach preventionAvoid incident response, notification, and compensation costs
Reduced remediation reworkPre-release fixes cut production patching overhead
Vulnerability management laborMonthly operations smooth out ad-hoc patching spikes
Maintaining partner trustSupports B2B ongoing contracts and creditworthiness

Even if an initial investment of around 1.4 million yen is made for a spot audit and remediation implementation, this is typically orders of magnitude smaller than the cost of responding to a single major security incident (investigations, disclosures, compensation, and reputational loss). For applications handling personal data or payment processing, the expected value of avoided losses easily justifies the cost.

Five common pitfalls

Switching storage locations without implementing SameSite or CSRF defenses simply substitutes one risk for another. Migrations must be executed with a complete set of security controls.

Pitfall 2: Leaving CSP unconfigured

Without CSP as the last line of defense against XSS, script injection causes extensive damage whether tokens reside in localStorage or cookies. A pragmatic approach is a phased rollout starting from report-only.

Pitfall 3: Effectively indefinite refresh token lifespans

Long-lived refresh tokens cause catastrophic damage if stolen. Incorporate rotation and revocation lists into your architecture.

Pitfall 4: Clinging to pure SPA architectures without introducing a BFF

As long as tokens are held in the frontend, they remain within reach of XSS. When handling sensitive data, consider hiding tokens behind a BFF.

Pitfall 5: Ignoring third-party scripts

External scripts like advertising, analytics, and chat widgets can serve as entry points for XSS. You must inventory external scripts and enforce allowlists via CSP.

90-day action plan

WeekInitiative
Weeks 1–2Inventory token storage locations and diagram authentication flows
Weeks 3–4Threat evaluation for XSS, CSRF, and open redirects
Weeks 5–6Current-state review of CSP, SameSite, and HttpOnly, and definition of remediation policies
Weeks 7–9Remediation implementation, PR reviews, and adding tests
Weeks 10–11Phased rollout of BFF and cookie session migration
Weeks 12–13Re-audit, operationalizing recurring health checks, and handover

Conclusion

The debate over "don't store JWTs in localStorage" is not simply about "solving everything by changing the storage location"; rather, it calls for revisiting your entire authentication architecture against your threat model. When viewed holistically—spanning HttpOnly, Secure, SameSite, CSP, refresh token architecture, and BFFs—the key decision criterion, whether you choose localStorage or cookies, is whether the prerequisites are met. Our Web Authentication Implementation Security Audit provides hands-on support from diagnostic assessment and remediation to continuous operation. If you have any concerns about your existing application's authentication, please feel free to reach out via our contact form.

Sources

Share this articleXFacebook
Kakeru Suzuki

Fascinated by the possibilities of technology, has had a deep interest in programming and digital art since student days

Turn this article's theme into your company's next step

Concrete steps forward for your organization.

We organize your desired architecture, legacy systems, and operational requirements to formulate your next steps toward execution.

  • Desired architecture
  • Integration with existing environments
  • Operational requirements
Consult on development & operations initiatives

You can consult with us from the initial conceptual stage. Details from this article will be carried over to the inquiry form.

Receive the latest articles by email