CodePark/ questions / Cookies & browser storage
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Cookies & browser storage

Compare cookies, localStorage, sessionStorage and IndexedDB.

They differ in size, lifetime, who can read them, and whether the server sees them.

Cookies are small, about 4 KB each. The browser sends them to the server automatically with every matching request. They can have an expiry date and flags like HttpOnly, Secure and SameSite. Use them for things the server needs, like session IDs.

localStorage stores strings per origin, usually around 5 MB. Its API is synchronous (it blocks while it reads or writes). Data stays until it is cleared, and it is never sent to the server.

sessionStorage has the same API, but it belongs to one tab. It survives reloads, and it is cleared when the tab closes.

IndexedDB is an asynchronous, transactional database. It stores structured data, blobs (binary files) and large amounts of data. Its limit is a quota based on disk space. It works in web workers and service workers, but Web Storage (localStorage and sessionStorage) does not. Use it for offline data and caches.

  • Cookies are about 4 KB, are sent with requests, and support security flags.
  • localStorage holds about 5 MB, lasts until cleared, is synchronous, and stores strings only.
  • sessionStorage belongs to one tab and is cleared when the tab closes.
  • IndexedDB is asynchronous, holds large structured data, and works in workers.