Single Page Applications (SPAs) built with React, Vue, or Angular frequently communicate with APIs using JSON Web Tokens (JWTs) or OAuth 2.0 access tokens. Storing these tokens securely in the browser is one of the most critical aspects of frontend web security.

The Risk of LocalStorage and SessionStorage

Many developers store access tokens directly in localStorage or sessionStorage because it is simple and persists across page reloads. However, this data is vulnerable to Cross-Site Scripting (XSS) attacks. If a hacker injects a malicious script via a compromised third-party library, they can read localStorage instantly and steal the user's active session.

The Secure Standard: HttpOnly Cookies

To eliminate XSS-based token theft, store access and refresh tokens in secure, HttpOnly cookies. These cookies are processed directly by the browser and cannot be read by JavaScript scripts. Combine this with the Secure attribute (ensuring tokens are only transmitted over HTTPS) and the SameSite=Strict attribute to block Cross-Site Request Forgery (CSRF) attacks, keeping your authentication gateway perfectly secure.