Local Storage Versus Cookies: Which to Use to Securely Store Session Tokens (2024)

April 22, 2022

Table of Contents

Last Updated on February 9, 2024

Web applications need to store tokens to help manage user sessions. Because the browser/server relationship is “stateless,” every request would otherwise require reauthentication.

As a web developer, you typically have two options for client-side token storage: localStorage (aka localStorage) and cookies. The two have different purposes, and hence different strengths and weaknesses. Cookies are intended to be read by the server, whereas localStorage can only be read by the browser. Thus, cookies are restricted to small data volumes, while localStorage can store more data.

This post discusses whether to use localStorage or cookies for best-practice security of session management tokens in your web apps.

Two token types you need to store

Web applications most commonly need to utilize and store two types of tokens:

  1. Access tokens, which are short-lived JWT tokens signed by the server and included in every HTTP request that a browser makes to a web server, in order to authorize the request
  2. Refresh tokens, which are lasting, opaque strings stored in the application database and used to acquire new access tokens when they expire

Either of these tokens can potentially be stored as a cookie or in localStorage. So, which to choose?

localStorage pros and cons

localStorage is super convenient to use because it always uses JavaScript to access a token. If you’re relying primarily on an API, you can’t always depend on the service to set a specific cookie for your site. localStorage also works efficiently with APIs that require an access token in the header.

Another advantage of localStorage is its contents cannot be automatically sent anywhere. Therefore, localStorage is immune to cross-site request forgery (CSRF) attacks.

On the downside, localStorage is potentially vulnerable to cross-site scripting (XSS) attacks. If an attacker can inject malicious JavaScript into a webpage, they can steal an access token in localStorage. Also, unlike cookies, localStorage doesn’t provide secure attributes that you can set to block attacks.

Another potential disadvantage of localStorage is that, as persistent storage scoped to an origin rather than a domain, it cannot be accessed from different domains or even subdomains.

Cookies pros and cons

Cookies are not accessible via JavaScript provided the proper secure attributes for the cookies are set. This makes cookie data less vulnerable than localStorage data to JavaScript-based attacks. Also, there are a variety of approaches to securing cookies, so you might have more security options than with localStorage.

But because cookies have a limited storage capacity of 4KB, you might not be able to store some tokens that way. You may also need to put an access token in the HTTP Authorization request header with some APIs, which means cookies won’t work to store the tokens in all cases.

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’s next?

Need to validate the security of your web application? Contact Pivot Point Security to speak with an expert about how application penetration testing services can protect your confidential data, isolate vulnerabilities and provide a fast and affordable way to prove your service is secure.

For more information:

Local Storage Versus Cookies: Which to Use to Securely Store Session Tokens (1)

Free OWASP ASVS Testing Guide

If you are just learning about OWASP’s testing standard or are considering the best way to prove the security of an application, this guide is meant for you!

Local Storage Versus Cookies: Which to Use to Securely Store Session Tokens (2024)

FAQs

Local Storage Versus Cookies: Which to Use to Securely Store Session Tokens? ›

Storing JWT (JSON Web Token) in a cookie is considered safer than storing it in session storage or local storage for several reasons: Cookies are less vulnerable to Cross-Site Scripting (XSS) attacks than session storage or local storage.

Are cookies more secure than session storage? ›

If we want it on the server, then we use it, and the session storage is used when we want to destroy the data whenever that specific tab gets closed or the season is closed by the user. There are also a few security issues related to the Web Storage objects, but they are considered more secure than the cookies.

Should we store tokens in localStorage or cookies? ›

Cookie is preferable compared to localStorage

Why? Both localStorage and cookies are vulnerable to XSS attacks, but it's harder for the attacker to do the attack when you're using httpOnly cookies. Cookies are vulnerable to CSRF attacks, but it can be mitigated using sameSite flag and anti-CSRF tokens.

What is the best way to store session tokens? ›

Browser in-memory scenarios

Auth0 recommends storing tokens in browser memory as the most secure option. Using Web Workers to handle the transmission and storage of tokens is the best way to protect the tokens, as Web Workers run in a separate global scope than the rest of the application.

When to use local storage vs session storage vs cookies? ›

Use cookies for server side data where you need a TTL, session storage for specific use cases discussed above, and local storage to manage global data in your application. However, avoid the pattern where your single page application directly interacts with the local storage.

Why would you use local storage instead of a cookie? ›

Unlike cookies, local storage data is not sent to the server with every request, which can improve performance and reduce bandwidth usage. Local storage data can also persist across sessions, meaning that it does not expire or get deleted unless the user clears it manually.

Is cookie safe for tokens? ›

With cookies, the access token is still hidden, attackers could only carry out “onsite” attacks. The malicious scripts injected into the web app could be limited, or it might not be very easy to change/inject more scripts. Users or web apps might need to be targeted first by attackers.

What is the best practice for storing tokens? ›



Storing tokens securely should be done on the backend (server-side) of your application, not on the frontend (client-side). A frontend application is more susceptible to potential security threats such as Cross-Site Scripting (XSS) attacks or unauthorized access if the client is compromised.

Is it safe to keep access token in local storage? ›

If you use localStorage for persisting access tokens and an attacker manages to run foreign JavaScript code within your application, the attacker can exfiltrate any tokens and call APIs directly.

What is the best way to store token in browser? ›

What are the best practices for storing and sending JWT tokens in the browser?
  1. Use HTTPS.
  2. Choose the right storage option.
  3. Use the HttpOnly and Secure flags.
  4. Use short-lived tokens.
  5. Validate and decode your tokens.
  6. Here's what else to consider.
Mar 21, 2023

Where do you store security tokens? ›

We recommend storing tokens on the server, as this offers traditional web apps the maximum level of security. If this cannot be done, you should use encrypted session cookies so the client cannot read token values.

How do you keep tokens safe? ›

Token Best Practices
  1. Keep it secret. ...
  2. Do not add sensitive data to the payload: Tokens are signed to protect against manipulation and are easily decoded. ...
  3. Give tokens an expiration: Technically, once a token is signed, it is valid forever—unless the signing key is changed or expiration explicitly set.

What is the difference between session storage and local storage token? ›

Storing authentication data in session storage

In terms of security, session storage is commonly deemed more secure than local storage because it automatically deletes data when the browser or tab is closed. However, similar to local storage, session storage is susceptible to XSS attacks.

Is it safe to store session in local storage? ›

Both Local and Session Storage provide a simple and efficient way to store data on the client side without frequent server trips. However, due to their limitations in security and capacity, it's crucial to use them judiciously and not for storing sensitive information. Data expires automatically when the session ends.

What to use instead of localStorage? ›

IndexedDB: IndexedDB is a low-level API for storing large amounts of structured data. It provides a more powerful and efficient alternative to localStorage . While the learning curve may be steeper, the benefits include asynchronous operations, better performance, and increased storage capacity.

Is it good practice to store data in local storage? ›

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.

Is cookie better than session? ›

Key Differences between Session and Cookies

The session ends when the user closes the browser or logout from the application, whereas Cookies expire at the set time. A session can store as much data as a user want, whereas Cookies have a limited size of 4KB.

How secure is session storage? ›

In terms of security, session storage is commonly deemed more secure than local storage because it automatically deletes data when the browser or tab is closed. However, similar to local storage, session storage is susceptible to XSS attacks.

Which type of cookies are safer session cookies or persistent cookies? ›

Session cookies vs Persistent cookies
FeatureSession CookiesPersistent Cookies
Storage spaceDoesn't occupy much spaceMay occupy storage space over time
Privacy ConcernsCan potentially track users, leading to privacy concernsUsed for targeted advertising and tracking, potentially raising privacy concerns
3 more rows

Are cookie sessions secure? ›

Session cookies are temporary and are automatically deleted when a user closes their browser. This means that they do not take up any space on the user's device. Session cookies can be used to keep a user's information secure because they only last for the duration of a single browsing session.

Top Articles
Poshmark Shipping: How Does It Work For Sellers?
On-Grid and Off-Grid Solar System| Understanding the Difference | Avaada
Frederick County Craigslist
Maria Dolores Franziska Kolowrat Krakowská
Ret Paladin Phase 2 Bis Wotlk
Workday Latech Edu
Poplar | Genus, Description, Major Species, & Facts
Select The Best Reagents For The Reaction Below.
Bank Of America Appointments Near Me
Dark Souls 2 Soft Cap
How Quickly Do I Lose My Bike Fitness?
Raid Guides - Hardstuck
Inevitable Claymore Wow
Lenscrafters Huebner Oaks
Gwdonate Org
The Witcher 3 Wild Hunt: Map of important locations M19
Rainfall Map Oklahoma
Patrick Bateman Notebook
2 Corinthians 6 Nlt
Parentvue Clarkston
Scotchlas Funeral Home Obituaries
R. Kelly Net Worth 2024: The King Of R&B's Rise And Fall
Galaxy Fold 4 im Test: Kauftipp trotz Nachfolger?
A Man Called Otto Showtimes Near Cinemark University Mall
Living Shard Calamity
Firefly Festival Logan Iowa
Craigslist Northern Minnesota
30+ useful Dutch apps for new expats in the Netherlands
Wcostream Attack On Titan
Workboy Kennel
Capital Hall 6 Base Layout
Craigslist Summersville West Virginia
Frcp 47
Rochester Ny Missed Connections
The Minneapolis Journal from Minneapolis, Minnesota
Überblick zum Barotrauma - Überblick zum Barotrauma - MSD Manual Profi-Ausgabe
Pokemon Reborn Gyms
Pa Legion Baseball
Doe Infohub
Gregory (Five Nights at Freddy's)
Sechrest Davis Funeral Home High Point Nc
BCLJ July 19 2019 HTML Shawn Day Andrea Day Butler Pa Divorce
Po Box 101584 Nashville Tn
Ts In Baton Rouge
Benjamin Franklin - Printer, Junto, Experiments on Electricity
Sams Gas Price San Angelo
Dineren en overnachten in Boutique Hotel The Church in Arnhem - Priya Loves Food & Travel
Suppress Spell Damage Poe
Minute Clinic Mooresville Nc
Great Clips Virginia Center Commons
Nfsd Web Portal
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated:

Views: 6454

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.