Storage API
The web storage is a used to store data locally within the browser.
Uses of web storage:
- store user settings such as theme or language.
- use cache data to improve performance
- remember user actions or state
- can be used for implementing offline functionality - such as the state of a form
- storing client side tokens
localStorage
store data in key-value pairs
localStorage.setItem('key', 'value')
const value = localStorage.getItem('key')
localStorage.removeItem('key')
localStorage.clear()
Unlike cookies, which are sent to the server with every request, local storage data remains on the client side and is not automatically sent to the server. This provides faster access to stored information, reducing the need for frequent server requests and thereby improving website performance.
sessionStorage
store data in key-value pairs.
Only lasts as long as the browser window is open.
sessionStorage.setItem('key', 'value')
const value = sessionStorage.getItem('key')
sessionStorage.removeItem('key')
sessionStorage.clear()
Amount of storage allowed in browser storage: 5-10Meg
Local Cookies
Unlike cookies, which are sent to the server with every request, local storage data remains on the client side and is not automatically sent to the server. This provides faster access to stored information, reducing the need for frequent server requests and thereby improving website performance.
document.cookie = "cookeName1=cookieValue1"
document.cookie = "cookeName2=cookieValue2"
document.cookie = "cookeName3=cookieValue3"
const cookieValue = getCookie("cookieName3")
function getCookie( cookieName ) {
const cookies = document.cookie.split(";")
for (let i = 0; i < cookies.length; i++ ) {
const cookie = cookies[i].split("=")
if ( cookie[0] === cookieName ) {
return cookie[i]
}
}
}
Cookies
• If you need access stored data on the server-side
• When you want to do cross-domain data sharing
Web Storage
• If you need to store larger amounts of data
• For simpler and more efficient way to store and retrieve data compared to cookies.