What is the difference between localStorage, sessionStorage, session and cookies?
Asked Answered
H

11

783

What are the technical pros and cons of localStorage, sessionStorage, session and cookies, and when would I use one over the other?

Houstonhoustonia answered 8/11, 2013 at 20:2 Comment(4)
This is also a related topic good to have a look : HTML5 Local storage vs. Session storage ( #5523640 )Edward
Also note that session cookies live as long as browser WINDOW is open (not tab in which they were set) BUT sessionStorage is nulled as soon as you close the tab...Teddie
Yes session is also type of cookie. The characteristic is it is transient where the cookie is persistenceAdit
@Teddie A particular browser window is an irrelevant UI element.Mariken
A
911

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.

localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.

localStorage and sessionStorage

localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).

Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

Cookies

This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.

As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.

localStorage vs. sessionStorage vs. Cookies

In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.

Client-side vs. Server-side

As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).

As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.

The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.

Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.

localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.

For further reading on client storage technologies see Dive Into Html 5.

Ammeter answered 8/11, 2013 at 22:20 Comment(16)
Beware: sessionStorage, localStorage are not appropriate for authentication information. They are not automatically sent to the server. This means that if a user changes the URL manually, or clicks on HTML links, you will not get authentication information. Even if you rewrite HTML links, you are forced to pass the authentication information over the URL which is a security no-no. At the end of the day, you will be forced to use Cookies. See https://mcmap.net/q/55326/-binding-tab-specific-data-to-an-http-get-request/14731 for a related topic.Replace
Will sessionStorage be deleted when the window is closed, or the tab?Joanejoanie
The sessionStorage will be deleted when the tab is closed.Carcinogen
@Replace why is passing the auth info over the URL the only option if not using cookies? Why not pass it in a HTTP header?Gothic
@Gothic because actions like "Page Reload", "View Source" and others will not allow you to configure a custom HTTP header to be sent.Replace
@Replace If you don't need authentication for static resources (html, imgs, etc), and only need it for data requests which will be written in JS where you can always set headers, I think storing it in local storage should be viable, unless you have further reasoning against it.Kerley
@Replace Your correct to say that it does not send automatically, but your not correct to say its not appropriate. I use localStorage and sessionStorage in many different production applications i have out for my clients and have not had one vulnerability due to relying on localStorage/sessionStorage coupled with sending the id and a token in the headers. Less load on the server even. Also i bind an event to the page reload and application loading hooks to ask my backend if this users authenticated still. Works great. Happy authenticating! EDIT: A CSRF token with all that adds even more security.Elanorelapid
@Carcinogen That's not true, actually. sessionStorage lasts through the browser session.Hitoshi
@Hitoshi browser persists the data using sessionStorage? AFAIR that's the difference between localStorage and sessionStorageCarcinogen
@Carcinogen localStorage persists forever until deleted, sessionStorage persists through the life of the browser session (similar to a per-session cookie). You can test this by opening up the console and setting a sessionStorage item, and closing the tab (not the browser), then going back to the same website and looking at the sessionStorage object.Hitoshi
ALSO: Session cookies live as long as browser WINDOW is open (not tab in which they were set) BUT sessionStorage is nulled as soon as you close the tab...Teddie
Great point about localStorage vs. document.cookie: that the cookie will be sent with every single request to the server. I just finished an application that uses cookies to save quiz results, but as I don't need to see them server-side, I could/should have saved them in localStorage to lighten my request/response times a bit. Also good to know that localStorage can also store JS primitives while cookies only store strings.Nunes
I not quite convinced with-In terms of capabilities, cookies only allow you to store strings. sessionStorage and localStorage allow you to store JavaScript primitives. I tried storing various primitive data types e.g. string, number, boolean into cookies. They all get saved into cookies as strings. How that is a shortcoming or a difference in behavior as compared to localStorage or sessionStorage. I also stored a boolean variable having value true into localStorage but when I retrieved it into another variable and did typeof then it also says string. So even localStorage uses strings.Marcimarcia
@Marcimarcia I have read through the specs and documentation for both sessionStorage and localStorage and it appears that you are correct in that both keys and values are stored as strings (specifically DOMStrings developer.mozilla.org/en-US/docs/Web/API/DOMString). I am not sure if the specification has changed or I misunderstood sources at the time given truthiness in ECMAScript - I will update the answer.Ammeter
@Ammeter you're saying that: > The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications. but also: > if you are wanting to store sensitive data then the session is really your only option (in the cookies paragraph) Can you elaborate? I mean so how is session storage not good, and later you claim in cookies parapgraph that it's ok? RegardsPavid
@Pavid You are conflating sessionStorage the browser technology (see developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) and session state that a web application framework may use on the server side. sessionStorage is within the browser and as such can be read and manipulated by the user or by any scripts an attacker can inject into the page. If you re-read the answer with that in mind then hopefully this will make more sense to you.Ammeter
H
138
  1. LocalStorage

    Pros:

    1. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
    2. The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
    3. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

    Cons:

    1. It works on same-origin policy. So, data stored will only be available on the same origin.
  2. Cookies

    Pros:

    1. Compared to others, there's nothing AFAIK.

    Cons:

    1. The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
    2. The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

    Typically, the following are allowed:

    • 300 cookies in total
    • 4096 bytes per cookie
    • 20 cookies per domain
    • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)
  3. sessionStorage

    Pros:

    1. It is similar to localStorage.
    2. The data is not persistent i.e. data is only available per window (or tab in browsers like Chrome and Firefox). Data is only available during the page session. Changes made are saved and available for the current page, as well as future visits to the site on the same tab/window. Once the tab/window is closed, the data is deleted.

    Cons:

    1. The data is available only inside the window/tab in which it was set.
    2. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Checkout across-tabs - how to facilitate easy communication between cross-origin browser tabs.

