DEV Community

João Chitas for Runtime Revolution

Posted on • Originally published at revs.runtime-revolution.com on

Saving data inside the browser’s storage — a summary

Saving data inside the browser’s storage — a summary

Photo by Samuel Zeller on Unsplash

Every time you visit a website you may have noticed that on repeated visits there are some elements that no longer appear or load faster. It could be cache working its magic or maybe there is something inside your browser that triggers these behaviors.

A very simple example: modals asking for your consent about the use of cookies. After the EU approved the GDPR regulation, many websites started showing a modal warning the user that, to improve their experience navigating the page, they use cookies. Accepting the use of these needs to be stored somewhere so that when you visit the site for a second time, it would behave in a different way (in this case, the consent modal would no longer appear). This could be stored inside a server database but that would be complex. Instead, the browser has its own storage and cookies are just one storage type. Your choice is then stored inside your browser in the cookies store.

With this post, I’ll try to explain to you, in a very brief way, the different types of browser storage that you can use while providing some code snippets to illustrate their usage. In the end, I’ll list references to posts with more details about this topic!

Cookies

Good old cookie. This is probably the most famous browser storage. Everyone who surfs the internet has heard about it. From this link:

Each cookie is effectively a small lookup table containing pairs of (key, data) values — for example (firstname, John) (lastname, Smith). Once the cookie has been read by the code on the server or client computer, the data can be retrieved and used to customise the web page appropriately.

It is easy to create or get a cookie. The document element contains an API to manipulate them. Here are some code examples:

// get all cookies
cookies = document.cookie;

// add a cookie
// must be a string with the format "key=value"
document.cookie = "pokemon=bulbasaur";

Local Storage

Local Storage is a type of web storage that stores data as a key/value pair structure and without expiration date. Even if the user ends their session, the data inside local storage will not disappear. The value stored can only be a string and if the user wants to store an object, they will need to stringify it when storing and JSON parse it when retrieving the value.

// get the storage
pokedex = window.localStorage;

// insert into store
pokedex.setItem('1', 'Bulbasaur');
pokedex.setItem('25', 'Pikachu');

// get from store
let pikachu = pokedex.getItem('25');
console.log(pikachu); // _Pikachu_

// remove from store
pokedex.removeItem('1');
let bulbasaur = pokedex.getItem('1');
console.log(bulbasaur); // _null_

// clear the store _aka_ reset pokedex
pokedex.clear();

Session Storage

Session storage is very similar to Local Storage. The main difference is that after the page session ends, the data inside the Session Storage is cleared. Both Local Storage and Session Storage have the same API. Just type pokedex = window.sessionStorage to access it.

IndexedDB

IndexedDB is a more complex type of storage, useful for storing larger amounts of data and complex objects. The API is much more complicated to use, compared to the ones provided by Cookies and Local/Session Storages. Because of that, there are libraries that make it easier to use. Like the other types of storage, you can store and retrieve elements using a key. For that, you’ll need to specify the database schema, open a connection and manipulate the data with transactions.

Here is a snippet of a very simple flow for using the browser IndexedDB:

// init IndexedDB
let request= window.indexedDB.open('POKEDEX', 1);

// to create an new object store, you must define
// a function to onupgradeneeded
request.onupgradeneeded = function(event) {
  let db = request.result;
  let store = db.createObjectStore('POKEMONS', { keyPath: 'pk'});
};

// store on DB
request= window.indexedDB.open('POKEDEX', 1);
request.onsuccess = function(event) {
  let db = request.result;
  let transaction = db.transaction('POKEMONS', 'readwrite');

  let store = transaction.objectStore('POKEMONS');

  store. **put** ({
   pk: 'pikachu',
   value: {
     number: 25,
     name: 'Pikachu',
     moves: {
       "move\_1": "Volt Tackle",
       "move\_2": "Tail Whip"
     }
   }
  });

  transaction.oncomplete = function() {
    db.close();
  }
}

// get object from the store
request= window.indexedDB.open('POKEDEX', 1);
request.onsuccess = function(event) {
  let db = request.result;
  let transaction = db.transaction('POKEMONS', 'read');
  let store = transaction.objectStore('POKEMONS');

  let pokemon = store.get('pikachu');
  pokemon.onsuccess = function(event) {
    console.log(pokemon.result.value);
  }
}

Because this is a complex process, even for small examples like the one above, there are libraries, like dexie.js, that help you use IndexedDB.

Conclusion

As you can see, browsers provide a variety of tools to store data for very specific cases. There is also another one called Web SQL but this one has been deprecated for a quite few years.

This is just a very small summary of those tools so please, take a look at some references below for more information.

References

Pokémon © 2002–2019 Pokémon. © 1995–2019 Nintendo/Creatures Inc./GAME FREAK inc. TM, ® and Pokémon character names are trademarks of Nintendo.

No copyright or trademark infringement is intended in using Pokémon content on this post.

I’m currently a Ruby-on-Rails developer at Runtime Revolution that still likes to play the good old Pokemon games for the GameBoy. Go check our website to know us more.


Top comments (0)