Please Stop Using Local Storage

rdegges profile image Randall Degges Originally published at rdegges.com ・11 min read

Grumpy Rage Face

Seriously. Just stop it already.

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

Almost every day I stumble across a new website storing sensitive user information in local storage and it bothers me to know that so many developers are 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 stop using it to store session data.

What is Local Storage?

HTML5 Local Storage

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

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

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

// You can store data in local storage using either syntax
localStorage.userName = "rdegges";
localStorage.setItem("favoriteColor", "black");

// Once data is in localStorage, it'll stay there forever until it is
// explicitly removed
alert(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

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

Local Storage Inspector

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

What's Cool About Local Storage?

Happy Rage Face

Now that we're on the same page about what local storage is, let's talk about what makes it cool! Even though the whole point of this article is to dissuade you from using local storage to store session data, local storage still has some interesting 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 by a 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), using something like local storage means your web pages can run independently of any web server. They don't need any backend language or logic to store data in the browser: they can just do it as they please.

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

Another neat thing about local storage is that it doesn't have as many size constraints as cookies. Local storage provides at least 5MB of data storage across 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 some application 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

Frowning Rage Face

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

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

I feel like most developers don't realize just how basic local storage actually is:

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

  • It is synchronous. This means each local storage operation you run will be one-at-a-time. For complex applications this is a big no-no as it'll slow down your app's runtime.

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

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

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

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

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

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

Stick Figure Instructor

Here's the deal: most of the bad things about local storage aren't all that important. You can still get away with using it but you'll just have a slightly slower app and minor developer annoyance. But security is different. The security 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 session data, user details, credit card info (even temporarily!) and anything else you wouldn't want publicly posted to Facebook is doing it wrong.

