📜 ⬆️ ⬇️

Why you should not use LocalStorage

Hi, Habr! I present to your attention the translation of the article " Please Stop Using Local Storage " by Randall Degges.


More and more developers use localStorage to store data, including confidential ones, without even knowing that they are thus hacking their sites. That is why I urge to abandon this practice, and in this article I will try to substantiate my point of view with arguments.


Introduction


image


So, localStorage is a new HTML5 feature that allows you to store any information in a user’s browser thanks to JavaScript. This is a good old JS object in which you can add and remove key / value pairs. Let's look at a small code example:


//     localStorage.userName = ""; localStorage.setItem("favoriteColor", ""); //    localStorage,    //   ,      alert(`${localStorage.userName}  ${localStorage.favoriteColor} .`); //       localStorage.removeItem("userName"); localStorage.removeItem("favoriteColor"); 

By running this code on a test HTML page, we’ll see the phrase "Peter prefers black color" in the alert window. If you go into the developer’s tools, having commented out the lines before deleting the data, you can make sure that both values ​​are saved in your browser’s local storage.


image


Now you may be interested in the following question: is there a way to use local storage so that the saved data is automatically deleted? Fortunately, the HTML5 developers took care of this by adding a global sessionStorage object that works exactly the same way as localStorage, except for one thing: all data stored in it is deleted when the user closes the browser tab.


Benefits


Although the whole point of this article is to discourage you from using localStorage, it still has a number of advantages.


First, it is pure javascript! One of the unpleasant things about cookies (which, in fact, are the only real alternative to local storage) is that they must be created by the server. The horror, because working with web servers is boring and time consuming. If you create a static site (for example, SPA), then using localStorage will allow it to work without any backend. This is a fairly powerful concept and one of the main reasons why this practice is popular with developers.


Another advantage is that localStorage has at least 5 MB of data storage (this size is supported by all major web browsers), which is an order of magnitude larger than cookie files (~ 4 KB). This gives a significant advantage if there is a need to cache a relatively large amount of application data in the browser for later use.


disadvantages


LocalStorage has a very simple API, many developers do not even realize how simple it is. Consider more:



It turns out that localStorage is a good tool only under certain conditions.


Security


The point is this: most of the minuses of local storage are insignificant. But the issue of security is a decisive factor, so let's talk about it in more detail.
So, localStorage is NOT SECURE ! Totally! Anyone who uses it to store sensitive data is doing the wrong thing.


Let's understand what is meant by confidential data:
- User IDs
- Session IDs
- JWT (JSON Web Token)
- Personal information
- Credit card information
- API keys
- Any other information that you would not publish publicly.

LocalStorage was not designed as a secure mechanism for storing data in the browser, but as a simple keystore and value store to facilitate the creation of small sites / web applications. And that's all. What do you think is the most dangerous thing in the world? Right! Javascript So when you want to keep something important in your local storage, imagine that you want to hide the most sensitive information in the most unreliable safe on the planet. Not the best idea.


In fact, the problem is cross-site scripting ( XSS ). I do not want to load you with a detailed explanation of this vulnerability, so I will try to explain briefly: if a hacker can run JavaScript code on your website, he will easily pull out all the information from localStorage and send it to his server, thereby acquiring, for example, data about the user session .
You can argue: "Oh, well? My site is safe. No one can run any script on my site." And here is the snag. In theory, you are absolutely right, but in fact this is virtually impossible to achieve. Let's see why.


Surely your website contains scripts that are loaded from other servers. The most common options are links to:
- Bootstrap
- jQuery
- Vue, React, Angular and others
- Google Analytics


Well, and so on. Then there is the likelihood that an attacker will be able to run a script on your site. Imagine that it contains the following code:


 <script src="https://awesomejslibrary.com/minified.js"></script> 

Suppose that awesomejslibrary.com is under attack, and the minifed.js script has also been modified. In this case, there is a risk that the script will collect all the data from localStorage and send it to a specially created to store the stolen information API. It turns out that hackers stole user data, while neither he nor you (as a developer) know about it. Bad option.


We all often think about the fact that all js-scripts need to be placed locally on their server, but in practice this happens rarely. In many companies, marketers can directly make changes to the site through WYSIWYG editors and other tools. This raises the question: are you really sure that your site does not use third-party JS anywhere? I will answer for you: no. Therefore, to reduce the risk of leakage of user information, do not store sensitive data in localStorage .


About tokens


Although it seems to me that I have quite convincingly explained why it is not worth storing confidential data in a local repository, it is worthwhile to separately clarify the situation with JSON Web Token (JWT). Many developers who store JWT in localStorage do not understand that this is essentially the same as the username / password.


If hackers copy these tokens , they will be able to send requests to your server, and you will never know about it. Therefore, treat them as you would with a credit card or password, namely, do not store in localStorage, despite thousands of tutorials, videos on Youtube and even programming courses at universities. This is wrong ! If someone advises you to store tokens in the local store for authentication, show them this article.


Alternatives


So, after we made sure that localStorage is far from an ideal solution for storing information, it’s time to get acquainted with alternatives.


Confidential data


To store such data, the only correct solution is a server-side session. The algorithm is as follows:



This simple and, most importantly, secure model. And, of course, with the help of it you can scale a project of any level.


Data other than strings


If you need to store information that is not confidential and that represents something more complicated than strings, then the best solution for this is IndexedDB. This is a transactional database system with a low-level API, which is a good option for storing various data (including files / blobs) directly in the browser. More information can be obtained from the guide from Google .


Offline data


To ensure the work of the application without connecting to the Internet, the best solution is to bundle IndexedDB with the Cache API (it is part of Service Workers), thanks to which it is possible to cache all the necessary resources for correct operation. An excellent tutorial on using Google is here .


Conclusion


I hope you understand now (understand?) Why it’s not always worth using localStorage. If you need to store data that is public, not used in high-performance applications, will not take up more than 5 MB, and consist only of rows, then local storage will be a good tool for your purposes.
In all other cases - do not use local storage ! Use alternative solutions.


And please, I just beg you, do not store session information (like JSON Web Token) in localStorage. This will make your website vulnerable to numerous attacks that harm users.


PS For those who wondered why I did not mention the Content Sequiriy Policy (CSP) as a way to protect against XSS. The reason is simple: it does not help in the situation that I described. Even if you use CSP to check all third-party domains, from where you are connecting JavaScript, it will not help if the site from the white list is hacked.


PPS Subresource integrity , unfortunately, is also not a solution. For most marketing tools, ad networks, etc. (which are the most common third-party scripts) subresource integrity is almost never used, since the suppliers of these scripts often change them to extend the functionality and other things.


Translation of the article Please stop using Local Storage .
Published with permission.


')

Source: https://habr.com/ru/post/349164/


All Articles