When you think of data persistence for your web application, I would be willing to bet that the first thing that comes to mind is cookies. You’re not wrong. Cookies are a very common way to save data within an application. In cases such as authentication when the data needs to be read by the server, they are absolutely the correct choice. However, in most other cases a better tool would be localStorage
or sessionStorage
.
So what are localStorage
and sessionStorage
? They are part of the web storage API and are used to store key-value pairs. By and large the two can be used interchangeably as they both perform the exact same function and utilize the exact same syntax. The primary difference between the two is how long the stored data persists. In the case of sessionStorage
, the data will persist only until the window or tab is closed. However, with localStorage
the data will persist until the browser cache is manually cleared, or until your code clears the data within your application. Since both localStorage
and sessionStorage
perform the same tasks, I am only going to refer to sessionStorage
from now on, and we will all just agree that I am talking about localStorage
as well. Remember, the syntax is the same!
sessionStorage
over cookies?There are a number of advantages to using sessionStorage
instead of cookies.
sessionStorage
is much greater. In most browsers this is 10Mb, as opposed to the 4Kb allowed in cookies. That’s 2500 times more storage capacity!sessionStorage
much easier to use.So now you are thinking, “This is amazing! If he would just give me some examples I could start using sessionStorage immediately!”
New sessionStorage
entries are created with the syntax sessionStorage.setItem
, and then assigning a key-value pair.
If you need to update an existing entry, the methodology is the same as creating a new entry. Use sessionStorage.setItem
, but instead of using a new key, use an existing key and input the new value. The existing key will now point to the updated value in sessionStorage
.
#sessionstorage #localstorage #cookies #javascript #web development