Two places to keep data
Browsers offer several client side stores, and cookies and local storage are the most common. They differ in how data travels and how exposed it is to scripts.
- Cookies are sent automatically on every matching request.
- Local storage stays on the client and is read only by script.
- Cookies can be HttpOnly, but local storage is always script readable.
The security tradeoff
A token in local storage is convenient but fully exposed to any script that runs on the page. If an attacker injects script through cross site scripting, that token is trivially stolen. A cookie marked HttpOnly cannot be read by script at all, which limits theft, though it must still be defended against request forgery.
- Put session tokens in HttpOnly cookies when possible.
- Treat anything in local storage as readable by injected script.
- Never store long lived secrets where script can reach them.
Choose storage by threat model, not only by convenience.
Key idea
Cookies travel automatically and can be HttpOnly, while local storage is always script readable, so secrets belong in HttpOnly cookies.