DEV Community

Megan Sullivan
Megan Sullivan

Posted on • Originally published at meganesulli.com

[Sketchnote] Web Storage APIs: How Browsers Store Data

A sketchnote about localStorage and sessionStorage

Browsers have two built-in ways to store data: sessionStorage and localStorage.

⚠️ Don't use either for sensitive information (passwords, credit cards, etc.), since both are vulerable to XSS attacks!

sessionStorage

  • Data stored there is cleared when the page session ends (i.e., the browser tab/window closes).
  • Each tab has its own sessionStorage object, independent from the one in other tabs.

localStorage

  • Data stored there has no expiration time.
    • Exception: If you're in a private tab, then localStorage is cleared when the last private tab is closed.
  • Storage object is specific to the protocol. (HTTP object is separate from HTTPS.)

Common API

sessionStorage and localStorage both implement the Storage interface.

Both objects contain a key-value store, which is where data is kept. The keys and values are both type DOMString.

Properties

  • .length - The number of entries in the Storage object's key-value store.

    const numEntries = sessionStorage.length
    

Methods

  • .setItem(key, value) - Adds the key-value pair to the store.

    localStorage.setItem("key", "value")
    
  • .getItem(key) - Retrieves the value for the specified key. (Returns null if the key doesn't exist.)

    const username = sessionStorage.getItem("key")
    
  • .removeItem(key) - Removes the key-value pair for the specified key. (If the key doesn't exist, nothing happens.)

    sessionStorage.removeItem("key")
    
  • .clear() - Removes all key-value pairs from the store.

    localStorage.clear()
    

Additional Resources

Oldest comments (4)

Collapse
 
bhagyash007 profile image
Bhagyash

There are more ways to store data

Cache, IndexedDB, Cookies, Web SQL

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

I have no idea who designed the API for indexedDB it is horrible!

Collapse
 
bhagyash007 profile image
Bhagyash

Yeah! I think this wrapper should make life less complicated
github.com/jakearchibald/idb

Collapse
 
bias profile image
Tobias Nickel • Edited

I way to often see people opt for localStorage when all they need is an array.