๐ฆ๐๐ผ๐ฝ ๐จ๐๐ถ๐ป๐ด ๐๐ผ๐ฐ๐ฎ๐น๐ฆ๐๐ผ๐ฟ๐ฎ๐ด๐ฒ ๐ณ๐ผ๐ฟ ๐๐๐๐ต ๐ง๐ผ๐ธ๐ฒ๐ป๐
You have five ways to store data in a browser. Most developers pick the wrong one.
Ask yourself three questions. How big is the data? Who needs to read it? How long should it stay?
Here are your options.
- Cookies: Small size. The browser sends them to the server automatically. Use these for session tokens.
- localStorage: 5 to 10 MB. Data stays until you clear it. Use this for theme settings or language.
- sessionStorage: 5 to 10 MB. Data dies when you close the tab. Use this for form drafts.
- IndexedDB: Hundreds of MB. It is asynchronous. Use this for offline apps.
- Cache API: Stores HTTP responses. Use this for PWAs.
Many tutorials tell you to put auth tokens in localStorage. This is a mistake.
Any script on your page reads localStorage. A single security hole lets a hacker steal your token. They steal the user session.
Use HttpOnly cookies instead. JavaScript is unable to read these. The browser sends them to the server. Your users stay safe.
Pick based on these rules.
- Server needs it? Use Cookies.
- UI preference? Use localStorage.
- Tab data? Use sessionStorage.
- Huge data? Use IndexedDB.
- Offline PWA? Use Cache API.
Most apps only need three. Use an HttpOnly cookie, localStorage, and sessionStorage.
Source: https://dev.to/dip_032d2fe1959e1990ddbb1/should-we-use-localstorage-for-storing-auth-token-5g51