Habitable answered 4/6, 2017 at 20:59 Comment(6)
Cookies : "The data is sent back to the server for every HTTP reques". In some use cases (like in authentication process) this may considered as an advantage as well. sessionStorage: "Changes are only available per window (or tab in browsers like Chrome and Firefox)". I think it's better to formulate it "Changes are only available during the page session". A page session lasts for as long as the browser is open and survives over page reloads and restores (from MDN: developer.mozilla.org/en/docs/Web/API/Window/sessionStorage)Repossess
Updated! Thanks @DenizToprakHabitable
@softvar: sessionStorage - Con 2. : "The data is not persistent i.e. it will be lost once the window/tab is closed." - This is definitely not a defect. I would say it's an advantage. It's "session" storage after all. It is designed to work that way.Vietnam
@Vietnam Yea, you're right. I thought it in terms of storing some data locally. Have updated the answer. Thanks for pointing that out.Habitable
@Habitable you said sessionStorage is available for a future visit within the same window. Isn't sessionStorage life is till the page is existing? which makes it destroyed when a tab or window is closed. If it is as i said how is closing a site and again opening it in the same window, make my previously stored sessionStorage available?Cephalometer
Under sessionStorage you say "Changes made are saved and available for the current page, as well as future visits to the site on the same window". I think this last part is misleading, and I recommend removing it. It implies that if you open another tab and navigate to the same site, it will use the same sessionStorage. This is not the case. Each tab has its own sessionStorage context.Threshold
R
107

OK, LocalStorage as it's called it's local storage for your browsers, it can save up to 10MB, SessionStorage does the same, but as it's name saying, it's session based and will be deleted after closing your browser, also can save less than LocalStorage, like up to 5MB, but Cookies are very tiny data storing in your browser, that can save up 4KB and can be accessed through server or browser both...

I also created the image below to show the differences at a glance:

LocalStorage, SessionStorage and Cookies

Revengeful answered 17/2, 2018 at 7:37 Comment(0)
N
30

Here is a brief review that is easy to understand and comprehend quickly.

enter image description here