Local storage wasn't designed to be used as a secure storage mechanism in a browser. It was designed to be a simple string only key/value store that developers 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 your most 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't bore 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 the data you've stored in local storage and send it off to their own domain. This means anything sensitive you've got in local storage (like a user's session data) can be compromised.

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

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

If your website contains any third party JavaScript code included from a source 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 your website. 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.js script 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 have easily been able to compromise anything you had stored in local storage and you would never notice. Not ideal.

As engineers, I think we're frequently susceptible to thinking that we would never embed third-party JavaScript in our websites. But in the real world, this scenario rarely plays out.

At most companies, the marketing team directly manages the public website using different WYSIWYG editors and tooling. Can you really be sure that nowhere on your 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 a security incident: don't store anything sensitive in local storage.

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

Stick Figure with Stop Sign

While I feel like I made myself clear that you should never ever store sensitive information in local storage in the previous section, I feel the need to 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 are essentially 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 ever store them in local storage.

There are thousands of tutorials, YouTube videos, and even programming classes at universities and coding boot camps incorrectly teaching new developers to store JWTs in local storage as an authentication mechanism. THIS INFORMATION IS WRONG. If you see someone telling you to do this, run away!

What to Use Instead of Local Storage

Pointing Man

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

Sensitive Data

If you need to store sensitive data, you should always use a server-side session. 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 and store it in a cryptographically signed cookie. If you're using a web framework, look up “how to create a user session using cookies” and follow that guide.

  • Make sure that whatever cookie library your web framework uses is setting the httpOnly cookie flag. This flag makes it impossible for a browser to read any cookies, which is required in order to safely use server-side sessions with cookies. Read Jeff Atwood's article for more information. He's the man.

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

  • Each time a user makes a request to your site, use their session ID (extracted from the cookie they send to you) to retrieve their account details from either 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 to pull any associated sensitive data along with it

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

Non-String Data

If you need to store data in the browser that isn't sensitive and isn't purely string data, the best option for you is IndexedDB. It's an API that lets you work 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, and create transactions to prevent data integrity issues.

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

Offline Data

If you need your app to run offline, your best option is to use a combination of IndexedDB (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 this Google tutorial.

Please Stop Using Local Storage

Happy Rage Face

Now that we've had a chance to talk about local storage, I hope you understand why 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 JSON Web Tokens) in local storage. This is a very bad idea and will open you up to an extremely 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't specifically call out Content Security Policy as a way to mitigate the effects of XSS, I specifically chose not to include this because it cannot help in the situation I described above. Even if you use CSP to whitelist all third-party JavaScript domains, that does nothing to prevent 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 marketing tools, ad networks, etc. (which are by far the most commonly used types of third-party JavaScript), subresource integrity is almost never used as the providers of those scripts want to change them frequently so they can silently update functionality for their users.

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

... In other words, any authentication your application requires can be bypassed by a user with local privileges to the machine on which the data is stored. Therefore, it's recommended not to store any sensitive information in local storage.

Posted on by:

rdegges profile

Randall Degges


I'm just a happy programmer that likes to hack stuff.


markdown guide

While some of your points are correct, suggesting to use sessions and cookies instead of JWT is missing the point.
People using JWTs are most probably running a SPA and communicating with a pure stateless API. We don’t want to hear about sessions in this case.

Storing a JWT in the cookies is perfectly OK and it has the advantage of not needing custom JS code to pass it to each HTTP request to your backend.
But in some situations, like when your API is also used by your mobile app and it requires the "Authorization Bearer xxx" header instead of a cookie or when you’re making HTTP requests to multiple backends but with same JWT, it’s convenient to have your JWT in localStorage instead.

Also, most modern JS frameworks (React, Angular, ...) nowadays produce concatenated and minified vendor scripts so you don’t have to include single scripts from third party locations.


Hey, this is a great point. But hear me out.

Let's say you want to store a JWT in a cookie -- that's fine. BUT: the purpose of JWTs is to be stateless, right? Cookies are capped out at 4k, which means the JWT needs to be < 4k for this to work.

Most stateless JWTs are > 4kb (this is quite easy to test, serialize a user from your DB into a compact'd JWT and look at the byte size -- I've done this on a lot of sample apps and in almost every case except the most simple the JWT is > 4kb). In this scenario, you've basically got to use local storage.

Instead of doing that: why not just use a session cookie as I recommended? The downside is that you need to manage a cache on the API side, but this is easily doable. If you're using JWTs anyway (with local storage, let's say), you STILL NEED to have centralized sessions in some way to manage revocation.

JWTs are insecure by design: they cache authentication/authorization data, so in order to work around their speed-vs-security tradeoff you've got to manage a revocation list centrally no matter what: otherwise you end up in situations where revoked permissions/data are being allowed through -- a poor scenario.

Now, let's talk about your point about using the Authorization header. I hear this a lot: I think I will write another article about it as it's a common misconception.

There is NO DIFFERENCE between sending auth data to a server in the Authorization header (with a bearer token) vs sending it to the server using a cookie. COokies are just HTTP headers as well. The difference is a few characters:

Authorization: Bearer <token>
Cookie: session=<signed(id)>

Any server can parse either header. While you may not want to for some reason, there is nothing technical or bad about using a cookie for this purpose.

I'd argue that the ONLY reason you need to use a JWT for auth is if you're using OpenID Connect, as for some reason the authors of the spec decided to standardize on JWTs for the ID token. In this case, using the JWT and putting it into an Authorization is actually required -- outside this case? Not at all.

And re: scripts being minified/included... This does not apply to the biggest use case I mentioned in the article: third party tools. Things like GA, Optimizely, Kissmetrics, and all the other marketing/ad network tools that most companies use.

There are definitely scenarios in which you can make yourself safe from XSS, but those situations are increasingly rare.

As always, this article is only meant to provide guidance to the 99% of people who do this stuff blindly without thinking about it. In your case, you likely know the risk profile for what you're doing and can decide whether or not you want to take the risk.


One problem with the article is that the words 'never' and 'always' are used way too often.

Also, the article says that localStorage is insecure quite often but doesn't give any evidence or examples.

I would argue that localStorage is as secure as cookies (including httpOnly cookies).

localStorage uses essentially the same security policy as cookies; one of its core principles is that a domain cannot access localStorage data that was created under a different domain so there is no chance that a website could steal data from a different website.

Also, httpOnly cookies do not make your site any less vulnerable to XSS attacks; if the attacker manages to inject a malicious script into your front end, then they can use that script to make HTTP requests to your server (directly from the victim's browser) and your precious httpOnly cookie (containing the user's valid session ID) will be attached to every request so the server will service them without suspecting anything.

The only real difference is that if the token (e.g. JWT) is in localStorage then the attacker can steal the token to use later (same goes for regular non-httpOnly cookies BTW)... Which is hardly a convenience because it's more advantageous for the attacker to carry-out the attack in-place from the victim's browser rather than from the attacker's own machine (thus allowing their IP to be traced directly).

Also, with JWTs, it's good practice to set short expiry dates. If you're using WebSockets you can even issue JWTs with 10 minute expiry (for example) and re-issue a new one automatically every 8 minutes if the user is still connected and logged in; then when the user logs out or becomes disconnected; their last issued JWT will become invalid in only 10 minutes (at which point it becomes completely useless to an attacker).

Also, it's not recommended practice to store large amounts of data inside a JWT because of the overhead of having to send it with every request/connection.

woow this is one of the best comments in this post.

Indeed the original article totally misses the point that local storage is by no means less secure than any other part of your website. If you have an XSS, you are flawed. That's actually the reason why XSS attacks are so serious/bad.

If you fetch from the browser, you don't get cookies. You have to add {credentials: "include"}. And that requires a whitelisting on the server. So no, it's no so easy to get httpOnly cookie content in browser as you describe. It requires a TRACE method or other known vulnerability or bug to expose them. Pls. prove me wrong if you think otherwise.

Other than that, I agree with your point. When an app has an XSS injection there are tons of attack vectors a hacker can take. And yes, localStorage is almost the same as cookies security-wise. This article is mostly a FUD, unfortunately.

His point was that you don't need to read the cookie if you can send requests when the user is on the compromised website.


you've got to manage a revocation list centrally

This might be true for Google or Amazon but is not actually true for the majority of applications out there I would argue.

You find out a token is compromised? Just regenerate your signing key. Yes every application user will have to log in again but that is a perfectly acceptable action for most applications.


Content-security-policy for XSS + subresource integrity hashes for third party hosted libraries, or just compile in the third party tool like google analytics, e.g. npmjs.com/package/analytics

There are many improvements being made to the security of single page applications (HSTS en.wikipedia.org/wiki/HTTP_Strict_..., certificate transparency en.wikipedia.org/wiki/Certificate_...) that make storing sensitive information in JS about as safe as storing them in a mobile app.


I don't think you understand that APIs don't scale with sessions maintained on server side. That's why we no longer use session cookies. Storing JWT in http only cookies is not perfect, but ok from scalability perspective.


JWTs aren't inherently unsafe. I like that JWTs are signed by a server side secret, and I like the flow that creates during auth. Depending on how secure the app needs to be, I've even stored user agent and remote address info in a JWT, signing it with a user specific secret. I had the JWT checked for all of that as accurate against headers and then refreshed the sign/verify secret if the JWT had data that was bad in it.

Most apps can get away with an expiry on a JWT and increase performance, this decreasing energy usage, this decreasing environmental impact of your code.

The CIA of information (Confidentiality, Integrity, Availability) is held strong. OP only focuses on Confidentiality for some reason.


I think you’re misreading him. He doesn’t say “don’t use JWT” he’s just saying “don’t stick your JWT in local storage”.

Yes, it’s convenient. It’s also convenient to just leave the key to my house in the lock, but it means anyone who can get to the door can get in.


JWTs are insecure by design

Considering JWT are most likely used for security, it is pretty much urging not to use them. Unless you need a token for accessing public data.

Many people don't realize that JWTs are essentially the same thing as a username/password.

This one is a stretch and if you go this way, then that is true for pretty much everything used for security nowadays. It is true for cookies. It is true for SSH keys, etc. Any written access that replaces your password can be exploited in a way or another.

Your example with keys is interesting because even if it is not bulletproof, then you are better off typing your password on each request. Except it's not practical.

Don't get me wrong, the article is interesting and everybody should understand the danger of all these practices. But then people will be waiting for the alternative. And mentioning an alternative is the worst thing to do because people will prove you wrong, because nothing is unbreakable.

You're better off warning and help them make sure they are making their best to secure the way they use the current tool.


Here's a question: in what contexts do SPAs need to use bearer token auth, and is this truly an ideal?

There's only one class of SPAs which CAN'T use cookie auth -- namely, SPAs using a statically served application shell. This is an architectural decision with a lot of tradeoffs to it. On the plus side S3 is cheap, there's a certain theoretical purity to having your web frontend go #serverless, and you only need to maintain one form of API authentication. On the minus side, you have to greenspin literally everything that the browser gives you for free.... like the nice security properties of cookie auth.

There's nothing wrong with maintaining a simple, stupid edge service that exists to maintain sessions & proxy requests to your API. It feels pretty oldschool, but it works pretty well. And if (when) your web frontend winds up wanting a sliiiiightly different API than your mobile app, having an edge service already in place makes that trivial! Most existing SSR frameworks (Next, Nuxt...) can serve this purpose without too much modification of an existing app-shell-style SPA.


You can work around statically served apps and authentication if you use a concept of an API gateway like Kong. I my case statically served apps are only allowed to go through a Kong like service...in which we can control authentication, rate limiting etc


Good article and good awareness. However....

Quote: "If an attacker can run JavaScript on your website, they can retrieve all the data you've stored in local storage and send it off to their own domain."

Edit: "If an attacker can run JavaScript on your website, you're ka-pooched, and a local jwt is the least of your worries."


"If an attacker can run JavaScript on your website, you're ka-pooched, and a local jwt is the least of your worries."

Have you ever used jQuery or any other 3rd party JS library on your site? How certain are you that that 3rd party does nothing malicious? How certain are you that 3rd party library hasn't been compromised?

Not even the library: if you're using one, you're probably pulling from a CDN right? How certain are you that CDN hasn't been compromised to serve a different version of the library than what you think you're getting?


"How certain are you that that 3rd party does nothing malicious?"

I'm not very certain. But you're missing the point. If the library is tainted, what can it do? Much, much worse than the worst case scenario here. That's the point. It's like duct tape to fix the titanic. It's like humans in a Marvel movie. Useless.

Just like Xavier, a compromised lib can mind-control the poop out of your app and wreak havoc for your users, and there's nothing you can do about it. XSS is a security rabbit hole.

When you understand what a tainted lib can do, you realize how trivial this article's point is. That is my only point.

Part of the problem with the proposed solution in this article is that cookies are tied to a specific domain. That makes it much harder and clunky to use third party security services like Auth0. Also, scalability does become a MUCH harder issue with server-side sessions; I don't care what this article says.

Best idea to overcome your tainted paranoia is to use script's integrity attribute, eg:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script>

Yep, it seems to me that people started working with microframeworks on nodejs etc. thinking they understood what they were doing, then realized they're missing all the convenient features they used to have and didn't have a clue of how they were implemented so they just picked some things that sounded cool (JWT & localStorage) and went with those without even a single second of thought as to "why isn't everyone doing this?" or similar.

Secure information, such as session information, should almost universally be stored in httpOnly & secure cookies, potentially with SameSite=strict. I just don't see any reason for JS to touch the cookies in general, just use a /me endpoint or similar to check if you're logged in and to fetch your user's information so you don't need to touch the secure cookies.


The /me endpoint solution doesn't work with a stateless API.


Can you clarify what you mean by a "stateless" API? If I'm reading you right, the concept seems kind of nonsensical to me. I'm going to respond to what I think you're saying, but I'm worried that I'm constructing a strawman in doing so.

I see three worlds in which a /me endpoint wouldn't be "stateless." The first is a world in which the current user is considered a form of state. Whether that's true in some absolute sense is an abstract philosophical question. The more practical question: if we're considering tracking the current user (ie "performing authentication") to be antithetical to a stateless API, then how are we supposed to then perform authorization? Is everyone just supposed to be allowed to do/see everything?

The second: if you're using a /me endpoint to retrieve user data, in lieu of retrieving it from a cookie, presumably some earlier interaction has logged the user in. I suppose there's implicit state in the fact that those two interactions must occur in order. But even if we're using bearer token auth, that token needs to have been generated somehow. Complaining about the presence of that state doesn't seem very practical to me.

The third: cookies are inherently stateful because they require session data to be present on the server. This is kind of true? But if we want to use a bearer token instead, presumably we need to have generated it. We can't generate secure bearer tokens idempotently or reversibly, so we need to store some kind of data about the bearer token on the server... which to me is not philosophically all that different from creating a session?

Anyway, again, I feel like I may well be arguing against a strawman here! If there's some fourth definition I haven't considered, I'd love to hear how you're defining stateless APIs and why you feel that that definition produces more useful/usable API designs.

cookies are inherently stateful because they require session data to be present on the server

Not exactly true. Many cookies use signatures or encryption to make the data trustworthy for the server, so there does not need to be the somewhat traditional "sessions" list in a database.

Cool, I didn't know that! How does credential revocation work in that context? Or do you just maintain a really short validity window?

Well, it doesn't necessarily work. One way is to keep short validity, another is to tie it to e.g. the last update of the relevant user's password, or similar - you wouldn't have to check the contents of the package, just that it's been signed after the password has last changed.

There are lots of little options you could use, but it's not always necessary.

I think lietu has just described JWT in a cookie ...


I don't really understand what your thinking of stateless is here. If your cookie holds all the necessary data, e.g. your user information in encrypted form or JWT style tokens or similar, then your backend server really needs to know no other "state".

To be clear, you're suggesting using cookies for authentication in a REST API? In my experience this is not a successful pattern and certainly doesn't conform to some of the core principles of REST.

It does conform to REST. There's nothing not RESTFUL about cookies.

Cookies are purely an HTTP header. When a cookie is sent from a browser->server it is sent via the Cookie: name=value format. This is it.

What you're comparing it to is the Authorization header, which looks like this: Authorization: .... There is NO difference whatsoever here except for the name of the header.

This is a really common misconception. I've started replying to comments (this article really blew up while I've been busy working...) but I plan to write a more in-depth article covering some of the arguments I only briefly mentioned here in more depth.

On top of that, not all APIs have to be RESTful and assumed to be accessed by 3rd parties.

If it's your own application, you can still make pretty RESTful APIs, using cookies, and not have to worry about the difference between using Authorization: ... headers vs. Cookie: ... headers. Authorization: header is great when you assume the client is a non-browser application, and you can cater to those easily with your middleware. For your own browser applications cookies are better.

Keep in mind that some sandbox environments don't allow arbitrary headers to be set or even cookies to be added, but they do support the RFC for Authorization headers. So, it may seem like the same thing, but when your local API (e.g. WkWebView had (has?) this as a limitation) - then you're going to have to use it that way.

So what you're trying to say is that since some systems are limited, it's ok to use a bad practice everywhere?

Of course you're allowed to work with the limitations of your system (though finding a less idiotic system is a better choice), but that doesn't mean you should use the bad practice from the bad system when working with good systems or systems you have control over and can fix.

Good article, but the language is too strong. You made a few good points but also some arguments are controversial.

I am not sure if using authentication cookie for API is a common pattern out there. I haven't seen many APIs using Cookie for authentication. Cookie and Authorisation are designed for different purposes. Yes, they are just different names behind the scene but applications treat them differently. Authorisation header is not automatically pre-filled by browsers while cookie is. That means using Cookie as authentication you're prone to CRSF. That's why we use Authorisation header to avoid CRSF as much as possible.

