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.

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

That's it. You have now saved an item with the key restaurant and 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:

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

If you were to run this, you will have saved a JSON representation of a JavaScript object 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.

JAVASCRIPT
const restaurant = localStorage.getItem("restaurant"); console.log(restaurant);
HTML
chipotle

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.

JAVASCRIPT
const gameJSON = localStorage.getItem("game"); const game = JSON.parse(gameJSON); console.log(game);

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.

Resources

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.