Information being stored on a user's computer is a very powerful strategy for a developer making cool things for the web. In this article we will look at how we can store information on the user's computer which the user can access after closing the browser weeks winged away into months,and months into years after the data was saved and also what it can be used for.
Before we get a detailed picture of what localstorage
is all about , I think it is highly recommended for you to know the difference between client-side storage
and server-side storage
in relation to websites and applications. Basically , Server-side
is an external means of storage which deals with pulling data from the server each time a request is made , using a database , while Client-side
on the other side is an internal means of storage, it consists of javascript APIs that allow you to store data in the browser(client).
Prerequisites
For you to get the best out of this article , it is important to know and have the following:
Basics of javascript ; aspect of javascript like defining
variables, object, array, function, JSON,DOM.You will also need an IDE(code editor) ; for example: Atom , sublime text , bracket , visual studio code.
For this article I will be using visual studio code which you can download here.A web browser.You can get google chrome via the link below , that's the browser that would be used in this article.
Google chrome can be downloaded here.
What Is localStorage?
local storage
, one of the web storage APIs
(a set of mechanisms that enables browsers to store key-value pairs) , is a storage mechanism that has data with no expiration date , data that will persist across browser sessions. It is found in a browser and not on a server. It can be compared to a large javascript object , where data is stored in a form known as key-value
pairs. The keys and values stored with localstorage
are always in the UTF-16 string format , which stores two bytes per character. One of the most amazing things about localstorage
is that we can do much more than just to store data , we can retrieve data or delete it with the help of localstorage
methods which will be discussed in details later in this article.
localStorage vs SessionStorage.
First of all,we must know that Web Storage API consists of two mechanisms:localStorage
and SessionStorage
which are similar in a way,they maintain a separate storage area for each document's
origin for the period of a browser session.
The main difference you should know is that SessionStorage
maintains storage only for the period the browser is active(open) while localStorage
retains data even when the browser is closed.In other words,SessionStorage
has expiring date(immediately the browser is closed) for it's data but localStorage
stores data for a long period of time(days,months,years) , and only loses the data if it is explicitly cleared by the user.
Technically , the
localStorage
read-only property of thewindow
interface allows you to access a Storage object for theDocument's
origin; the stored data is saved across browser sessions.
What Is Cookie?
A cookie is a text file hosted on the user's computer and connected to the domain that your website runs on. You can store information in them , read them out and delete them. Cookie has few limitation though:
- They allow up to only 4 KB of data storage.
- They add to the load of every document accessed on the domain.
- They are used to spy on people's surfing behaviour.Security-conscious users turn them off or request to be asked every time whether a cookie should be set.
Why Use localStorage?
The major problem with HTTP as a transport layer of the web is that it is stateless. This simply means that when you make use of an application and then close it , it's state will always be reset on next visit. As a developer , it is pertinent to store the user interface somewhere. Normally , this is done with the help of a server , using the username which serves as a key to know the exact state to retract. However , we know that it will be cumbersome to be implementing the signup method in static
applications or websites.
This is where localstorage comes in. You would need a key to know which state to revert to when the user returns.
Where Is localStorage?
For the aim of this article , I will be using chrome browser as I mentioned earlier in the Prerequisite
, it is pretty similar accessing the localStorage of any browser. We open the console
by right clicking in the browser and choosing the inspect option , then navigate to the Application
tab where we see Localstorage
by the left side under the storage
tab.
Something like this:
When we expand the LocalStorage
dropdown , we get this;
As we can see above , we have two columns namely Key
and Value
, which are normallly occupied with data , it is empty in this screenshot because i cleared the localstorage.
We can access the storage object by using Window.localStorage , and also fill up the two columns in the screenshot above by using some pre-defined
localStorage methods
. For accessing the storage we use this syntax:
//Accessing the localStorage
Window.localStorage
// or
localStorage
localStorage Methods
The localStorage
offers five methods that we can implement in our code , these methods aids the smooth use of localStorage
and enhances the CRUD
functionality , they are also pretty easy once you know the syntax for using each one of them. In this section we would practicalize these methods by using actual code once we get the syntax for each one of them. They are:
1.setItem()
:It is use to add key and the corresponding value to localStorage
.
2.getItem()
:This is the method used to retrieve value from localStorage
.
3.removeItem()
:Use to remove a particular value from localStorage
with the help of the corresponding key.
4.clear()
:use to empty thelocalStorage
.
5.Key()
:Passed a number to retreive the nth key of a localStorage
.
setItem(key,value)
//use to add something to localStorage
localStorage.setItem('key','value');
getItem(key)
//use to access a value in the localStorage
localStorage.getItem('key');
removeItem(key)
//use to remove a particular value in the localStorage
localStorage.removeItem('key');
clear()
//use to remove all the values in the localStorage
localStorage.clear();
We should do real practical of using these methods now,since we know the syntax for each.
Let's start by adding something to the localStorage
.
//adding value to empty localStorage
//open your code editor and run this code then check the localStorage
window.localStorage.setItem("cars","Ls-500");
One thing you should know as earlier mentioned , is that localStorage
can store data only in string format. Unfortunately , our data is in object form but localStorage
only store data in string format. There is an antedote
for this issue , which is the use of JSON
and it's methods , JSON.stringify()
and JSON.parse()
. When we want to store data , we convert to string using JSON.stringify()
and we convert string back to object on retrieving data using the JSON.parse()
method.
let's add more values to the localStorage using the setItem() method so we can understand better.
//storing data in object inside the localStorage
const programmer = {name:"Segun", age:12, language:"Javascript"}
const save = JSON.stringify(programmer);
localStorage.setItem("programmer",save);
Now the localStorage is occupied with more data and should look like this:
Note , we can continue to add up values to the localStorage
as long as the data saved does not exceed the max storage capacity of the localStorage
, which is 5MB
.
Moving to the next phase , let's retrieve the corresponding value of programmer
key. Don't forget we need to convert it back to object before we can retrieve it , which would be outputted by console logging it.
const saved = localStorage.getItem("programmer");
console.log(saved);
const retrieve = JSON.parse(saved);
console.log(retrieve);
Lastly , let's use the removeItem() to delete one of the values afterwhich we will use the clear method to empty the localStorage
:
Our localStorage
screenshot looks like this initially:
localStorage.removeItem("cars");
Running the above code using the removeItem() method , our localStorage should look like this now:
localStorage.clear();
Wow , see what we have:
Key()
I believe that you know index starts from zero in javascript.The first item in a list is accessed with index Zero.
//filling the localStorage , because the clear() method has emptied the localStorage
window.localStorage.setItem("cars","Ls-500");
const programmer = {name:"Segun", age:12, language:"Javascript"}
const save = JSON.stringify(programmer);
localStorage.setItem("programmer",save);
console.log(window.localStorage.key(0))//it retuens the first key in the localStorage which is `cars`;
The code above is accessing the key with index zero , meaning the first key in the localStorage
.
localStorage Browser Support
localStorage
, a type of web storage is supported across all major browsers. It is important for us to be sure that the browser we using supports localStorage
, this can be done by opening your browser console
and running the code below:
//localStorage browser support
if (typeof(Storage) !== "undefined") {
console.log("Browser supports localStoarge");
} else {
console.log("Browser does not support localStoarge");
}
You should have something like this if you run the code:
localStorage Limitations
There are two sides to a coin,definitely everything has it's own advantages and disadvantages.The following are limitations/disadvantages of localStorage
:
1.Limited Storage Capacity:localStorage
is limited to just 5MB data storage across all major browsers.
2.Insecure Data:localStorage
has no data protection , data in localStorage can be accessed easily on the webpage.It is susceptible to cross-site scripting(client-side code injection attack).
3.Synchronous Operation :localStorage
runs Synchronous Operation system,meaning operations runs step by step , one after the other.
4 Mode of Storage:localStorage
can only store data in string format , but this mode of storage might be cumbersome when working on a complex project.
Conclusion
In this article , I introduced you to what localStorage
is , why you need localStorage
, how you can access it in your browser , the methods it has and how you can implement them.Sensitive data should not be stored in the localStorage , use Server-Side storage instead.
If you find this article helpful as I anticipate , especially if you are just learning localStorage
for the first time , please kindly share.
Top comments (1)