And last point, no one puts a few MB of data in a JWT token.

I hope nobody is putting a few MB of data in my localstorage either. If you use Authorization header, the token can be extracted by XSS etc. and sent to malicious servers and they can then use it however they wish.

If you use a secure; httpOnly cookie it can't be stolen by malicious JS and is bound to your browser's security model. Add to that proper CSRF tokens, and e.g. sameSite=strict and you've got a decent system.


Why do you assume I have access to a an endpoint where I can fetch this user's information? This user's claims could come from a trusted 3rd-party, and their claims are verified on my end by their pubkey.


Good article but I disagree.

IMHO storing JWT in localstorage is ok. I mean, what is actually not ok given your examples is to be vulnerable to XSS attacks, or using third party scripts/infrastructure you don't trust, in both cases the local stored jwt is the least of your worries –as crazy4groovy points out–.

Here's the thing, we need to store something on client side so they don't have to type the user/password each time we're making a request to the server and yeah EVERYTHING on client side is meant to be insecure. But, does it mean that, for example, browsers shouldn't let users save user/password because third party extensions, etc. can access to them? Hell no.

Yes, if you have the jwt you can access, but is it that bad? That's why they're called bearer tokens: you have one, you can access then. It's like a check payable to cash: they are payable to anyone who presents them. Does it mean that the bank should hire a bodyguard for you? Probably not.

Okeey! I digress, but the point is we need a balance between security and ease. No way I'm using cryptographically signed cookies for storing just a user token for a social network. However, if I were a bank website I would do exactly this.

On the other hand, I agree with the sensitive data point. There is no need for storing sensitive data like addresses or credit cards into the localStorage.

Sorry for the long talk, too much text for a non native speaker like me:)


Hey! Thanks for the comment.

Storing a JWT in local storage is fine -- the point of this article is to explain to the 99% of developers who do this without thinking about it why it is bad and not recommended by OWASP and security people.

Obviously, if you are aware of the risks and choose to do so anyway, that's fine.

The tradeoff of using a JWT really comes down to this: speed vs security. JWTs are basically opting for speed (and a very minimal amount of speed, I might add) over security.

JWTs were not designed to be used for authentication or authorization data. They were designed to be used as one-time, short-expiration tokens to pass signed data from A->B. Using them as a way to "securely" store session data is abusing them in ways that are directly contrary to a secure mindset.

I guess if I could summarize my thoughts about your comment, I'd say this:

IMO, using session cookies is not only faster/more secure, but far simpler and safer for 99% of developers to use. If you're in the 1% who knows what you're doing and is willing to make the tradeoff, go for it. But for 99% of people out there, it's a bad idea.


Maybe it wasn't the intention but I feel that this article is contributing to hysteria around JWTs/localStorage.

I do software consulting related to an open source project I created and now I feel that I keep having to explain to my clients/companies over and over again why using a cookie would not make things more secure in their case.

I've even been asked to re-implement a perfectly secure authentication system because a security firm that my client was using recommended that they should stop storing their JWTs inside localStorage and that they should store it in the app memory as a global variable instead (as if that was any safer from XSS) - Also the JWTs had a 10 minute expiry so quite safe.

The problem is now that a lot of security consultancies are full of people who like to use articles like this to make blanket decisions on behalf of their clients in order to save them the ordeal of actually having to think about each company's case on an individual basis.

I just want to jump in real quick as one of those people who like to use articles like this to make blanket decisions. A few points as why security people say not to store session data in JWT and LocalStorage. Out of the box yes LocalStorage is more secure than a cookie for session data, however with the optional flag SameSite cookies are now equal to LocalStorage with built-in anti CSRF protections from the browser. Adding the HTTPOnly flag bring cookies to a higher level than LocalStorage. This is because now client-side JavaScript cannot access the cookies. The last part is where the recommendation to use cookies over LocalStorage is made in relation to potential exposure from XSS. Outside of XSS or vulnerabilities in the browser itself both are limited to exposure from physical access on the client-side in a general risk perspective.

The biggest risk for both options from a security perspective is XSS and while some may be confident in their ability to not introduce XSS, I can say that even the most experienced developers can have a hard time preventing XSS. I won't dive into too specific details but a shockingly common bypass to a lot of anti-XSS solutions is to switch the method from GET to POST or POST to GET in a request. Some popular frameworks even allow submitting GET parameters in the body which is completely wrong from the RFC point of view. The pervasiveness of XSS is why security people make the recommendation, we like to think in layers so if XSS is somehow introduced into the application you still have the layer from HTTPOnly on the cookie verse no additional layer on the LocalStorage side.

TLDR: LocalStorage out of the box is less insecure, but cookies offer more security than LocalStorage when done right. Security people aren't blindly making the recommendation there is a reason.

I would argue that using an httpOnly cookie doesn't add any security. At best you could say that it might make it slightly less convenient for an attacker to carry out the XSS attack.

I wrote a more detailed technical explanation here: dev.to/jondubois/comment/373l

Concur. There's no threat modeling that I could think of that would hold up httpOnly as being a significant factor if the threat vector up to that point has already leveraged XSS - so your local JS context is already 0wned - at this point, the exploit code just needs to directly execute from the compromised browser instead of sending the auth token to a remote server to be exploited from there. Considering the local context is already compromised, that hardly seems more than an inconvenience to the attacker, as jondubois indicated.


Heyo! I can tell you obviously aren't a fan of the article.

One thing I would say though: just check out the point of the article. I'm not telling people to do anything insane. I'm trying to encourage people to simplify their apps, their code, and often their security strategy by simply using cookies.

They can both contain the exact same info, transmit the same data (in the same way! via http headers), and provide very little differences in terms of implementation/API.

What I'm suggesting here is simpler, quicker, and more secure than what I've described as the problem.

And... I'm not the only one saying this stuff. OWASP, Thomas Ptacek (a well-known security researcher), and many other smart people constantly try to dissuade people from doing the things I mention above. This isn't anything obscure that I'm talking about.


Thanks for introducing me to IndexedDB. I had been using localStorage in a webapp and IDB sounds like a much better solution.


IDB is great for some use cases =)


Hey Randall,

I definitely agree that storing session information in localStorage is a bad idea. Secure, HTTP only cookies are the way forward for that.

I just wanted to point one thing out around cookies. You said

One of the annoying things about cookies (the only real alternative to local storage) is that they need to be created by a web server. Boo! Web servers are boring and complex and hard to work with.

Firstly, you definitely come up with another alternative to localStorage later in the article with indexedDB. However, you absolutely can write cookies from JavaScript. It's as straightforward as:

document.cookie = "dev.to=awesome";

You can then read the document's cookies again with:


Now, all we need to do is flawlessly fix XSS and we won't have to worry about any of this again!


Doesn't this approach have the same security flaw as storing an authorization token in the local storage? I mean, every JS code is going to be able to read them.


Well, yes. As Randall points out above, he was referring to httpOnly cookies, which cannot be read or written to from client side JavaScript. I think that paragraph just lacked that context. Client side cookies are just as susceptible to XSS attacks as localStorage. I just didn't agree that just cookies needed a server to write them, httpOnly cookies do though.


Good point -- I was referring to the httpOnly ones. Good catch!


This story creates so much FUD(Fear, Doubt and uncertainty) about a very common tool like Local Storage which is very essential for a lot of web applications.

Careful research on this topic will tell you that there are no known Local Storage vulnerabilities that lets some one else steal your data from the browser's local storage.

JWT is an awesome idea that works well for scaling many services.

Storing JWT tokens in local storage is perfectly alright.

Storing ids in Local storage is perfectly alright unless it is something like social security id. Even if some developer did store social security id on local storage, it is not so easy to steal that information from local storage unless the end user has malicious browser plugins. If the end user has malicious plugins then nothing will help.

There is a place for encrypted cookies, local storage, indexdb and server side session storage. There is no one size fits all approach to all problems. In many many cases, storing temporary data like ids and user preferences on that site are perfectly alright.

These ideas belong to the author and definitely not the employers, but I cannot help it, after reading this, I have a very poor opinion of the employer. I doubt I am the only one who thinks like that.


Hey there,

Thanks for leaving a comment!

I understand what you're getting at here, but I strongly disagree. I'm one of many people actively involved in the security community with this viewpoint.

The creators of the JWT spec itself, for instance, did not design it for the way it is being used in web apps described here. There are TONS of resources written by cryptographers (like DJB), security professionals, etc., all pointing to the massive holes and problems that using JWTs and storing tokens in local storage can cause.

It's not just me.

The biggest problem I see is that there is so much misinformation around advocating using these things. This is a big problem.

This article is just one of many which showcase some of the issues with all the insecure recommendations made amongst the general web development community.

I strongly urge you to read through all the other resources out there which have more to say on this topic. Not only does OWASP recommend against using local storage (which was the point of this article), but there are a PLETOHORA of reasons why you don't want to use JWTs AT ALL! The spec itself has SERIOUS issues and has been widely criticized by the security/cryptography community.

The underlying crypto options themselves have a million issues that cannot be easily resolved, and that's all BESIDES the portion this article talks about, which is just the high level architecture/storage piece.


Best way to refute my argument is to provide some references where JWT was unsafe or local storage was compromised.

Instead you are still continuing the FUD and throwing a bunch of other accomplished people's names and complicated crypto words and "security community" to bring credibility to your arguments.

I think you should talk about this to some other experienced people at your work place. People with serious qualifications disagree with your assessment of the topic at hand.

Here are some good resources to read through:

And, re: when is local storage compromised... Read through OWASP top 10: owasp.org/images/7/72/OWASP_Top_10... (XSS has been one of the top 10 web exploits since 2013 and likely far before).

Did you even read these blogs you linked to?

The first link says "This article does not argue that you should never use JWT". but you are confidently advocating everyone not to use JWT at all.

The other links do not show any vulnerabilities in either local storage or use of JWT tokens. They are talking about specific cases of using bad encryption mechanisms with JWT payload.

If you have XSS in your setup, using local storage is least of your concerns.

The links you posted are related to security. None of them support your argument that local storage and JWT are bad.

Yes -- they do.

The first link describes what is talked about in this post. Using JWTs for web auth is not optimal and causes a lot of issues.

The other links talk specifically about weaknesses in JWTs as a protocol, implementation issues, and real security concerns with the spec.

The bit about OWASP + XSS is the main issue around local storage, since it's something difficult to prevent, even when you're using CSP, which I explained in depth in this article itself.

I'm not certain what more you are looking for =/ The usage of JWTs for web authentication tokens is not ideal, and even for valid use cases of JWTs they are not optimal to use due to security issues with the protocol (as well as many popular implementations) you would be better served using alternative token types which avoid JWT issues.

In short:

  • It is not recommended to store sensitive data in local storage due to wide prevalence of XSS and the difficulty of preventing XSS
  • JWTs are not recommended due to spec issues, poor encryption and signing algorithm choices, complex specs that make developing JWT libraries challening, and flexibility in algorithm usage which allows web developers to easily mess up important implementations

Not sure what else I can do to explain :o

You are able to talk around the topic in circles while missing the whole point. You are advocating people not to use local storage and JWT tokens based on nothing credible or nothing concrete. You are misleading a lot of people with your story.

There are perfect legitimate use cases for JWT and Local storage. They are very useful tools.

There are no spec issues with JWT and you can use JWT without encryption.

XSS is not an issue with local storage.

Please stop the FUD.

You do not have to explain anything, If what you say is credible and has any merit, people will make up their mind.

What you are saying is directly contrary to what is outlined in those links I supplied.

I'd love to have a more in depth convo at some point. I'd you're interested in continuing the conversation please hit me up: r@rdegges.com. I'd be happy to talk about spec issues in more depth, or issues with architecture as outlined above.

Really open to whatever! It's a complex topic, and fun to look at.

looking back, this sure seems more like a hit piece from a shill than a legit criticism of jwts


As someone who is taking their very first steps into web development, I found this article was very informative and I like the repetitive way the fact is drummed into the reader. I know that when I get to that stage in my learning, this is something that will come to mind straight away. Thanks :)


If a rogue script can send the contents of local storage to a server, can't they just add a key logger as well? In other words, if someone can inject malicious JavaScript into your site, you've got problems no matter what you do.


Title of the article could have been "Please Stop Using Local Storage For Sensitive Data" rather than "Please Stop Using Local Storage"


I disagree on the security concerns with LS and JWT. As others have said, you will have a much larger concern if an attacker can inject JS into your site. Proper use of JWT is implementing expirary and sensible authorization after one has authenticated.
Deferring to the Auth0 docs, they recommend LS or cookies for storage.


I'm very familiar with Auth0 and have a lot of friends there. That being said: the recommend incorrect things all the time.

Nobody is perfect, especially not security companies! We get things wrong all the time ^

  1. They do not recommend, they say you "can" use local***
  2. Right after that they say, you can use cookies too
  3. For both options they tell you what can go wrong
  4. For the local storage option, they mention XSS, exactly the thing this article is trying to educate us about

Well, you stated that using Local Storage for sensitive information is bad, and that's OK. But just saying "do not use" doesn't constitute good advice. There are good and bad choices, as always. Know your choices and act accordingly.


I like to use github.com/localForage/localForage because it uses IndexedDB or WebSQL but it falls back to local storage when needed. Still, security advice holds.

This looks awesome. Thanks for sharing Alex.


I've found one of the best uses for (local|session)Storage is just to cache data. If you have a data set that is going to remain static for the entire application session but still needs to be fetched asynchronously, sessionStorage is great for caching it (unless it somehow contains sensitive data of course...).


Exactly! I love it for that. This is what I use it for as well.


Sorry, but as far as I see the whole point of this article is (for the security argument) to not use local storage, because of XSS attacks.

XSS attacks are a serious thing, but recommending cookies is just silly. Obviously if you have an XSS attack JavaScript can also read your cookie. Even more, it can easily scrape your website and such stuff.

So if you have an XSS vulnerability you have a problem. Period.

OWASP, as you quote, points out a different security aspect, however: Data is locally stored. (obviously, that's how the thing is named). As such other local users may access it. If that surprises you, I think you did not get the concept of a "local storage".
As such, obviously, I agree to not put credit card numbers or other sensitive data in there, which may require a login.
However, what's for sure is that a cookie itself is not really much more secure than local storage. The only advantage it may have is that it can be automatically deleted at the end of a browser session, thus invalidating your own session. But as it seems, JWTs also found a solution for that.


Tom add: Yes, httpOnly (and sameSite) cookies add some security and when you can use them, it's great (for session cookies e.g.)! However, it's also a thing you need to use. You can also use local storage as secure as this.

My point is just, this article calls out local storage as insecure and only shortly explains how cookies should be done to be more secure! It's not at all obvious that when you don't do it properly also cookies are by no means more secure.


While I agree with most of your points, there are hacks or workarounds to get past most of the limitations of localStorage and sessionStorage.

At my last job, I was tasked with writing a SPA, but the person in charge of the backend was an absolute idiot who would rather re-use old, inefficient code than write new code, so I ended up using sessionStorage to store a lot of information (we worked with PHI [Protected Health Information], so this was really a terrible workaround in practice).

Since we had to work with IE10, I couldn't implement an indexedDB solution to the problem, and ran into several issues, firstly, the lack of security. In order to address this, I incorporated Crypto.js into the webapp and encrypted everything before storing it and decrypted when retrieving it. The key to access sessionStorage was created anew every time the page was refreshed, and if a key couldn't be read with the stored key, the data would be deleted and re-fetched.

This led to a second problem: some of the data I needed to store was quite large, and encrypting everything meant I had to base64 encode the result in order to stuff it into sessionStorage, which led to a 33% bloat on everything. Sometimes, this would blow out the 5MB limit. So I ended up incorporating a GZIP library to compress the data when storing and then decompress when retrieving.

This led to a third problem: GZIP isn't the fastest algorithm, and this was all being done synchronously, so when compressing/decompressing large data sets, the browser tab would freeze (we had some searches that could return 3-4MB of data). Fortunately, IE10 at least supports Dedicated Web Workers, so I was able to offload the encryption/compression and decompression/decryption to a worker thread. The worker took the data to be encrypted/compressed/decrypted/decompressed and an encryption key, and returned the result.

Due to the sheer amount of data we could end up processing in a short period of time, I also ended up writing a worker thread pool manager so that we could have 2 or more dedicated workers to do that and not cause lag spikes when doing lots of reads/writes to and from sessionStorage.

Eventually, the solution I ended up with was as follows:

  • Generate a random encryption key every time a user logs in
  • Store that key in sessionStorage using a different, fixed encryption key (insecure, but only accessible inside our own code)
  • Whenever a request that can be cached finishes, send the data off to a worker thread to be compressed, encrypted, and then compressed again (this yielded the best overall size - one 3.5MB JSON payload was compressed to a little over 220KB once)
  • Store the result in sessionStorage
  • Reverse the process to retrieve

No, that is not a joke. What part of it made you hope that it was a joke? Perhaps I can clarify.

There's a lot of security issues in the architecture you described above:

  • Using crypto in client-side JS
  • Storing an encryption key on a client
  • etc.

There are other ways to do this stuff safely, although I don't envy your situation.

In a lot of cases focusing on security isn't possible: maybe it's due to a very bad team dynamic (like back-end developers not wanting to work with you), maybe it's due to legacy issues -- but whatever it is, it isn't always feasible.

I like to keep things simple and try to focus on security for apps that require it -- and in these cases I just do the most basic straightforward thing possible.

If you ever find yourself using encryption tools manually (especially in JS) you may want to re-evaluate your goals and see if there's something simpler you can do.

I didn't really have a choice. The users wanted the SPA to be fast, my bosses wanted it to be secure, and the backend engineer was unwilling to address his performance issues. I had to compromise a bit.


What a horrible title to use for your article.

You could have used "Please stop using local storage FOR SENSITIVE INFORMATION".

besides that, its an amazing API which allows us developers to make cool things you couldnt do without ( at least not that easy ).

Examples of localStorage uses I have used:

  • Website theme changing

  • Client information such as duration of visit per page ( you save this in localStorage so you can send this info to the server with AJAX on next page visit sendBeacon has limited support, on unload doesnt seem to work persistently)

  • Device specific settings on a website that cant/ dont need to be saved in externally.

I could think of many other uses for the great localStorage API.
simply, it can store anything ( ofcourse dont store sensitive information ) which doesn't need or can't be saved to a server for whatever reason.


You're advocating for cookie-based authentication using sessions (an increasingly dated practice), but do not mention anywhere adding real csrf protection:

From OWASP regarding your SameSite=strict suggestion
Considering the factors above, it is not recommended to be used as a primary defense. Google agrees with this stance and strongly encourages developers to deploy server-side defenses such as tokens to mitigate CSRF more fully.


A couple of technical corrections here about your claims that LocalStorage is "basic":

1) LocalStorage CAN be asynchonous.
2) LocalStorage CAN work with web workers.

