← Lessons

quiz vs the machine

Silver1120

Frontend

Local Storage vs Cookies Tradeoffs

Compare where browser data lives and why tokens in local storage carry real risk.

4 min read · intro · beat Silver to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. Why is a token in local storage risky?

2. What advantage does an HttpOnly cookie have for tokens?