Many of us talk about this user side storage options but usually we don’t know the differences. So in this document we will try to clarify one of the most common frontend interview questions.
We all know that all three options are client side solutions for storing data in the browser as plain text (you can store more complex data structures like objects but you need to handle the parsing first), but not all options store that data for the same duration.
As the data is stored in plain text, these are not good solutions for storing sensitive data which can be easily accesed and modified by the user.
Also, as the data can be modified by the user, this storage options cannot be completely trusted as the user may remove them. It is the application responsiblity to handle the possibility that the values are not there any more.
Both sessionStorage and localStorage are kind of new APIs (introduced with HTML 5) while cookies have been arround since HTML 4.
Cookies are the best way of storing the user’s authentication data because are sent to the backend and then to the frontend again with each request, meaning that both sides can be sure of the users identity.
On the other hand, that the cookies are sent to the backend and back to the frontend means that they could be intercepted. It is not very common due to the use of SSL certificates but it is something to keep in mind.
Finally, the addition of the cookies to each request and response may make them a big heavier and slower than we want them to be, so we should keep only the necessary data.
Session and Local storage
Both sessionStorage and localStorage are identical, not only in how they are used and what they offer. They both store the data in the form of key/value pairs on the client side and can be accesed and modified from the browser’s terminal.
The most important difference between the two is the persistence duration:
- Session storage lasts the same as the session, so if you close the tab or the browser it is removed. It does survive page reloads.
- Local storage never expires, they will last until the application or the user manually removes them.
The way to set a key-value item is:
The way to get the value of an item is:
let data = sessionStorage.getItem("key");
let data = localStorage.getItem("key");
And finally to remove or clear the storage:
All three options are valid and good choices depending on the use case. The best way of identifying which one to use is to check for how long do you need that data and if you also need to use it in the backend.
Also, you may need to consider if storing data locally in the browser is a good decision as sometimes is more secure and controllable to store the data in a simple and fast database in the backend.