We've all heard of cache, local, and session storage. However, what precisely are they, what issues are they addressing, and how are they unique? In this write-up, we will discuss each of them. Stay tuned to this blog to learn about local storage, session storage, and cache storage.
With the introduction of HTML5, we now have various choices for storing information on the client browser. Before this, we only had a minimal cache with a very modest size. However, now we also have local storage and session storage.
The cache has been the buzz of the past, although it serves various functions.
Head-to-Head Comparison of Local, Session, and Cache Storage
Parameters | Local Storage | Session Storage | Cache Storage |
---|---|---|---|
Capacity | 10 Mb | 5 Mb | 4 Kb |
Browser | HTML5 | HTML5 | HTML4/HTML5 |
Accessible from | Any Window | Same tab | Any Window |
Expires | Never | On tab close | Manually set |
Storage location | Browser only | Browser only | Browser & Server |
Sent with requests | No | No | Yes |
What is Local Storage?
It is a technique for preserving the key-value combination in the web browser. The best thing about localStorage is that there is no expiration date, so the data will still be in the browser even if you refresh the page.
A Guide to Browser-Side Storage
Quokka Labs for Quokka Labs ・ Jan 12 '23
Where is localStorage stored?
Web storage data is saved in Google Chrome in an SQLite file in a subdirectory in the user's profile. The subdirectory is found at \AppData\Local\Google\Chrome\User Data\Default\Local on Windows computers and macOS /Library/Application Support/Google/Chrome/Default/Local Storage.
What is window.localStorage?
localStorage is available through windows.localStorage property is a component of the Window interface in Javascript that conveys the window holding the DOM Document.
How does localStorage work?
There are five ways you may use localStorage in your web applications:
- setItem(): It is to add key and value to the localStorage
- getItem(): Used to get items from the localStorage
- removeItem(): To remove an item by key from the localStorage
- clear(): It is used to clear all localStorage
- key(): Passed a number to retrieve the key of a localStorage
The above are the five ways or methods to use localStorage in your web application. Let's explore each respectively-
How to store values in localStorage using setItem()
This function lets you save values in the localStorage object, as the name would imply.
A key and a value are the two inputs. Later, we can retrieve the value associated with the key by referencing it.
window.localStorage.setItem('name', 'Anupam Singh');
Where Anupam Singh is the value and name is the key.
Note- Only strings are stored in localStorage.
You would need to transform arrays and objects into strings to save them.
Before submitting the data to setItem, we utilize the JSON.stringify() function to do this ().
const person = {
name: "Anupam Singh",
location: "Noida",
}
window.localStorage.setItem('user', JSON.stringify(person));
How to get items from localStorage using getItem()
The getItem() function is used to retrieve things from localStorage. The data kept in the localStorage object of the browser are accessed using the getItem() function.
The key is the only parameter that getItem() accepts and returns the result as a string.
To get a user key:
window.localStorage.getItem('user');
The above returns a string with the value:
“{“name”:”Anupam Singh”,”location”:”Noida”}”
Before using this value, you must transform it back into an object.
The JSON.parse() function, which turns a JSON string into a JavaScript object, is used to do this.
JSON.parse(window.localStorage.getItem('user'));
How to delete localStorage sessions using removeItem()
Use the removeItem() function to remove local storage sessions from the system.
The removeItem() function, when given a key name, deletes the key from the store if it is there. This approach will only be effective if the key provided has a linked item.
window.localStorage.removeItem('name');
How to delete all items in localStorage using clear()
To completely delete the localStorage of all items, use the clear() function.
When this approach is used, all the records for that domain's storage are entirely cleared. It receives no parameters at all.
window.localStorage.clear();
How to get the name of a key in localStorage using key()
The key() function lets you pass a number or index to localStorage to receive the name of the key and is useful when you need to loop over keys.
var KeyName = window.localStorage.key(index);
What is Session Storage?
Session storage is a type of storage specific to a single-user session on a web page. It allows data to be stored in key-value pairs and is typically used to keep data only required for a user's visit to a website, such as information entered into a form. When the user closes the web page or navigates to a different page on the website, the data in session storage is deleted. In contrast, local storage persists even after the user has closed the web page or browser.
As we know, the sessionStorage is a Storage type. Thus, you can manage the data using the 5 Storage methods.
- setItem(name, value) – It is used to set the value for a name.
- removeItem(name) – Used to remove the name-value pair identified by name.
- getItem(name) – Used to get the value for a given name.
- key (index) – It is used to get the name of the value in the given numeric position.
- clear () – To remove all values in the sessionStorage.
How to Store data in the sessionStorage using setItem()
Use the below code to store a name-value pair within the sessionStorage.
sessionStorage.setItem('mode','dark');
The setItem() function will change the value for the existing item to dark if the sessionStorage has an item with the name of the mode. Otherwise, a new item will be inserted.
How to remove an item by using removeItem()
Use the removeItem() method to remove an item. The 'mode' item is removed by doing the following:
sessionStorage.removeItem('mode');
How to get data from the sessionStorage using getItem()
The getItem() function retrieves an item's value by name. The value of the item "mode" is obtained in the example below:
const mode = sessionStorage.getItem('mode');
console.log(mode); // 'dark'
The getItem() method will return null if there is no item with the name mode.
How to Iterate over all items using the key()
Should follow these steps to iterate through every item in the sessionStorage:
- To retrieve all keys from the sessionStorage object, use object.keys().
- To obtain the items by keys and iterate through the keys, use for...of.
The steps are shown in the code below:
let keys = Object.keys(sessionStorage);
for(let key of keys) {
console.log(`${key}: ${sessionStorage.getItem(key)}`);
}
How to delete all items in the sessionStorage using clear()
When a web browser tab or window is closed, the data kept in the sessionStorage are automatically removed.
Additionally, one can programmatically delete any information kept in the sessionStorage by using the clear() function.
sessionStorage.clear();
What is Cache or Cookies Storage?
Before the introduction of HTML5, cookies were the sole option. Therefore, saving data with it is an old-fashioned method of doing so on the client system. It enables us to save client-side data to provide website visitors with a customized experience. These are sent to the server along with requests & back to the client after a response. Thus, the server and client exchange data whenever a request is made. The servers could deliver user-tailored content using the cookie data.
It may be created, edited, or read using JavaScript: document. Cookie. To address security risks, such as cross-site scripting, we have an HTTPOnly cookie setting that can limit cookie access in JavaScript.
Session cookies and persistent cookies are the two categories under which cookies fall.
Session Cookies
Expire, and Max-Age characteristics are not specified; as a result, they are removed when the browser is closed.
Persistent Cookies
Persistent cookies define the characteristic Expires or Max-Age. These will expire at a particular date (Expires) or period rather than upon quitting the browser (Max-Age).
Bottom Line
Another big factor to consider when deciding which storage to use is the application type you are building. For example, if your goal is to create a mobile app, localStorage would be the best choice because it will be available offline. If your application is online only and has no user interface to display dynamic data, then the cacheStorage is the one you should use. If you want your website to create a user profile, you should use the sessionStorage because it will clear out after a browser session ends.
Also Read
Top comments (0)