The Local Storage is an internal database created into the browser, which you can use to save data in a key-value format. Most popular and commonly used browser like Chrome, Firefox and Safari all support Local Storage. The data stored in local storage has no expiration data, so it will persist over closed browser window and session.
Local storage has a very simple set, retrieve and remove API, and the key-value pair is always of string type.
If you’re using Chrome or Firefox, you can access local storage easily by using the console. Use the
localStorage object identifier.
And you can see the current content of the local storage through Application tab
The local storage can only be accessed when you go into the corresponding domain. The tab above is show when you access
Local storage methods
You can set data in local storage programatically by using the
localStorage.setItem(key, value). Try it in your dev console:
localStorage.setItem('a', 'Mickey'); localStorage.setItem('b', 'Minnie');
The syntax for retrieving data is
localStorage.getItem('a'); // returns Mickey localStorage.getItem('b'); // returns Minnie
To delete a key-value pair, use
localStorage.removeItem('a'); // remove Mickey localStorage.getItem('a'); // returns undefined
To delete all data in the current web domain, use
Limitations of local storage
- localStorage is not a safe database, and you should never use it for storing sensitive data.
- It’s max storage size 5 MB. Never store large amount of data in it.
- It’s synchronous
The most important thing to ask before storing data in the local storage is “Can malicious hackers do something while impersonating as the user with this value?”
If other people can authorize purchase and login into app and API, then it musn’t be saved in local storage.
Our fellow developer Randall Degges suggest not using local storage at all, but I’d say its find to use for local projects when you’re learning about framework or library.
You’ll see me use it on some of my tutorials.