LocalStorage & SessionStorage
#browser api
LocalStorage
The
localStorage
is part of the document
object.localStorage
is similar to sessionStorage
, but the main difference is that while sessionStorage
data is cleared when the session expires (i.e., when the tab or browser is closed), localStorage
data persists even after the session ends, and it remains available until explicitly cleared by the user or through the program.localStorage
is protocol-specific. This means that even with the same domain and host, the data stored in localStorage
will be different for http
and https
protocols.The data stored in
localStorage
is automatically converted to a string, and is stored in a key-value format. Each key and value is stored as a UTF-16 DOMString
with a maximum size of 2 bytes.Examples of
localStorage
methods:localStorage.setItem(key, value); // Store a key-value pair localStorage.getItem(key); // Retrieve a value by key localStorage.clear(); // Remove all items in localStorage
Session Storage
sessionStorage
stores data for the duration of the browser session. It persists as long as the browser window or tab is open, but the data will be cleared once the tab or window is closed. Unlike session cookies, if a new tab or window is opened, a new sessionStorage
instance is created.Like
localStorage
, sessionStorage
is protocol-specific (http vs https), and it stores data in the same key-value format. The maximum size for each key-value pair is 2 bytes, stored as UTF-16 DOMString
.Examples of
sessionStorage
methods:sessionStorage.setItem(key, value); // Store a key-value pair sessionStorage.getItem(key); // Retrieve a value by key
Key Differences:
localStorage
persists even after the browser or tab is closed.
sessionStorage
only persists as long as the tab or browser session is active.
- Both use the same key-value storage mechanism, with a 2-byte maximum per key-value pair (UTF-16 format).