from instructor Beau Carnes from freecodecamp

Neville answered 1/6, 2020 at 22:53 Comment(0)
I
28

These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.

Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.

Local Storage does the same thing, but persists even when the browser is closed and reopened.

You can set and retrieve stored data as follows:

sessionStorage.setItem('key', 'value');

var data = sessionStorage.getItem('key');

Similarly for localStorage.

Intestate answered 28/1, 2016 at 18:55 Comment(1)
Just to add - for sessionStorage even a new tab is a new window. So anything stored for a specific domain in one tab will not be available to same domain in next tab.Marcimarcia
D
23

Exact use case -

  • If you want your page to always hold some data that is not confidential, then you can use localStorage.
  • If the server needs to know some information like authentication keys, you should use cookies to store them.
  • sessionStorage can be used to store the state of the interface, i.e., whenever you visit a page, customize it, visit another page and return to the same page, you would want to show the page how the user customized it. That’s a good use case for sessionStorage.

enter image description here

Dart answered 25/1, 2022 at 9:14 Comment(1)
Just one note, cookies are editable by users, yes! But you can flag them as httpOnly or use the secure flag, and then they stop being editable, and cannot be deleted by javascript. What's more is that you can encrypt them, to then later decypher on the server-side using some secret key. And if you really wanna kick security up a notch, you can even throw in some SALT into the mixture.Haye
B
10

The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies. The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage. — invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin (domain).

Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads.

localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');

The keys and the values are always strings. To store any type convert it to String and then store it. It's always recommended to use Storage interface methods.

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('Converting String to Object: ', JSON.parse(retrievedObject));

The two mechanisms within Web Storage are as follows:

  • sessionStorage maintains a separate storage area for each given originSame-origin policy that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  • localStorage does the same thing, but persists even when the browser is closed and reopened.

Storage « Local storage writes the data to the disk, while session storage writes the data to the memory only. Any data written to the session storage is purged when your app exits.

The maximum storage available is different per browser, but most browsers have implemented at least the w3c recommended maximum storage limit of 5MB.

+----------------+--------+---------+-----------+--------+
|                | Chrome | Firefox | Safari    |  IE    |
+----------------+--------+---------+-----------+--------+
| LocalStorage   | 10MB   | 10MB    | 5MB       | 10MB   |
+----------------+--------+---------+-----------+--------+
| SessionStorage | 10MB   | 10MB    | Unlimited | 10MB   |
+----------------+--------+---------+-----------+--------+

Always catch LocalStorage security and quota exceeded errors

StorageEvent « The storage event is fired on a document's Window object when a storage area changes. When a user agent is to send a storage notification for a Document, the user agent must queue a task to fire an event named storage at the Document object's Window object, using StorageEvent.

Note: For a real world example, see Web Storage Demo. check out the source code

Listen to the storage event on dom/Window to catch changes in the storage. fiddle.


Cookies (web cookie, browser cookie) Cookies are data, stored in small text files as name-value pairs, on your computer.

JavaScript access using Document.cookie

New cookies can also be created via JavaScript using the Document.cookie property, and if the HttpOnly flag is not set, existing cookies can be accessed from JavaScript as well.

document.cookie = "yummy_cookie=choco"; 
document.cookie = "tasty_cookie=strawberry"; 
console.log(document.cookie); 
// logs "yummy_cookie=choco; tasty_cookie=strawberry"

Secure and HttpOnly cookies HTTP State Management Mechanism

Cookies are often used in web application to identify a user and their authenticated session

When receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header.

Set-Cookie: <cookie-name>=<cookie-value> 
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>

Session cookies will get removed when the client is shut down. They don't specify the Expires or Max-Age directives.

Set-Cookie: sessionid=38afes7a8; HttpOnly; Path=/

Permanent cookies expire at a specific date (Expires) or after a specific length of time (Max-Age).

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

The Cookie HTTP request header contains stored HTTP cookies previously sent by the server with the Set-Cookie header. HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property, the XMLHttpRequest and Request APIs to mitigate attacks against cross-site scripting (XSS).

