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
Getting Started with TypeScript
Getting Started with Express
Create an RSS Reader in Node
Getting Started with Electron
How to deploy a .NET app using Docker
How to build a Discord bot using TypeScript
How to deploy a PHP app using Docker
How to deploy a MySQL Server using Docker
How to Scrape the Web using Node.js and Puppeteer
Creating a Twitter bot with Node.js
Using Push.js to Display Web Browser Notifications
Getting Started with Moon.js
