Node.js › Authentication & Authorization
What is the difference between storing an authentication token in localStorage versus an httpOnly cookie, from a security perspective?
BeginnerAnswer
A token in localStorage is accessible to any JavaScript running on the page, meaning a successful XSS (Cross-Site Scripting) attack can trivially steal it and exfiltrate it to an attacker. An httpOnly cookie is inaccessible to JavaScript entirely (the browser enforces this at the API level), making it immune to token theft via XSS, though cookies bring their own separate consideration around CSRF protection, which is why httpOnly cookies are generally the more secure default for browser-based session or token storage.
// Setting an httpOnly cookie server-side (JavaScript on the page can never read this)
res.cookie('accessToken', token, {
httpOnly: true,
secure: true, // only sent over HTTPS
sameSite: 'strict',
});Real-world example A single-page application initially stored its JWT in localStorage for simplicity, but after a security review moved to httpOnly cookies specifically to eliminate the token-theft risk from a class of XSS vulnerabilities the team couldn't fully rule out across a large, frequently-updated frontend codebase.