Local Storage and Session Storage
Table of Contents
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
.
JAVASCRIPTlocalStorage.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:
JAVASCRIPTconst 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.
JAVASCRIPTconst restaurant = localStorage.getItem("restaurant");
console.log(restaurant);
HTMLchipotle
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.
JAVASCRIPTconst 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
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue