Suppose you have a requirement like "users should stay logged in even across devices." Where is the best place to store session information (a JWT or a session ID)? localStorage, sessionStorage, cookies... each option has its pros and cons, but once you take security and operability into account, the "right answer" narrows down considerably.

We'll compare four representative options and dig into why the recommended approach is recommended.

The Four Options Compared

A) A JWT stored in localStorage

  • Persistence: ◯ (retained even after closing the browser)
  • Risk: Extremely vulnerable to XSS (cross-site scripting)
  • Verdict: The contents are fully exposed to JavaScript, so the moment a malicious script runs, the token can be stolen. Not recommended if security matters.
  • Persistence: ◯ (retained until the cookie expires)
  • Risk: Cannot be accessed from JavaScript (httpOnly), so it is resistant to XSS.
  • Challenges:
    • Because a JWT holds no state on the server, it is hard to do things like "force logout of only a specific device."
    • Once you start managing token revocation (a blacklist), the stateless advantage of JWT fades.
  • Persistence: ◯
  • Security: ◯ (httpOnly gives XSS resistance, and the Secure attribute restricts it to HTTPS)
  • Operational flexibility: ◎ Most flexible
    • The actual data lives on the server in Redis or a DB, so the server can invalidate sessions freely.
    • It is easy to show a "list of devices currently logged in" or to destroy all sessions when the password is changed.

D) A JWT stored in sessionStorage

  • Persistence: ✕ (disappears when the tab is closed)
  • Fit with requirements: Doesn't meet the requirement of persisting across devices at all.

In modern web development, especially when security and advanced user management are needed, option C (an httpOnly cookie + a server-managed session ID) is considered the best balanced.

  1. XSS protection: Thanks to the httpOnly attribute, the session ID can't be stolen even if a script somehow gets injected.
  2. Server-side control: There's no "once issued, it can't be stopped" risk like with JWTs; the server can revoke access at any time.
  3. Device management: When a user is logged in on multiple devices, being able to manage (list and delete) each session individually is a strength of keeping state on the server.

Summary

The temptation to "put the JWT in localStorage for scalability" is common, but considering the risk of security incidents and how painful it becomes when you later need to "force logout a specific user," the combination of cookies and server-side sessions is still the most solid and safest choice.