Where to store a token in a browser

JWT Authentication Course · lesson 6 of 13 · 5 min read

localStorage or a cookie - each trades one attack for another.

Open this lesson in the learning hub

Key points

  • localStorage is readable by any JavaScript on the page, so any XSS steals the token outright.
  • A cookie with HttpOnly cannot be read by JavaScript at all, which closes that door.
  • But cookies are sent automatically, which reopens CSRF - hence SameSite.
  • SameSite=Lax stops the cookie riding along on most cross-site requests.
  • The common modern answer: HttpOnly + Secure + SameSite cookie, and never store the token in JS at all.

Choose the cookie: XSS steals a localStorage token permanently, while CSRF has a standard fix.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the JWT Authentication Course course, and every lesson in it is listed on the JWT Authentication Course contents page.