Randall Degges - Please Stop Using Local Storage (2024)

Randall Degges - Please Stop Using Local Storage (1)

Seriously. Just stop it already.

I don’t know what it is, exactly, that drives so many developers to storesession information in local storage,but whatever the reason: the practice needs to die out. Things are gettingcompletely out of hand.

Almost every day I stumble across a new website storing sensitive userinformation in local storage and it bothers me to know that so many developersare opening themselves up to catastrophic security issues by doing so.

Let’s have a heart-to-heart and talk about local storage and why you should stopusing it to store session data.

What is Local Storage?

Randall Degges - Please Stop Using Local Storage (2)

I’m sorry if I was a bit grumpy earlier. You don’t deserve that! Heck, you mightnot even be familiar with what local storage is, let alone be using it to storeyour session information!

Let’s start with the basics: local storage is a new feature of HTML5 thatbasically allows you (a web developer) to store any information you want in youruser’s browser using JavaScript. Simple, right?

In practice, local storage is just one big old JavaScript object that you canattach data to (or remove data from). Here’s an example of some JavaScript codethat stores some of my personal info in local storage, echoes it back to me, andthen (optionally) removes it:

// You can store data in local storage using either syntaxlocalStorage.userName = "rdegges";localStorage.setItem("favoriteColor", "black");// Once data is in localStorage, it'll stay there forever until it is// explicitly removedalert(localStorage.userName + " really likes the color " + localStorage.favoriteColor + ".");// Removing data from local storage is also pretty easy. Uncomment the lines// below to destroy the entries//localStorage.removeItem("userName");//localStorage.removeItem("favoriteColor");

If you run the JavaScript code above in your browser on a test HTML page, you’llsee the phrase “rdegges really likes the color black.” in an alert message. Ifyou then open up your developer tools, you’ll be able to see the that both theuserName and favoriteColor variables are both stored in local storage inyour browser:

Randall Degges - Please Stop Using Local Storage (3)

Now you might be wondering if there’s some way to use local storage so that thedata you store is automatically deleted at some point and you don’t need tomanually delete every single variable you put in there. Luckily, the HTML5working group (shout out!) has your back. They added something calledsessionStorage to HTML5 which works exactly the same as local storage exceptthat all data it stores is automatically deleted when the user closes theirbrowser tab.

What’s Cool About Local Storage?

Randall Degges - Please Stop Using Local Storage (4)

Now that we’re on the same page about what local storage is, let’s talk aboutwhat makes it cool! Even though the whole point of this article is to dissuadeyou from using local storage to store session data, local storage still has someinteresting properties.

For one thing: it’s pure JavaScript! One of the annoying things about cookies(the only real alternative to local storage) is that they need to be created bya web server. Boo! Web servers are boring and complex and hard to work with.

If you’re building a static site (like a single page app, for instance), usingsomething like local storage means your web pages can run independently of anyweb server. They don’t need any backend language or logic to store data in thebrowser: they can just do it as they please.

This is a pretty powerful concept and one of the main reasons that local storageis such a hit with developers.

Another neat thing about local storage is that it doesn’t have as many sizeconstraints as cookies. Local storage provides at least 5MB of data storageacross all major web browsers, which is a heck of a lot more than the 4KB(maximum size) that you can store in a cookie.

This makes local storage particularly useful if you want to cache someapplication data in the browser for later usage. Since 4KB (the cookie max size)isn’t a lot, local storage is one of your only real alternative options.

What Sucks About Local Storage

Randall Degges - Please Stop Using Local Storage (5)

OK. We talked about the good, now let’s spend a minute (or two!) talking aboutthe bad.

Local storage is soooo basic. WHEW. I feel better already getting that off mychest. Local storage is just an incredibly basic, simple API.

I feel like most developers don’t realize just how basic local storage actuallyis:

  • It can only store string data. Boo. This makes it pretty useless for storingdata that’s even slightly more complex than a simple string. And sure, youcould serialize everything including data types into local storage, butthat’s an ugly hack.

  • It is synchronous. This means each local storage operation you run will beone-at-a-time. For complex applications this is a big no-no as it’ll slow downyour app’s runtime.

  • It can’t be used by web workers=/ This means that if you want to build an application that takes advantage ofbackground processing for performance, chrome extensions, things like that:you can’t use local storage at all since it isn’t available to the webworkers.

  • It still limits the size of data you can store (~5MB across all majorbrowsers). This is a fairly low limit for people building apps that are dataintensive or need to function offline.

  • Any JavaScript code on your page can access local storage: it has no dataprotection whatsoever. This is the big one for security reasons (as wellas my number one pet peeve in recent years).

To keep it short, here’s the only situation in which you should use localstorage: when you need to store some publicly available information that is notat all sensitive, doesn’t need to be used in a high performance app, isn’tlarger than 5MB, and consists of purely string data.

If the app you’re using doesn’t fit the above description: don’t use localstorage. Use something else (more on this later).

Why Local Storage is Insecure and You Shouldn’t Use it to Store Sensitive Data

Randall Degges - Please Stop Using Local Storage (6)

Here’s the deal: most of the bad things about local storage aren’t all thatimportant. You can still get away with using it but you’ll just have a slightlyslower app and minor developer annoyance. But security is different. Thesecurity model of local storage IS really important to know and understand,since it will dramatically affect your website in ways you may not realize.

And the thing about local storage is that it is not secure! Not at all!Everyone who uses local storage to store sensitive information such as sessiondata, user details, credit card info (even temporarily!) and anything else youwouldn’t want publicly posted to Facebook is doing it wrong.

Local storage wasn’t designed to be used as a secure storage mechanism in abrowser. It was designed to be a simple string only key/value store thatdevelopers could use to build slightly more complex single page apps. That’s it.

What’s the most dangerous thing in the entire world? That’s right! JavaScript.

Think about it like this: when you store sensitive information in local storage,you’re essentially using the most dangerous thing in the world to store yourmost sensitive information in the worst vault ever created: not the best idea.

What the problem really boils down to is cross-site scripting attacks(XSS). I won’tbore you with a full explanation of XSS, but here’s the high level:

If an attacker can run JavaScript on your website, they can retrieve all thedata you’ve stored in local storage and send it off to their own domain. Thismeans anything sensitive you’ve got in local storage (like a user’s sessiondata) can be compromised.

Now, you might be thinking “So what? My website is secure. No attacker can runJavaScript on my website.”

And that’s a reasonable point. If your website is truly secure and no attackercan run JavaScript code on your website then you are technically safe, but inreality that is incredibly hard to achieve. Let me explain.

If your website contains any third party JavaScript code included from asource outside your domain:

  • Links to bootstrap
  • Links to jQuery
  • Links to Vue, React, Angular, etc.
  • Links to any ad network code
  • Links to Google Analytics
  • Links to any tracking code

Then you are currently at risk for having an attacker run JavaScript on yourwebsite. Let’s say your website has the following script tag embedded inside it:

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

In this case, if awesomejslibrary.com is compromised and their minified.jsscript gets altered to:

  • Loop through all data in local storage
  • Send it to an API built to collect stolen information

… then you are completely screwed. In this situation the attacker would haveeasily been able to compromise anything you had stored in local storage and youwould never notice. Not ideal.

As engineers, I think we’re frequently susceptible to thinking that we wouldnever embed third party JavaScript in our websites. But in the real world, thisscenario rarely plays out.

At most companies the marketing team directly manages the public website usingdifferent WYSIWYG editors and tooling. Can you really be sure that nowhere onyour site are you using third party JavaScript? I’d argue “no”.

So to err on the side of caution and dramatically reduce your risk for asecurity incident: don’t store anything sensitive in local storage.

PSA: Don’t Store JSON Web Tokens in Local Storage

Randall Degges - Please Stop Using Local Storage (7)

While I feel like I made myself clear that you should never ever storesensitive information in local storage in the previous section, I feel the needto specifically call out JSON Web Tokens (JWTs).

The biggest security offenders I see today are those of us who store JWTs(session data) in local storage. Many people don’t realize that JWTs areessentially the same thing as a username/password.

If an attacker can get a copy of your JWT,they can make requests to the website on your behalf and you will never know.Treat your JWTs like you would a credit card number or password: don’t everstore them in local storage.

There are thousands of tutorials, YouTube videos, and even programming classesat universities and coding bootcamps incorrectly teaching new developers tostore JWTs in local storage as an authentication mechanism. THIS INFORMATIONIS WRONG. If you see someone telling you to do this, run away!

What to Use Instead of Local Storage

Randall Degges - Please Stop Using Local Storage (8)

So with all of local storage’s shortcomings, what should you use instead? Let’sexplore the alternatives!

Sensitive Data

If you need to store sensitive data, you should always use a server-sidesession. Sensitive data includes:

  • User IDs
  • Session IDs
  • JWTs
  • Personal information
  • Credit card information
  • API keys
  • And anything else you wouldn’t want to publicly share on Facebook

If you need to store sensitive data, here’s how to do it:

  • When a user logs into your website, create a session identifier for them andstore it in a cryptographically signed cookie. If you’re using a webframework, look up “how to create a user session using cookies” and followthat guide.

  • Make sure that whatever cookie library your web framework uses is setting thehttpOnly cookie flag. This flag makes it impossible for a browser to readany cookies, which is required in order to safely use server-side sessionswith cookies. Read Jeff Atwood’s articlefor more information. He’s the man.

  • Make sure that your cookie library also sets the SameSite=strict cookie flag(to prevent CSRFattacks), as well as the secure=true flag (to ensure cookies can only beset over an encrypted connection).

  • Each time a user makes a request to your site, use their session ID (extractedfrom the cookie they send to you) to retrieve their account details fromeither a database or a cache (depending on how large your website is)

  • Once you have the user’s account info pulled up and verified, feel free topull any associated sensitive data along with it

This pattern is simple, straightforward, and most importantly: secure. Andyes, you can most definitely scale up a large website using this pattern. Don’ttell me that JWTs are “stateless” and “fast” and you have to use local storageto store them: you’re wrong!

Non-String Data

If you need to store data in the browser that isn’t sensitive and isn’t purelystring data, the best option for you is IndexedDB. It’s an API that lets youwork with a database-esque object store in the browser.

What’s great about IndexedDB is that you can use it to store typed information:integers, floats, etc. You can also define primary keys, handle indexing, andcreate transactions to prevent data integrity issues.

A great tutorial for learning about (and using) IndexedDB is thisGoogle tutorial.

Offline Data

If you need your app to run offline, your best option is to use a combination ofIndexedDB (above) along with the Cache API (which is a part of Service Workers).

The Cache API allows you to cache network resources that your app needs to load.

A great tutorial for learning about (and using) the Cache API is thisGoogle tutorial.

Please Stop Using Local Storage

Randall Degges - Please Stop Using Local Storage (9)

Now that we’ve had a chance to talk about local storage, I hope you understandwhy you (probably) shouldn’t be using it.

Unless you need to store publicly available information that:

  • Is not at all sensitive
  • Doesn’t need to be used in an ultra high performance app
  • Isn’t larger than 5MB
  • Consists of purely string data

don’t use local storage! Use the right tool for the job.

And please, please, whatever you do, do not store session information (like JSONWeb Tokens) in local storage. This is a very bad idea and will open you up to anextremely wide array of attacks that could absolutely cripple your users.

Have a question? Shoot me an email.

Stay safe out there =)

NOTE: For those of you who made it this far who are wondering why I didn’tspecifically call out Content Security Policyas a way to mitigate the effects of XSS, I specifically chose not to includethis because it cannot help in the situation I described above. Even if you useCSP to whitelist all third party JavaScript domains, that does nothing toprevent XSS if the third party provider is compromised.

And while we’re at it: subresource integrity(while cool) is also not a global solution to this issue. For most marketingtools, ad networks, etc. (which are by far the most commonly used types ofthird party JavaScript), subresource integrity is almost never used as theproviders of those scripts want to change them frequently so they cansilently update functionality for their users.

UPDATE: I’m not the only one who thinks you should never store anythingsensitive in local storage. So does OWASP:

… In other words, any authentication your application requires can bebypassed by a user with local privileges to the machine on which the data isstored. Therefore, it’s recommended not to store any sensitive information inlocal storage.

