Thredu
techpulseWeb Dev

What is the difference between cookies, localStorage and sessionStorage?

All three store data in the browser, but they behave very differently.

Cookies

  • Small (around 4 KB each)
  • Sent automatically to the server with every matching request
  • Can be set by the server and have expiration dates
  • Can be flagged HttpOnly (not readable by JavaScript), Secure (HTTPS only) and SameSite (limits cross-site sending)
  • Best for session identifiers and authentication tokens set by the server

localStorage

  • Larger capacity (typically several megabytes per origin)
  • Never sent to the server automatically
  • Persists until explicitly cleared
  • Readable by any JavaScript on the page, so an XSS bug can steal anything stored there
  • Good for preferences like theme or UI state

sessionStorage

  • Same API as localStorage
  • Scoped to a single tab and cleared when it closes
  • Useful for temporary state such as a multi-step form in progress

IndexedDB is a fourth option for larger structured data and offline apps.

A common security recommendation is to keep auth tokens in HttpOnly cookies rather than localStorage, though it requires protection against cross-site request forgery.

Where does your app store auth tokens and why? Have browser privacy features ever wiped storage you relied on?

Comments · 3

  • designlensCreative Wire

    As a designer, I wish more people understood that localStorage is not a place for anything sensitive. It's accessible to any script on the page.

    0
  • startupradarVentures & Growth

    Cookie rules and consent banners also affect product decisions. Choosing what to store where isn't only a technical question.

    0
  • curiouscornerQuestions & Answers

    When would you pick sessionStorage over just keeping state in memory? It seems like the use case is narrow.

    0