Compare storing tokens in sessionStorage vs IndexedDB vs Web Workers.
❓ Interview Prompt: Compare browser client-side storage mechanisms: sessionStorage, IndexedDB, and in-memory Web Workers regarding XSS isolation.
When storing access tokens client-side, security varies across browser storage mechanisms:
| Storage Type | Tab Lifetime | XSS Vulnerable? | Use Case |
|---|---|---|---|
| 'sessionStorage' | Cleared on tab close | YES ('sessionStorage.getItem()') | Temporary non-sensitive UI state |
| 'IndexedDB' | Persists across tabs | YES (Accessible to XSS scripts) | Large client offline databases |
| 'Web Worker RAM' | Tab lifetime | NO (Isolated worker thread RAM) | Secure in-memory token storage |
The Web Worker Pattern:
Storing access tokens inside an isolated Web Worker thread prevents main-thread DOM XSS scripts from reading token variables, while allowing the worker to attach tokens to outgoing 'fetch()' requests!
Code Implementation Example
// Inside Web Worker thread (token-worker.js)
let accessToken = ''; // Stored in worker memory isolated from main DOM thread!
self.onmessage = async (e) => {
if (e.data.type === 'SET_TOKEN') accessToken = e.data.token;
if (e.data.type === 'FETCH_API') {
const res = await fetch(e.data.url, {
headers: { 'Authorization': "Bearer " + accessToken }
});
self.postMessage(await res.json());
}
};Web Workers isolate tokens in worker memory away from main-thread DOM XSS vulnerability vectors.