Refresh Token Storage Strategies
What you'll learn: Where and how to securely store refresh tokens to balance security and usability.
Refresh tokens are long-lived credentials that grant new access tokens. Because they're so powerful (they can generate valid authentication repeatedly), where you store them is critical to your application's security.
HttpOnly Cookies: The Gold Standard
The most secure option is storing refresh tokens in httpOnly cookies. These cookies cannot be accessed by JavaScript, which protects them from XSS (cross-site scripting) attacks. When your browser automatically sends them with requests to your auth server, the server can validate and issue new tokens without frontend code ever touching the refresh token.
// Server sets httpOnly cookie (frontend never sees the token)
res.cookie('refreshToken', token, {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000 // 7 days
});
In-Memory Storage: Maximum Security, Minimum Persistence
Some applications store refresh tokens only in memory (a JavaScript variable). This prevents both XSS theft (since it's never in localStorage) and CSRF attacks (no automatic sending). The tradeoff? The token vanishes when users refresh the page or close the tab, requiring them to log in again.
// In-memory storage
let refreshToken = null;
function storeRefreshToken(token) {
refreshToken = token; // Lost on page reload
}
Think of it like this: HttpOnly cookies are like a safe deposit box the browser manages for you—secure but convenient. In-memory storage is like keeping cash in your pocket—ultra-secure but lost if you change clothes.
Key Takeaway: Use httpOnly cookies with secure flags for refresh tokens in most applications; reserve in-memory storage for high-security scenarios where forcing re-login after page refresh is acceptable.