Session Storage and Local Storage APIs
And how you may not need an external database
Table of contents
Hi , Zenkin's here .
Usually for a growing application you'd need data , and thus must be stored somewhere . Now , you'd likely never want to set up a database if your data is really miniscule and small . Therefore in the newer web browsers , the Web Storage API features the Local and Session storages within your browser.
Data within browsers ?
Data within browsers may seem slightly insecure , but they are the best way to keep data that you would need often , like user's authentication data or session data . This may also be the case if fetching data from an external API can cost time .
Session Storage
As the name suggests , this storage persists until the browser tab is closed thus ending the page session .
The storage provides you with a 5MB limit which is reasonably larger than the cookies . To access the session storage , use the window.sessionStorage
.
Make sure you check if the API is present in the browser before using it as it may cause errors for older browsers
const SessionStorage = window.sessionStorage
if(SessionStorage){
SessionStorage.setItem("Item 1","I'm an item")
console.log(SessionStorage.length) // Outputs 1
SessionStorage.getItem("Item 1")
SessionStorage.removeItem("Item 1")
}
The process is really simple . setItem
sets a key-value pair , getItem
retrieves the specific item and so on. The drawback is that you can store the key and values in String format only. However , we can stringify other formats into JSON in order to store them .
const SessionStorage = window.sessionStorage
if(SessionStorage){
let user = {name:"Mark",age:10}
SessionStorage.setItem("User",JSON.stringify(user))
console.log(
JSON.parse(SessionStorage.getItem("User"))
) // {name: 'Mark', age: 10}
}
Local Storage
The local storage is almost the same as session storage , except that it persists even if the page is closed. They can be used in the same way as the session storage :
const LocalStorage = window.localStorage
if(LocalStorage){
let user = {name:"Mark",age:10}
localStorage.setItem("User",JSON.stringify(user))
console.log(
JSON.parse(localStorage.getItem("User"))
) // {name: 'Mark', age: 10}
}
Hopefully this guide helped you on utilizing the Storage API and how you can integrate them into your apps seamlessly .
Thanks for reading and happy coding ๐ฉโ๐ป !