Introduction To Browser Storage and how to persist data in browser.

Reading Time: 4 minutes

Irrespective of what javascript framework or library you are working on the one thing that remains constant for all web developers is the browser, where the javascript runs. Learning about browser storage is a must for all web devs. 

What is browser storage?

The browser and server interact with each other. The server serves the web pages that run on the browser and the user data is sent back to the server from the browser. So the server is the main place where we want to store the data but we can also store some temporary and convenient data on the browser. So data like authentication details and session ID or some user preference is not required for the whole operation on the server but is conveniently available.

3 types of browser storage

NOTE: The user can access all these stores in the toolbar of the application and manipulate them.

How to access browser storage through browser


Open the browser toolbar -> go to Application’s tab -> you will see all the storage options

LocalStorage SessionStorage

These web storage objects are simple key/value pairs. What’s interesting about them is that the data survives a page refresh (for sessionStorage) and even a full browser restart (for localStorage)

They have a lot more storage capacity than cookies cause they are not sent to servers in the headers. Most browsers have 5 megabytes (can be extended).

Both storage objects provide the same methods and properties:

  • setItem(key, value) – store key/value pair.
  • getItem(key) – get the value by key.
  • removeItem(key) – remove the key with its value.
  • clear() – delete everything.
  • key(index) – get the key on a given position.
  • length – the number of stored items.

localStorage

The main features localStorage of are:

  • Shared between all tabs and windows from the same origin.
  • The data does not expire. It remains after the browser restart and even OS reboots.

sessionStorage

The sessionStorage object is used much less often than localStorage.

Properties and methods are the same, but it’s much more limited:

  • The sessionStorage exists only within the current browser tab.
    • Another tab with the same page will have a different storage.
    • But it is shared between iframes in the same tab (assuming they come from the same origin).
  • The data survives page refresh, but not closing/opening the tab.

Demo

We can directly access both the storage objects.

// to add a key value pair
localStorage.setItem('test', 1);
sessionStorage.setItem('test', 1);

// to fetch the value stored in a particular key
console.log( localStorage.getItem('test') ); // 1
console.log( sessionStorage.getItem('test') ); // 1

And if you open the localStorage or sessionStorage in the browser you can see the data

Note: both key values should be strings

Storing objects

// wrong way
localStorage.setItem('user',{name: "John"});
console(localStorage.user); // [object Object]

// corrent way
localStorage.setItem('user',JSON.stringify({name: "John"}));

let user = JSON.parse( localStorage.user );
console.log( user.name ); // John

To learn more about localStorage and sessionStorage
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

Cookies

Same as localStorage, cookies also are storage objects with key/value pairs. They are somewhat special as they are attached to the HTTP request headers. So they can be helpful if the servers might need to use those cookies data. Cookies give you a limit of 4kb limit.

It’s good for data such as user preferences that the server might need to run an operation.

Demo

Note: you need an app hosted by a server to work with cookie storage a normal file hosted won’t work.

// To access this storage object you can: 
console.log(document.cookie) // shows all cookie data

// Right now might be empty cause nothing is set

// Setting data
document.cookie = "user=John"; // does not overwrite just appends new pair
console.log(document.cookie) // shows all cookie data

const user = {name: max, age: 20}
document.cookie = "user=${user}";

To learn more about cookies
https://developer.mozilla.org/en-US/docs/Tools/Storage_Inspector/Cookies

IndexedDB

This is the most complex browser storage of the three. It’s like a browser database. it lets you create web applications with rich query abilities regardless of network availability, your applications can work both online and offline.

So this is really useful for applications that need to persist really complex data for example games, calendars, google word documents, etc

Demo

Steps:

  1. Open a database.
  2. Create an object store in the database.
  3. Start a transaction and make a request to do some database operation, like adding or retrieving data.
  4. Wait for the operation to complete by listening to the right kind of DOM event.
  5. Do something with the results (which can be found on the request object).
const dbName = "CheckoutProductsStore";

//open a connection to an existing db or create new
// first parameter is the name of the db and second parameter is // the version of the db
// open method returns a request 
var request = indexedDB.open(dbName, 2);

// request object has the result, whether the connection was successful or error
request.onerror = function(event) {
  // Handle errors.
};
request.onsuccess = function(event) {
  var db = event.target.result;

  // Create an objectStore to hold information about our customers. We're
  // going to use "id" as our key path because it's guaranteed to be
  var objectStore = db.createObjectStore("products", { keyPath: "id" });

  // Use transaction oncomplete to make sure the objectStore creation is
  // finished before adding data into it.
  objectStore.transaction.oncomplete = function(event) {
    // Store values in the newly created objectStore.
    var productsObjectStore = db.transaction("products", "readwrite").objectStore("products");
    checkoutProductsData.forEach(function(product) {
      productsObjectStore.add(customer);
    });
  };
};

To learn more about indexedDB
https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB

Wrap up

This was all for just introducing the ways we can store data in the browser and the different APIs provided to us to interact with it. You can dive way deeper into these and choose which will be best for your project. Browser storage can be very useful for providing a good user experience and saving cost but just keep in mind that it can always be accessed by the client and manipulated. So it’s never an alternate to an actual server but something which can be handy for building a web app.

Leave a Reply