Web Storage is of fundamental importance in development as it replaces cookies in storing data in the browser. It is also safer and more recommended than browser cookies.
Web Storage has been around for a few years now, it came along with HTML5 which brought a lot of new features to web applications. However, today most programmers with more experience do not know and do not know its benefits.
In the past, I used cookies and sites had difficulty storing data in the browser because of the 5mb limitation and the sending of data in the header in each request with the server. There was the biggest problem with cookies: data crossed the network and could expose user data.
How the Web Storage API works
The storage API has 2 main classes to localStorage and the sessionStorage both classes have the same functions but work differently from each other.
The class sessionStorage it is used to keep data while the page is open, when the page is closed all saved data is erased. An example of using this class is to save shopping carts, configuration pages, sessions with sensitive data, checkout, etc.
while the class localStorage data is permanent and is deleted manually by the user or when the application executes one of the functions that remove data. In this sense, examples of saved information are the JWT, user id, date the user performed some action, etc.
Web Storage Functions
Web Storage classes have 4 functions and work on a key/value basis. Remembering that these functions work for both classes.
This function is used to add items to Web Storage.
sessionStorage.setItem(“animal”,”dog”); // Save dog with animal key.
This function returns the value saved in the key.
localStorage.getItem(“animal”); // Return animal key.
This function removes the key that has the name key.
sessionStorage.removeItem(“animal”); // Remove key and value with animal key.
This function removes all data saved in storage.
localStorage.clear(); // Clear all data
In summary, Web Storage came to replace cookies that will soon be discontinued by browsers. Soon every web programmer must learn to use these resources, their advantages and their variations.