Memory-Only Token Storage
You'll learn how to store authentication tokens exclusively in JavaScript variables for maximum security without browser persistence.
What is Memory-Only Storage?
Memory-only token storage means keeping your JWT or access token in a JavaScript variable (like let accessToken = '...') rather than writing it to localStorage, sessionStorage, or even cookies. The token lives only in your application's runtime memory—it exists while the page is open but vanishes completely when the user refreshes or closes the tab.
How It Works
When your user logs in, your frontend receives the token and stores it in a simple variable:
let accessToken = null;
async function login(credentials) {
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify(credentials)
});
const data = await response.json();
accessToken = data.token; // Only in memory!
}
function makeAuthenticatedRequest(url) {
return fetch(url, {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
}
The Security-Convenience Tradeoff
Maximum security: Since the token never touches localStorage, it's immune to XSS-based token theft that reads from storage. An attacker can execute JavaScript, but they can't easily extract a token they can't locate in persistent storage.
Zero persistence: The user must log in again after every page refresh or browser restart. There's no "remember me" functionality—it's like writing notes on a whiteboard that gets erased when you leave the room.
When to Use This Pattern
Memory-only storage works well for high-security applications (banking, healthcare) where you're already using HttpOnly cookies for refresh tokens to handle the persistence problem separately.
Key Takeaway: Memory-only token storage maximizes protection against XSS attacks by keeping tokens in JavaScript variables, but requires users to re-authenticate after every page reload.