Quick Notes on sessionStorage & localStorage

Shinemon Divakaran
2 min readJul 19, 2020

--

Photo by Md. Zahid Hasan Joy on Unsplash

In many of the applications we extensively use the sessionStorage and localStorage, and its of great usage for accessing some required information and establishing various client side features. For any web development there are large number of API’s we use to fulfill various implementations.

The Web Storage API provides mechanism(localStorage and sessionStorage) by which browsers can store key/value pairs which can be used by client-side.

Unlike Cookies, the localStorage/sessionStorage cannot be passed/read by the server-side. This eliminates the security issues bound with cookies.

Web Storage allows much more data to be stored, ~10MB in most browsers. Unlike Cookies where we can store max of ~4KB per domain(4096 bytes).

sessionStorage:

Maintains a separate storage area for each given origin, and the key/value pair data is stored only until the window or tab is closed.

Note- Origin here refers to domain, port and protocol. i.e same app running on http vs https have different storage.

localStorage:

The key/value pair data with no expiration survives until the user manually clears the browser cache or the web app systematically clears the data. i.e even survive post browser restart or os restart.

Same syntax work for both sessionStorage and localStorage, as you can see below its very simple and straightforward.

Create:

let key = 'key_1';
sessionStorage.setItem(key,'value_1');

Read:

sessionStorage.getItem('key_1');

Update:

sessionStorage.setItem('key_1','newValue_1');

Remove:

sessionStorage.removeItem('key_1');

As sessionStorage/localStorage allows key value pairs of Strings only, doesnt mean we cannot store complex objects. By using JSON.stringify to setItem value, and JSON.parse to read the value, we can store complex objects.

//sample storage jslet key = 'key_1';
sessionStorage.setItem(key,"session_Value_1");
localStorage.setItem(key,"local_Value_1");
alert("Session Storage " + sessionStorage.getItem(key));
alert("Local Storage " + localStorage.getItem(key));

//Set Object:
let myObj = { studentName: 'John Smith', course: 'CSC' };
let key2 = 'key_obj_1';
localStorage.setItem(key2, JSON.stringify(myObj));
// Read item:
let item = JSON.parse(localStorage.getItem(key2));

--

--

Shinemon Divakaran

Passionate Software Engineer exploring to learn and share knowledge. I enjoy hiking, running, and most sports. All opinions are my own.