Local Storage VS Cookies

Local Storage vs Cookies

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.

If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

You'll want to leave your session cookie as a cookie either way though.

As per the technical difference, and also my understanding:

  1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domainSO Question also mentions it.

  2. localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.

Cookie or local storage?

Both cookies and local storage are similarly susceptible to being tampered with on the client-side: the client can see and modify both, and so can any (possibly malicious) extensions they have. But if the connection to your site is over HTTPS and their browser/OS/hardware doesn't have something malicious snooping on things, then there shouldn't be an issue with either cookies or local storage.

The main difference between them is that cookies get sent to the server with every network request, whereas local storage stays on the user's hard drive and doesn't get sent to the server.

Cookies are arguably a little bit more vulnerable than local storage because if a cookie gets sent over an unencrypted connection, it can be intercepted - but local storage stays on the client's machine, so there's less chance of it being intercepted by something malicious. But if the connection is encrypted, which it should be, using cookies will be fine.

If your script requires the token to be sent with requests to the server, you should probably use cookies so you can examine them on your back-end. (If you use local storage instead, you'll have to manually send the token with every request, which is still possible, but a bit inelegant given that cookies can do the same thing without requiring manual intervention on your part.)

If your script doesn't require the token to be sent with every request, then feel free to use local storage instead if you want. If the server never needs to see the token after it's been generated, then don't use cookies, since it'll be unnecessary overhead for no reason.

The same general logic above applies to any data on the client-side. If the server often or sometimes needs to see it, cookies are a good choice, if the data isn't too large. If the server never needs to see it, cookies are the wrong choice.

localStorage vs sessionStorage vs cookies

localStorage and sessionStorage are both so-called WebStorages and features of HTML5.

localStorage stores information as long as the user does not delete them.

sessionStorage stores information as long as the session goes. Usually until the user closes the tab/browser.

cookies are simply cookies, which are supported by older browsers and usually are a fallback for frameworks that use the above mentioned WebStorages.

In contrast cookies can store way less information then WebStorages and the information in WebStorages is never transferred to the server.

Keep in mind that the EU has a regulation that requires websites to inform their users about the usage of cookies. I dont know whether this also applies to WebStorages

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

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.

Localstorage Vs Cookies - Performance

Since cookies are server-side and Localstorage is client-side, which is the fastest for the user to retrieve?

You're starting off with an incorrect assumption. Cookies are stored client-side as well. Both localStorage and cookies are stored client side.

The difference however, and that cookies can be set, manipulated from the server side. localStorage is only workable from the client side.

I assume if the client's machine is slow, then cookies are faster? Or that makes no diffrence [sic]?

They are such lightweight operations I wouldn't worry about speed.

Performance between the two is not a factor for choosing one. It's what are your needs.

Cookies:

  1. Have worked in browsers for a long time. Every modern, and not so modern, browser support cookies.
  2. Can be accessed and manipulated server side.
  3. Are typically limited to a few kilobytes, depending on browser.

localStorage:

  1. Is a relatively new concept. Not all browsers support it. IE 6, 7 for example, and you're out of luck.
  2. Is inaccessible from the server side. You could make an AJAX call back to the server with data that is stored in localStorage.
  3. Have a W3C recommendation of being able to store 5 MB.

How can I make this faster?

I don't think either one can directly introduce a performance problem. Other problems, like waiting for the DOM to be in ready state, waiting for script files to load; etc. can introduce slowdowns.

Is using cookies to store minor details of the client better than local storage?

Cookies are transferred by the client to the server on every request. If the data being transferred is something that the server frequently has to access - like a session cookie, so that the server can easily tie a given request with a particular user and their credentials/settings - that's the perfect situation for using a cookie. httpOnly makes it more secure because only the server can read it.

If the data you want to store is not often read by the server, then cookies may not be the right choice, because cookies get sent by the client on every request; putting the data into cookies could be resulting in unnecessary overhead.

For data that the client needs to send that's security sensitive, like a session token, I'd recommend cookies with httpOnly, because that'll make possible XSS attacks much more difficult to execute.

For data that isn't security sensitive - like layout preferences - storing it in Local Storage will definitely make more sense if the data is only read/written by the client.

For your situation, consider whether the userType and other flags are essential to keep secret - it sounds like they may not be. Then, if they're only used by the client, Local Storage is the more appropriate choice. If the server does occasionally need use of them, you could put it into non-httpOnly cookies - or not, whatever makes your workflow easier.

Understanding Local Storage & Cookies in Javascript

localStorage is an API that the browser provides to allow you to read and write data. You can kind of imagine it as a single large JavaScript object, storing data values under different keys. Using it is easy: localStorage.setItem(key, value) (for some key and value, e.g. localStorage.setItem('test', 23)) to write a value and localStorage.getItem(key) to read/access that value. Details and examples can be found here

Cookies are accessed through the API document.cookie. document.cookie also uses pairs of keys and values (the cookies) to store data; however, the approach for reading and writing cookies is different. To create a new cookie, you enter document.cookie = "key=value" (for some key and value, e.g. document.cookie = "test=23"). To see all cookies, enter document.cookie, which will spit out all cookies as a string of keys and values, separated by semicolons (e.g. "test=23; someOtherKey=59"). Unfortunately, this makes reading cookie values a little trickier than with localStorage; the simplest way to get the value for a single key would be to use a Regular Expression, a specific pattern for matching text. More details and examples can be found here.

In terms of how you use them, they're similar in that they both are used for storing data. However, cookies are mainly sent to the browser from the server along with the page; localStorage, in contrast, is only accessible to the JavaScript code in the browser.

Hope this helps!

[EDIT]

See also

Whats the difference between web cookies and Local storage?

There're some rather inaccurate statements in your question. Re:1 - redux doesn't persist data forever in browser. This is actually what localStorage, cookies and local DB does.

But with that correction in mind, it's a good question.

  1. redux state is the most "reactive" one. It's aim is to let components within your app to have access to the "single source of truth". It stores data directly in JS, in memory. It can be quickly accessed and updated by your components, without any medium (like local storage), that's why it's handy for it's purposes.

  2. local storage indeed is capable in storing data in your browser forever. However, reading from it and writing to it takes extra time and burden in order to keep data sync, because you can't interact with it synchronously, it's not the best choice for using as primary data source for your component. But it's good to hydrating some data on app inits (for example, you can store the JWT token there, and then hydrate it into the redux store in app load - it's a common pattern)

  3. Cookies is not a good place to store the info in broad sense. It's rather a placeholder for storing some session-specific identifiers for communicating them to your backend. Check out this one for more info: https://medium.com/datadriveninvestor/cookies-vs-local-storage-2f3732c7d977#:~:text=Differences%20between%20cookies%20and%20localStorage&text=Cookies%20are%20mainly%20for%20reading,you%20more%20to%20work%20with.

what are cookies? Is it a kind of local storage?

What are cookies?

  • HTTP cookies are small blocks of data created by a web server while a user is browsing a website and placed on the user's computer or other device by the user's web browser. Cookies are placed on the device used to access a website, and more than one cookie may be placed on a user's device during a session.

What are they used for?

  • When you visit a website, your web server transfers a small packet of data to your device's browser: a computer cookie. This cookie is designed to remember information about you, including a record of your website visits and activity.

Are some browser cookies harmful?

  • Since the data in cookies doesn't change, cookies themselves aren't harmful. They can't infect computers with viruses or other malware. However, some cyberattacks can hijack cookies and enable access to your browsing sessions. The danger lies in their ability to track individuals' browsing histories.

Where are browser cookies stored?

  • In the browser lol


Related Topics



Leave a reply



Submit