Dev Overflow Logo

Dev Overflow

Global search

Search across questions, answers, users and tags.

Loading...
save

Is storing a JWT in localStorage really that dangerous?

clock icon

asked 1 month ago

message icon

2

eye icon

1.5K

Every article says "never put your JWT in localStorage" but few explain what to do instead in a SPA that talks to a separate API domain. What is the actual threat model here?

2 Answers

The threat is XSS. localStorage is readable by any JavaScript on the page, so a single injected script exfiltrates the token and the attacker has a valid session until it expires.

The standard alternative is a cookie the page's JavaScript cannot read:

1Set-Cookie: session=...; HttpOnly; Secure; SameSite=Lax; Path=/
1Set-Cookie: session=...; HttpOnly; Secure; SameSite=Lax; Path=/

That moves the risk from "token theft" to "CSRF", which is the easier problem — SameSite plus a CSRF token handles it.

Being honest about the limits: if you have XSS, an attacker can also just make requests with the cookie attached. HttpOnly stops them walking away with a token they can replay elsewhere later, which is a meaningful reduction, not a cure.

For the cross-domain case, put the API behind the same site as the app (api.example.com with the cookie scoped to .example.com). Third-party cookie restrictions have made the "separate domain plus bearer token" pattern steadily less viable anyway.

1

of 1

Write your answer here

Introduce the problem and expand on what you've put in the title.

Top Questions