What is the key difference between using sessionStorage and localStorage for storing tokens in a web application?
- A.sessionStorage is shared between the tabs of an origin; localStorage is limited to one tab, so tokens in localStorage are safer against XSS since a script in another tab does not see them in the browser
- B.sessionStorage is encrypted by the browser; localStorage is stored in plain text, so XSS reads the second one on disk in the profile
- C.localStorage is attached to each request by the browser; sessionStorage stays in the page, so CSRF targets the first of the two
- D.sessionStorage is cleared when the browser tab is closed; localStorage persists until explicitly cleared. Both are equally accessible to JavaScript, so both are equally vulnerable to XSS
Why D is correct
The persistence difference: sessionStorage data lives only for the browser tab session and is cleared on close; localStorage persists across sessions. However, from an XSS attack perspective, both are equally readable by JavaScript running on the same origin. Neither provides the protection of HttpOnly cookies against XSS-based token theft.
Know someone studying for Web App Fundamentals? Send them this one.