#1 is actually possible by taking advantage of #2. By setting up a separate frame/JS exec environment, you can use standard web worker communication mechanisms of postMessage to communicate across your site. I've used this in a few apps to implement shared storage across local/remote access of a site. Doing this gives you async access, which may or may not be a good thing depending on what you're doing with localStorage, but if you're accessing a lot of data from storage it's wise to be using this method anyway.


3) While it's true that you can only store string data, treating this as a negative is subjective. MOST key values stores (or DBs in general) treat structured data this way: MongoDB, BoltDB, even storing JSON in SQL, in all cases you're doing exactly the same thing. Sure, there's a downside for numeric primitives which SQL supports natively, but that's quite a small edge case (and for JS, passing floats around as string types is much safer). Performing serialization is a pretty standard practice in structured data cases.

And of course, having to serialize structured data is actually a decision you're making in the first place-- you can always avoid heavy serialization by restructuring your storage (using keys to namespace structures), at which point you're really only converting numerics, and that's again almost rarely a bottleneck in the grand scheme of all things JS.

I would actually argue that storing data as strings is a feature, not a bug, and a pretty standard practice for KV storage, too.

There's also a small point to be made about the 5MB limit (actually 10MB these days but who's counting) which you can workaround using methods 1&2 (granted very awkwardly), but also, you can use IndexedDB for larger data sets if you need to, you should probably only be using localStorage for state, not novel user data (like "saved content").


Local storage can be useful in some scenarios as long as one is aware of the security situation and other limitations.

I used local storage on a single page application where the user had the option to play around with various scenarios in a parts configuration/selection quote before committing it to the server/database. There wasn't anything that needed to be secured in there, just the user's sandbox so that they could reuse it as a template for another customer quote or finish their work on the quote the next day.

One big limitation on using IndexedDB and Cache API in the average corporate environment is that many users are still on IE or Edge which don't fully support them.

The whole point of this article is to raise awareness of security. Sadly, I find too many front-end devs think that security is something for backend devs and server ops. I understand your point on polarity of these types of discussions, but security is really not something to screw around with.


First of all - I agree with what you say in the article and fully echo your sentiment. I am personally on a journey to find the best solution for the problem.

I am sure you would appreciate the complexities of building software in larger teams. We often have a situation where the API is built by one team, the front-end by another. These teams do not talk to each other. Not that they don't want to. It's just how they are structured. And both depend on an identity provider (something based on OIDC or OAuth 2.0) who is responsible for issuing the tokens. This very same API can be consumed by another team that is building a mobile App.

Now, I can take your advice and put my JWT in an HTTP only cookie. My mobile app can add a cookie header to make sure that JWT is always sent to the API.

You would also appreciate the fact that running an XSS attack on my SPA front-end is only one of the many ways to steal tokens. There are a number of documented vulnerabilities in both ODIC and OAuth 2.0 that the hackers can target to get hold fo tokens. Once they do, it does not make any difference if the API expects the token to be set in a header called Authorization or a header called 'Cookie`.

Is there a way for the API developer to protect its API without having to worry about the security mechanics in place at the consumer?


No. Unfortunately, if you are using OAuth or OIDC that's the name of the game.

I'm not a fan of either protocol due to to their poor structure and implementation issues. The burden in using these protocols is everywhere: on the authorization server, on the client, and anywhere else :(

If you're stuck using those protocols just do the best you can with the tools you have.


The very fact that you're posting on dev.to means you're already using OAuth, as it's the only auth mechanism for the site (via either Twitter or GitHub's IdP). There's only a few ways to implement CSRF-less and cross domain credential proxying and JWT is one of them. I don't necessarily agree with JWT, since by the time you get done implementing revocation and audit logging, you're just a hop and a skip from just having the IdP store "session" since at the end of the day either the JWT itself or a token wrappered with a cookie represents the user's identity to the application. If you're not facebook or some other huge platform with potentially a gazillion identity verification requests per second, signed JWT doesn't save you much compute anyway since it's expensive to generate the token signature vs. just having the IdP do a session lookup against something fast like Redis. On the other hand, you're not autospewing the contents of your cookie jar on every request to that domain either.


Why would you say that? I have been using OIDC for some time without any significant issues. Can you shed some light on why you think these protocols have problems?


For this reason alone we shouldn't use internet...

If you have xss on your page... there are worse things than a token.

What they can do with a token? Access the account? Then what? Bohoo nothing.

You can ask for password for "confidential" data that really hurts the user. Every bank does it, you can do too.

The only reason is XSS. And that it's mitigated by any good framework out there(Symfony, Laravel, etc).

JWT tokens can be used everywhere. Not everyone has the luxury to have everything on one server.

JWT are insecure if you don't know how to use it. You can pretty much make a JWT 5 minutes required refresh and 24 hours expiring...

More than that if you really don't like them being stateless(but thats another problem) you can put an id on them and save in database but that defeats the purpose.

You can attach a ip to the JWT. Makes it even harder to steal.

I mean i lock my door when i leave the house. I don't put a tank in front of it, hire 20 bodyguards and buy a flamethrower ...


How do you attach an IP to a JWT? And even if you manage to do that, how do you then use an IP bound JWT from an SPA or mobile app?


Simple. You can put it in the jwt ...

JWT can have any number of object you want.
It's a json...

Any request to an has a requester data... you can particularise from there, or any other method and make it very unique for user and harder to just take it and reuse it.

Did i say you have a universal solution? No. You need to make it your own.

If you are afraid of tehnology than thats on you. But tools are there to be used not be afraid because of "problems".

LocalStorage has some drawbacks, but has good parts as well... Tokens are used everywhere ... even to log in on this websites.