Cookies are mainly used for three purposes:

  • Session management « Logins, shopping carts, game scores, or anything else the server should remember
  • Personalization « User preferences, themes, and other settings
  • Tracking (Recording and analyzing user behavior) « Cookies have a domain associated to them. If this domain is the same as the domain of the page you are on, the cookies is said to be a first-party cookie. If the domain is different, it is said to be a third-party cookie. While first-party cookies are sent only to the server setting them, a web page may contain images or other components stored on servers in other domains (like ad banners). Cookies that are sent through these third-party components are called third-party cookies and are mainly used for advertising and tracking across the web.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

GitHubGist Example


As summary,

  • localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit.
  • sessionStorage object does not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window.
  • Web Storage (session, local) allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie.
  • Cookies that are used for sensitive actions should have a short lifetime only.
  • Cookies mainly used for advertising and tracking across the web. See for example the types of cookies used by Google.
  • Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage and sessionStorage) and IndexedDB.
Backbite answered 16/3, 2018 at 14:27 Comment(0)
H
9

Local storage: It keeps store the user information data without expiration date this data will not be deleted when user closed the browser windows it will be available for day, week, month and year.

In Local storage can store 5-10mb offline data.

//Set the value in a local storage object
localStorage.setItem('name', myName);

//Get the value from storage object
localStorage.getItem('name');

//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege

Session Storage: It is same like local storage date except it will delete all windows when browser windows closed by a web user.

In Session storage can store upto 5 mb data

//set the value to a object in session storege
sessionStorage.myNameInSession = "Krishna";

Session: A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values.

Cookies: Cookies are data, stored in small text files as name-value pairs, on your computer. Once a cookie has been set, all page requests that follow return the cookie name and value.

Histo answered 29/6, 2018 at 20:3 Comment(0)
R
7

LocalStorage:

  • Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. Available size is 5MB which considerably more space to work with than a typical 4KB cookie.

  • The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.

  • The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

  • It works on same-origin policy. So, data stored will only be available on the same origin.

Cookies:

  • We can set the expiration time for each cookie

  • The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.

  • The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

sessionStorage:

  • It is similar to localStorage.
  • Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted The data is available only inside the window/tab in which it was set.

  • The data is not persistent i.e. it will be lost once the window/tab is closed. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Rama answered 4/3, 2019 at 6:28 Comment(0)
S
2

localStorage

  1. data stored with localStorage has no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data.
  2. The storage limit is the maximum amongst the three.
  3. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
  4. It works on the same-origin policy. So, data stored will only be available on the same origin.

sessionStorage

  1. It stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
  2. Data is never transferred to the server.
  3. Changes are only available per window (or tab in browsers like Chrome and Firefox). Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.
Spalding answered 12/12, 2021 at 17:50 Comment(0)
G
0

I would expect that sessionStorage would be faster as it doesn’t need to write to the disk (lacking persistency). But my simple console tests shows that they are equal in performance 😔

let item = 500000;
const start = Date.now();

while(item) {
  sessionStorage.setItem('testKey', item);
  item = parseInt(sessionStorage.getItem('testKey'));
  item--;
}

console.log('SessionStorage PERF: (lower is better)', Date.now() - start);

same code for local storage

let item = 500000;
const start = Date.now();

while(item) {
  localStorage.setItem('testKey', item);
  item = parseInt(localStorage.getItem('testKey'));
  item--;
}

console.log('LocalStorage PERF: (lower is better)', Date.now() - start);

results:

SessionStorage PERF: (lower is better) 2889
SessionStorage PERF: (lower is better) 2852
LocalStorage PERF: (lower is better) 2807
LocalStorage PERF: (lower is better) 2889
Gilemette answered 9/2, 2023 at 10:15 Comment(1)
Could someone explain why downvoting, it would be very appritiated feedback, thanksGilemette

© 2022 - 2024 — McMap. All rights reserved.