The Ultimate Guide To localStorage in JavaScript
Cookies were the only way to store temporary and local information, but now we have localStorage. LocalStorage is widely discussed and used in a variety of Javascript applications. In this article, we’ll go over everything you need to know about localStorage in Javascript.
What is localStorage?
Imagine filling out a form online and your device disconnecting from the internet connection. You have filled out your name and age; all you have left to fill out is your country’s name and gender. You fill these out while you’re still disconnected from the Wi-Fi. The moment you reconnect to Wi-Fi, you submit the completed form.
When you entered your country’s name and gender without being connected to the internet, did you notice that you could log back in without losing your information? This is localStorage.
Window.localStorage
is a read-only property that stores data in the web browser without using a server-side language. Only Javascript is used. This data is explicitly stored in the domain and protocol being used. Also, the information is stored in key-value pairs in an SQLite file located in the user profile subfolder.
Among its uses are remembering the contents of a shopping cart, signing in to a website, and tracking whether a user enabled dark mode. This is because the data stored in localStorage does not expire. Additionally, it continues to store data after the browser is closed.
Using localStorage only for not-sensitive information is advisable because it is susceptible to Cross-Site Scripting (XSS) attacks and other Javascript-based attacks. In addition, localStorage data for a document that has been loaded in a “private browsing” or “incognito” session is cleared when the final “private” tab is closed.
Advantages of localStorage
There are many benefits to using localStorage. On top of the list is its ability to store data even after the browser is closed. The following is a list of some of its advantages:
- The data is stored using key-value pairs.
- The data stored does not expire.
- It holds information on the client side.
- Data is not automatically deleted unless Javascript code is used.
- Even after the browser is closed, it still keeps the data.
- With each HTTP request, sending data back and forth is unnecessary.
- It can store up to 5MB of data.
Disadvantages of localStorage
Utilizing localStorage has several benefits, but it also has some drawbacks. Here are a few of them:
- It should not be used to store private and important information because it is susceptible to Cross-Site Scripting (XSS) attacks.
- It has no data protection, making it accessible with any code.
- It can only contain strings but can be serialized with JSON.stringify().
- It cannot be accessed from different domains or subdomains.
Differences between Cookies and localStorage
Cookies are simply data stored in small text files on your device. It maintains the state of a user and remembers the user’s information on all web pages. Cookies and localStorage share these characteristics, but what distinguishes the two? Here are the differences between Cookies and localStorage:
Cookies | localStorage |
---|---|
It has an expiration date. | It has no expiration date. |
Cookies are read by the server. | They are only read by the browser. |
It has a maximum storage capacity of 4kB. | It has a maximum storage capacity of 5MB. |
Fairly susceptible to Cross-Site Scripting (XSS) and other Javascript-based attacks. | Highly susceptible to Javascript XSS attacks and other Javscript-based attacks. This is because localStorage was never intended to be secure. It has no data protection. |
It is fairly secure. | It is not secure at all. |
localStorage Syntax
This is the syntax of localStorage in Javascript:
localStorage Methods
There are four methods we use to work with localStorage. These include
*setItem()
: This method saves data to localStorage. It takes a key-value pair and adds it to localStorage.
getItem()
: This method reads data from the localStorage. It takes a key and returns the corresponding value.
removeItem()
: This method removes data from localStorage. It does so by taking a key and removing the corresponding key-value pair.
clear()
: This method clears localStorage from the domain.
Session Replay for Developers
Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data. Check our GitHub repo and join the thousands of developers in our community.
Application of localStorage
The best way to learn is to code and see how things work. We will use the four methods to understand how they work. Open your browser console and open the Developer’s Tools.
Enter the localStorage
, and the currently stored data will be returned (assuming it’s initially empty):
Enter localStorage.setItem('myKey', 'testValue')
. The string value will be stored in the key myKey
:
undefined
means that there was no value returned. Enter localStorage
again to view the data that is stored.
Enter localStorage.getItem('myKey')
, and the corresponding string will be returned:
Enter localStorage.removeItem('myKey')
to clear the corresponding key-value pair:
undefined
means no value is returned, showing that the key-value pair has been cleared. To confirm, enter localStorage
. The length returned is 0
.
Enter localStorage.clear()
to clear the localStorage
from the domain:
Conclusion
In this article, we’ve looked at localStorage and how to use it. Consider adding this tool to your coding!
Glossary
- Cross-Site Scripting (XSS) attacks. Cross-Site Scripting (XSS) attacks occur when malicious Javascript code is injected into a victim’s browser.
- Domain. A domain is equivalent to your website’s physical address.
- HTTP request. A Hypertext Transfer Protocol (HTTP) request occurs when a browser sends a “request” to a website’s server for information on a webpage.
- Key-value pair. This is a set of linked items: a unique identifier (key) and a value (value).
- Serializing. This procedure turns a data object into a stream of bytes so it can be transmitted or stored in memory.
- Server-side language. This is a programming language that performs tasks on the server side before the page is sent to the browser for rendering. Examples include Python, Golang, PHP, Ruby, Java, etc.
- Synchronous. This means the process runs only after other tasks are completed or handed off.
A TIP FROM THE EDITOR: For more on localStorage, don’t miss our A Guide To Using LocalStorage In JavaScript Apps and The Ultimate Guide To Browser-Side Storage articles