Using browser storage in JavaSript and TypeScript projects is relatively simple, but implementing it correctly can be tricky. Take a moment to review the 4 key considerations we'll need to account for in most circumstances.
Session or local storage
We choose between local or session storage depending on the nature, lifespan, and sensitivity of data.
- Local Storage
- maintained between sessions (i.e. it stays after you close the browser)
- Session Storage
- cleared automatically between sessions (i.e. when you close the browser)
Choosing a storage key
Data is saved into browser storage with an associated key or string so it can be retrieved later. Since there's nothing to stop another feature on the site from using the same key, we should make ours as specific as possible.
Storing complex data
Saving primitive data to the browser like numbers and strings just works, but you'll run into issues when storing or retrieving objects. To get around this, saving should incorporate
JSON.stringify and retrieving should incorporate
Unlike cookies, local and session storage don't incorporate any expiration logic out of the box. To work-in expiration we also need to save a date timestamp. The timestamp could be paired directly with the save-data (i.e. saving an object with date and data properties) or it could be saved as a separate entry with a standardized naming convention (i.e. if 'myData' stores the data 'myData_date' will store the date). I prefer the latter option in order to keep data agnostic from the retrieval method.
Blog post series
Next, we'll learn how to implement the 3 routine actions: saving, retrieving, and clearing: Browser storage: How to use browser storage code examples.