Lets not talk the iframe solution which is implemented and has security flaws as well(looking at you google).


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

Ok, but if you're dealing with an XSS attack then any JavaScript on your page can also make network requests using your cookies. Sure, the tokens themselves haven't been stolen, but the attacker can still use them however they want from right there in the browser.


Some clarifications on JWTs taken from the RFC as well as JWT.IO and Auth0's best practices for storing tokens.

They can be used to store sensitive information.

From RFC:

A JWT may contain privacy-sensitive information. When this is the case, measures MUST be taken to prevent disclosure of this information to unintended parties.

From JWT.io:

JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.

They can be used for authentication and that is one of their primary use cases.

From JWT.io:

Authentication: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

I think it is important to point out that there are security concerns with both Cookies and JWTs (mentioned in Auth0's best practices) that cannot be left unchecked and should be handled delicately.


Auth0 is a great company (I have a lot of friends that work there) -- that being said, they recommend things that other security experts disagree with all the time.

Nobody is perfect.

Auth0 is the main reason JWTs are so popular today, and has a pretty vested interest in encouraging people to use them for authentication (which I strongly disagree with).

There are a lot of resources online of cryptographers speaking against using them for this purpose any why (other than myself).


Don't disagree with your assessment of Auth0. My nit would be the RFC for JWT says quite plainly that there's nothing wrong with storing sensitive data in a JWT so long as it is safeguarded.

That said I don't see much advantage to using a JWT to store anything beyond claims & id.


LocalStorage is an option that comes with tradeoffs. Whether it is better for a given use case or not is going to come down to the specifics. We assume that we need to persist state between the server and the client. This means that our two choices to identify each request are a token stored in LocalStorage or one stored as a cookie. One is more vulnerable to XSS the other to CSRF. Personally I'm generally more concerned about CSRF, but your mileage may vary.


Thanks for the comment!

Yah, you can pick either. I personally feel like preventing CSRF is a lot simpler since it's built into almost every web framework by default nowadays. There's only way to CSRF a website but a million ways to XSS it :(


Well, I find I'm rarely in a place where I'm too concerned about allowing untrusted mobile code into my application. Yes, you can end up with bad actors in things like NPM but an XSS attack is the least of my worries there. And elsewhere it's just a matter of sanitizing user input. Sadly there isn't a silver bullet. Which is why we can't have nice things.


Untrusted input is one vector -- but XSS comes from a lot of places: third-party JS (google analytics, etc.) -- domain compromise, DNS hijacking -- all over. It's significantly harder to prevent.

This article really only discusses the content from a web perspective, if you're doing native mobile stuff it's a whole different story =D


I almost used localStorage my every project. For example:

let OrderID = document.querySelector(".orderNum").innerText;
window.localStorage.setItem("OrderID", OrderID);

After that, I redirect another page without any query string. I still need to OrderID. This is the best solution at the moment.

I did not store any important information in localStorage. Yes, I know we shouldn't store any password or related information in localStorage.

What about OrderID like information? Should I use? I don't want to use server-side sessions.

For example, I completed Order. I delete key from localStorage.


Thanks for this great article.


After that, I redirect another page without any query string. I still need to OrderID. What about OrderID like information? Should I use? I don't want to use server-side sessions.

You've just discovered POST.


Really good article for opening the eyes of so many people. I want to get your opinion on something though.

So as far as I understand, it would be a bad thing to have a site that logs you in and sets a token in localStorage to be used for further authentication. This is bad because if you're vulnerable to XSS, the token can be used. One better alternative is to use a secure, httpOnly cookie (with SameSite, which isn't supported everywhere, but I'll give you that one because why the crap wasn't that in the original cookie spec, right?) with a JavaScript accessible csrf token. Aren't you still vulnerable to the same attack? In all of the ways that the csrf token is made available, it's accessible to the client. Either a metatag, or hidden input field, if it's in the DOM, it's accessible via JavaScript. Given, it's an extra step for the attacker to take, but any Pen Tester worth his salt will check csrf vulnerabilities in his first five minutes of testing. Just saying, XSS should probably be the focus in protecting your site because browser security is a bad joke.

I still agree with you, that localStorage should stop being used for authentication tokens and the like because support for localStorage can be spotty and unpredictable. I think it would be perfect to use localStorage as a local cache (of non-sensitive information).


I would be interested to see a followup post to give some substance to this statement (especially the scaling part):

And yes, you can most definitely scale up a large website using this pattern. Don't tell me that JWTs are “stateless” and “fast” and you have to use local storage to store them: you're wrong!

Also, if an attacker can run JS on your site, then they can also issue XHR requests which will automatically use the secure cookie for your API. It is a valid point however, that they can exfil JWT from local storage and use it from outside (by setting a fake origin header), whereas using HttpOnly cookie the attacker must call your API thru the infected browser.

P.S. Cookies are still vulnerable to CSRF unless you keep even more state on the server (anti-forgery token) and have the client send that state along with each request. Otherwise, your API can be compromised from other sites without your JS even being compromised. Maybe that will go away once SameSite cookies are widely supported.


I plan to do a follow-up post about this. Subscribe for updates =)

This post really blew up since I've been away @ work. There are a lot of cool writing ideas I've gotten since publishing this initial piece to dive into other related topics and help clarify a lot.;


Given a 2 minute expiration, and 1 request per second, Facebook for example, could nominally reduce the number of IdP requests (if they had to retrieve a session from the IdP) by almost 120 times (assuming an unsigned JWT, which isn't realistic, but is useful from a Fermi estimation).

Yes the main advantage of not using cookies is to not have to worry about CSRF, which can be quite complicated because minimally now you have to have the server also generate a non-HttpOnly cookie from the CSRF token in order for the JS to retrieve it in order to send it out-of-band as part of the subsequent XHR request.


I'm pretty new to JWTs and have been researching this issue a bit - the only OWASP recommendation I could find is to keep JWTs in local session storage and use a fingerprint cookie to prevent sidejacking? owasp.org/index.php/JSON_Web_Token...

Not sure if the link above is current, updated, outdated or what. I've also looked at some identity providers like Okta and Auth0 and all of their docs show using local storage for JWTs, but then there are blog posts (a few years old) from employees kind of arguing the opposite (even one who seemed to have done his research on stackoverflow!) - there seems to be so much conflicting information.

Sorry to renew a zombie thread!