Web Storage: Local Storage and Session Storage

Web Storage: Local Storage and Session Storage

The Web Storage API, which includes local storage and session storage, offers us a way to store key value pairs in a more intuitive way than using cookies, even though they all do similar things (store data client-side). With that being said, a major difference between cookies and web storage is that the server can read cookies from a user's browser, but cannot read from local/session storage directly. Therefore, the two have slightly different use cases.

Saving Data

Saving data using local storage is straightforward. You simply use the setItem method on the localStorage object. The parameters it takes are the key and values, just like cookies.

Let's save your favorite fast food restaurant as chipotle.

    localStorage.setItem("restaurant", "chipotle");

That's it. You have now saved an item with key restaurant with the value of chipotle locally.

Because the value has to be a string, you can use our friend JSON.stringify to convert a complex JavaScript object into a string suitable for use in local storage.

Here's how you save an object:

    var game = {
        "name": "Rocket League",
        "release": 2015,
        "developer": "Psyonix"
    var gameJSON = JSON.stringify(game);
    localStorage.setItem("game", gameJSON);

If you were to run this, you will have saved a JavaScript object in local storage.

Saving an item in Local Storage.
Saving an item in Local Storage.

To confirm, check your Application tab and look under Local Storage, and you should see what is shown in the image above.

Reading Data

Reading data from local storage is the same process as saving data, but in the reverse. Instead of setItem, you use getItem.

If you know the value isn't JSON, you can just read it without needing to parse anything.

    var restaurant = localStorage.getItem("restaurant");

In the case that you know the value is JSON, you just simply need to parse the value to get back your original JavaScript object.

    var gameJSON = localStorage.getItem("game");
    var game = JSON.parse(gameJSON);
Reading an item from Local Storage.
Reading an item from Local Storage.

You can make some pretty cool features built around local and session storage, you just need to figure out which one is best for you, and give it a shot.