PS: If you read this far, you might want to follow me on Bluesky or GitHub and subscribe via RSS or email below (I'll email you new articles when I publish them).

Randall Degges - Please Stop Using Local Storage (2024)

FAQs

What to use instead of local storage? ›

While localStorage serves as a reliable storage solution for simpler data needs, it's essential to explore alternatives like IndexedDB when dealing with more complex requirements. IndexedDB is designed to store not only key-value pairs but also JSON documents.

What is the limit of local storage? ›

LocalStorage should be avoided because it is synchronous and will block the main thread. It is limited to about 5MB and can contain only strings.

What is the problem with localStorage? ›

The Limitations of localStorage:

Malicious scripts injected into a website can easily access and manipulate data stored in localStorage , compromising sensitive user information. Limited Storage Capacity: localStorage has a relatively small storage capacity (usually around 5 MB per domain).

How do I free up local storage? ›

  1. Select Start > Settings > System > Storage > Cleanup recommendations. Open Storage settings.
  2. Select the temporary files, unused files, files synced to the cloud, or unused apps you want to remove, then select the Clean up button for each section.

How do I free up local storage on Android? ›

  1. Close apps that don't respond. You don't usually need to close apps. ...
  2. Uninstall apps you don't use. If you uninstall an app and need it later, you can download it again. ...
  3. Clear the app's cache & data. You can usually clear an app's cache and data with your phone's Settings app.

When not to use local storage? ›

One of the main drawbacks is security issues. Since Local Storage is stored locally within the user's browser, it is vulnerable to malicious attacks. For example, malicious attackers can access the data stored in Local Storage and use it for malicious purposes. Another disadvantage of Local Storage is data loss.

What are the disadvantages of local storage? ›

However, local storage also has some disadvantages: No automatic expiration. Local storage does not have an expiration mechanism and must be deleted or updated manually. This isn't convenient for web developers and could violate compliance with the privacy laws.

Can local storage be turned off? ›

A local storage can only be disabled together with cookies. Open “Settings” –> “Privacy and Security” tab. Find Cookies section and select “Block sites from setting any data”.

What happens when localStorage is full? ›

When you try to store data in localStorage, the browser checks whether there's enough remaining space for the current domain. If yes: The data is stored, overwriting values if an identical key already exists.

How do I enable local storage? ›

Google Chrome/Chromium
  1. Click on the menu button in the top-right corner of your Chrome window.
  2. Select “Settings” from that menu.
  3. Click “Cookies and site permissions”.
  4. Click on “Cookies and site data”.
  5. Toggle on the setting for “Allow sites to save and read cookie data (recommended)”.

Does local storage expire? ›

localStorage is similar to sessionStorage , except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed.

What is a secure alternative to local storage? ›

A more secure alternative for storing sensitive user data would be by using backend cookies, which prevents malicious XSS attacks notably due to their httpOnly flag.

Why shouldn't you use localStorage? ›

Synchronous Blocking Operations: localStorage is not asynchronous and will block the main thread. It may even make your animations choppy depending on how much you read/ write and at what frequency. Asynchronicity is fundamental to creating fluid applications, especially for mobile devices.

Why use cookies instead of localStorage? ›

Conclusion. Both cookies and localStorage are vulnerable to XSS attacks. However, cookie-based token storage is more likely to mitigate these types of attacks if implemented securely. The OWASP community recommends storing tokens using cookies because of its many secure configuration options.

What is the cheapest method of storage? ›

The 9 cheapest storage options
  1. Rent a portable storage container. ...
  2. Go with self-storage. ...
  3. Use an online storage marketplace. ...
  4. Buy a used overseas container. ...
  5. Use a consignment shop for temporary storage. ...
  6. Store items at your home or business. ...
  7. Ask a friend to use their extra space. ...
  8. Make a temporary donation.
Jun 25, 2024

Top Articles
What causes high gas prices in the US?
A rising dollar spells trouble for investors | Fidelity UK
Poe T4 Aisling
55Th And Kedzie Elite Staffing
Using GPT for translation: How to get the best outcomes
Select The Best Reagents For The Reaction Below.
Ladyva Is She Married
Sarpian Cat
Calmspirits Clapper
Available Training - Acadis® Portal
Hilo Hi Craigslist
Po Box 35691 Canton Oh
R Personalfinance
Keurig Refillable Pods Walmart
Teacup Yorkie For Sale Up To $400 In South Carolina
Masterkyngmash
All Obituaries | Gateway-Forest Lawn Funeral Home | Lake City FL funeral home and cremation Lake City FL funeral home and cremation
Sec Baseball Tournament Score
Craigslist Rome Ny
Maisons près d'une ville - Štanga - Location de vacances à proximité d'une ville - Štanga | Résultats 201
Taylored Services Hardeeville Sc
Shoe Station Store Locator
lol Did he score on me ?
Stouffville Tribune (Stouffville, ON), March 27, 1947, p. 1
Que Si Que Si Que No Que No Lyrics
2015 Chevrolet Silverado 1500 for sale - Houston, TX - craigslist
Mgm Virtual Roster Login
Marie Peppers Chronic Care Management
Metra Schedule Ravinia To Chicago
Craigslist Mount Pocono
Pitchfork's Top 200 of the 2010s: 50-1 (clips)
Cherry Spa Madison
Cox Outage in Bentonville, Arkansas
Walgreens Agrees to Pay $106.8M to Resolve Allegations It Billed the Government for Prescriptions Never Dispensed
Qlima© Petroleumofen Elektronischer Laserofen SRE 9046 TC mit 4,7 KW CO2 Wächter • EUR 425,95
Differential Diagnosis
Walgreens On Secor And Alexis
Grand Valley State University Library Hours
Ghareeb Nawaz Texas Menu
Value Village Silver Spring Photos
New Starfield Deep-Dive Reveals How Shattered Space DLC Will Finally Fix The Game's Biggest Combat Flaw
Lesson 5 Homework 4.5 Answer Key
Rovert Wrestling
Online TikTok Voice Generator | Accurate & Realistic
Craigslist Sarasota Free Stuff
How to Do a Photoshoot in BitLife - Playbite
Elvis Costello announces King Of America & Other Realms
Diamond Spikes Worth Aj
Morgan State University Receives $20.9 Million NIH/NIMHD Grant to Expand Groundbreaking Research on Urban Health Disparities
Coldestuknow
Dr Seuss Star Bellied Sneetches Pdf
Kindlerso
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 5507

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.