Secure Token Storage — Best Practices for Storing Auth Tokens
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Secure Token Storage. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Secure token storage prevents token theft through XSS, CSRF, and other client-side attacks.
// Secure cookie-based token storage
function setSecureTokenCookie(res, token, options = {}) {
const cookieOptions = {
httpOnly: true,
secure: true,
sameSite: 'strict',
path: '/api',
maxAge: 15 * 60 * 1000, // 15 minutes
...options
};
res.cookie('access_token', token, cookieOptions);
}
// Refresh token in separate cookie with different path
function setRefreshTokenCookie(res, token) {
res.cookie('refresh_token', token, {
httpOnly: true,
secure: true,
sameSite: 'strict',
path: '/auth/refresh', // Only sent to refresh endpoint
maxAge: 7 * 24 * 60 * 60 * 1000
});
}
// Server-side token extraction
app.use('/api', async (req, res, next) => {
let token = null;
// Try cookie first (most secure for SPAs)
token = req.cookies?.access_token;
// Fall back to Authorization header (for mobile apps)
if (!token) {
const authHeader = req.headers.authorization;
if (authHeader?.startsWith('Bearer ')) {
token = authHeader.slice(7);
}
}
// Fall back to custom header
if (!token) {
token = req.headers['x-access-token'];
}
if (!token) return res.status(401).json({ error: 'No token' });
req.token = token;
next();
});
Secure token storage prevents XSS-based token theft by keeping tokens inaccessible to JavaScript.
← Previous
Identity Federation — Federated Identity Patterns Across Systems
Next →
API Gateway Authentication — Centralized Auth at the Gateway
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro