Cookies VS Local Storage VS Session Storage: Usage and Differences

Robin
Updated on August 1, 2022

Understanding the differences between cookies, local storage, and session storage are essential for every developer. Otherwise, we could use them in the wrong ways.

While developing a website, many times we face the necessity of storing data in the browsers. In this situation, we will use browser storage. We have many types of client-side storage available in modern browsers.

But, do you really know the differences among those storages?

If the answer is no, you have come to the right place. In this post, I will show you every detail about cookies, local storage, and session storage.

You will also learn:

  • Their similarities.
  • How they are different from each other.
  • Why and when should you use those storage options?

Before learning about these 3 storage, you should know about the browser storage and client-side.

What is Browser Storage?

Since HTML5, modern browsers offer various types of options to store user data inside the browser. These storage options are known as browser storage. But they are different in their characteristics and use cases.

Before introducing HTML5, we only had cookies to store the data in the browser. But there are some limitations to using cookies.

That's why got other options like local storage and session storage. They minimize the limitations of cookies. Yet they have their own problems. They are also known as web storage.

That's why we must know about their benefits and limitations so that we can use them according to our requirements.

Why Should We Use Browser Storage to Store Data?

You might have a question in your mind that why we should store data in the browser. Because we can keep those data inside our database on the server-side.

If you can save information on the server side, we will not need to do the same thing on the client-side, right?

No, there are many situations when saving data on the client-side is the best option. We are talking about the client and server-side a lot.

What are the client-side and server-side?

The Client-side is everything that users see in the browser. It includes sending HTTP requests, downloading and processing scripts, styles, etc. It means everything that happens on the user's computer is called the client-side or front-end of a website.

On the other hand, the processing or activities that happen in the website server is called server-side or backend. A website backend handles clients' requests and manages the database to save and retrieve data.

These are some of the reasons to store information on the client-side instead of sending it all the way to the backend:

  • It increases the website performance and reduces response time. Because getting data from the client's browser is quicker than sending an HTTP request and getting it from the backend.
  • If the user has personalized settings and preferences, we can store those setting information in the browser. In this way, we can set different settings for each user. Like one user might choose the dark mode and another user might prefer the light mode.
  • We also store the login state of a user on the client side like session id or JWT token. Then we can send this to the backend with each request.
  • Sometimes we keep some data in the browser so that our users can access those without making any network connection.
  • Our users might need some information very frequently and if that information is not sensitive like a password, we can store them in the browser. It will reduce the number of server requests.
  • It not only improves the user experience but also saves the internet bandwidth of our users. Because they don't have to download the same data again and again from the server.

There are a lot of reasons for using browser storage like cookies, local storage, and session storage. They depend on the website's requirements.

But before storing something in the client's browser, we must consider the security of that information. Because some of them can be accessed using JavaScript.

Therefore, someone can steal that information. That's why we should know the differences in browser storage. We will also talk about security later in this post.

Also Read: Self Invoking Functions in JavaScript - Why Should You Use?

Cookies VS Local Storage VS Session Storage

Cookies can store up to 4 KB of data and browsers automatically send it on every HTTP request. On the other hand, local storage has the capacity to hold up to 10 MB of data, and it is 5MB for session storage. Browsers never send those data to the server automatically like the cookies.

There are also many other differences among these storage options. This is the list of their differences that you need to know:

CookiesLocal StorageSession Storage
Capacity4KB5MB10MB
Available AtHTML4/HTML5HTML5HTML5
AccessibilityAny windowAny windowAny window
ExpirationManually setNeverOn tab close
Browser SupportVery highVery highVery high
Supported Data TypesString onlyString onlyString only
Auto ExpiryYesNoYes
Storage LocationBrowser and ServerBrowserBrowser
Sent with RequestsYesNoNo
Editable and BlockableYesYesYes
SecurityMore secureLess secureLess secure
SSL SupportYesNoNo
Server Side AccessibilityYesNoNo

As you can see, every storage option has its own limitations. When we choose one of them we need to focus on the requirements of our website.

In that situation, understanding and knowing their differences will help you to decide which storage you should choose for your need. I will also show you in which situation each of them works the best.

Cookies VS Local Storage VS Session Storage: Usage and Differences

What is Cookie?

In HTML4, the cookie was introduced for storing data inside the client's web browser. It has a limited capacity in size compared to other storage. But there is a reason for this limited size.

In the traditional user authentication system, we use two things: cookies and sessions. We can set and get cookies using the NodeJS server.

The cookie is the piece of data that is stored in the browser and sent to the server on every HTTP request. If a cookie is set for a specific website, the browser will send that cookie every time the user makes a request to that website server.

That's why the cookie size needs to be small. Because it will take more time to send a large amount of data to the server. It is bad for the user experience.

When a server sends data as a cookie, browsers store that piece of data inside the cookie storage. Because this is the only storage that automatically sends it to the server with which a cookie is connected.

The characteristics of cookies in the browser:

  • It was available before HTML5 was introduced.
  • A cookie size can be up to 4KB.
  • Browsers automatically send data over HTTP requests.
  • It can be created, modified, or read using JavaScript.
  • There are 2 types of cookies: session cookies and persistent cookies.
  • It has support for SSL.
  • We can set an expiration date for cookies.
  • By setting the HttpOnly attribute we can forbid the accessibility using JavaScript.

If a cookie contains Expires or Max-Age attribute then it is a persistent cookie. If it doesn't have those attributes then it is called a session cookie.

What is cookie? How to use it and its pros and cons

Accessing Cookies Using JavaScript

You can set cookies using the JavaScript document object. To set cookies, we need to access the cookie property.

          document.cookie = "lang=js; Max-Age=10; Path=/; SameSite=Strict; Secure";
        

Here, I am setting the lang=js cookie. I am also using Max-Age, Path, SameSite, and Secure attributes.

We can also multiple cookies by following the same method.

          document.cookie = "lang=js; Max-Age=10; path=/; SameSite=Strict; Secure";
document.cookie = "theme=dark; Max-Age=10; path=/; SameSite=Strict; Secure";
        

To set multiple cookies, we have to set them separately using document.cookie object. Here I am setting lang and theme cookies at the same time.

Getting Cookies

Accessing cookies is very easy. Because we can get those cookies using the same document.cookie object. This object returns the cookies as a string.

          document.cookie
// "lang=js; theme=dark"
        

As you can see, the document.cookie is returning lang and theme cookies together.

Advantages of Cookies

  • It has SSL support.
  • It helps to authenticate users.
  • We can configure cookies using attributes.
  • You don't have to send cookie data manually to the server.
  • We can prevent anyone from accessing cookies using HttpOnly attribute.

Disadvantages of Cookies

  • We can only store plain string.
  • It can store a small amount of data.
  • Sensitive data should not be stored.
  • Anyone can edit or modify the cookie value.

Also Read: How to Get File Extensions in Node.js From Any Files

What is Local Storage?

Local storage is browser storage that can store data as a key/value pair. It was introduced with the HTML5 version. The strongest point of this storage is it can store a large amount of data compared to cookies.

It only accepts the string data type. You can easily set and retrieve information from the local storage. You can access data from the local storage by using localStorage object in JavaScript.

This object has 5 methods and 1 property. Using the property and methods, we work with this storage in JavaScript.

  • localStorage.setItem(key, value)
  • localStorage.getItem(key)
  • localStorage.removeItem(key)
  • localStorage.clear()
  • localStorage.key(index)
  • localStorage.length

The characteristics of local storage in the browser:

  • It only can store data in the form of key/value pairs.
  • It was introduced in HTML5.
  • The data size can be up to 10MB.
  • Browsers don't automatically send data over HTTP requests.
  • The data never gets expired automatically.
  • You can access the local storage via JavaScript.
  • It doesn't have SSL support.
  • The browser stores data until users manually remove or clear the memory of the browser.
  • It follows the same-origin policy. That means, data will only be available on the same origin.
What is local storage? How to use it and its pros and cons

Accessing Local Storage Using JavaScript

To set an item inside the local storage, we use the setItem() method. You have to pass the key name and the data as its value.

The key and value both will be strings. Then it will save the data under the key name that you have passed.

          localStorage.setItem('isAuthenticated', true);

localStorage.setItem(
    'token',
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4g'
);
        

Here, I am setting two items isAuthenticated and token. If you check the local storage, you will find them with the values.

You can also use the same method to update any value. You just have to call the setItem() method with the key that you want to update and pass the updated value.

Getting Date from Local Storage

To get back the stored date from the local storage, you have to specify the key name. Because as you have seen, every piece of data is saved under a specific key.

          const isAuthenticated = localStorage.getItem('isAuthenticated');
console.log(isAuthenticated);
// true

const token = localStorage.getItem('token');
console.log(token);
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4g
        

Deleting Item from Local Storage

The removeItem() method is used to remove an item from the local storage. It takes the key name of the item, you want to delete.

          localStorage.removeItem('token');

const token = localStorage.getItem('token');
console.log(token);
// null
        

Here, I have removed the token item from the storage. When I try to get the value for this key, it returns null because this key doesn't exist anymore.

Removing All Items from Local Storage

You can delete all items for the local storage by calling the clear() method. It doesn't accept any argument.

          localStorage.clear();
        

Advantages of Local Storage

  • The data doesn't have any expiration date.
  • Browsers never send data to the server.
  • It can store more data compared to other browser storage.

Disadvantages of Local Storage

  • It only stores plain text.
  • Data can be obtained on the client side.
  • Less secure by design because anyone can modify it.

Also Read: Easiest Way to Set & Use Environment Variables (.env) in Node.js

What is Session Storage?

Session storage is the part of the browser storage that will save data as key/value pairs. It only stores string values. When the browser tab is closed, data gets deleted automatically.

Like local storage, it was also introduced with HTML5. It looks similar to local storage but the difference is local storage data never gets expired.

JavaScript has 5 methods and 1 property to work with session storage. We can access the property and methods on the sessionStorage object.

  • sessionStorage.setItem(key, value)
  • sessionStorage.getItem(key)
  • sessionStorage.removeItem(key)
  • sessionStorage.clear()
  • sessionStorage.key(index)
  • sessionStorage.length

The characteristics of session storage in the browser:

  • Similar to local storage.
  • It was introduced in HTML5.
  • The storage limit is about 5MB.
  • Data is only accessible by JavaScript.
  • It doesn't have SSL support.
  • It only can store data in the form of key/value pairs.
  • Browsers don't automatically send data over HTTP requests.
  • Data gets deleted when the browser tab is closed.
  • One tab of the same website can not access the data of another tab
What is session storage? How to use it and its pros and cons

Accessing Session Storage Using JavaScript

The setItem() method is used to add or update a new item inside the session storage using JavaScript. It takes 2 arguments: key and value.

          sessionStorage.setItem('isAuthenticated', true);

sessionStorage.setItem(
    'token',
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibm'
);
        

Getting Items from Session Storage

We have the getItem() method to get the stored data from the session storage. We have to specify the key name of an item.

          const isAuthenticated = sessionStorage.getItem('isAuthenticated');
console.log(isAuthenticated);
// true

const token = sessionStorage.getItem('token');
console.log(token);
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibm
        

Deleting Items from Session Storage

We can delete any item from the session storage by calling the removeItem() method with the item's key name.

          sessionStorage.removeItem('token');

const token = sessionStorage.getItem('token');
console.log(token);
// null
        

Removing All Items from Session Storage

Like local storage, we also have access to the clear() method on sessionStorage object to delete all items from the session storage.

          sessionStorage.clear();
        

Advantages of Session Storage

  • It can store more data than cookies.
  • Another browser tab can not access data.
  • Browsers never send data to the server.
  • We can save some data specifically for a single tab.

Disadvantages of Session Storage

  • It only accepts plain text.
  • All data will be removed when the tab closes.
  • The client-side can read data using JavaScript.

Which Browser Storage Should You Use?

We have talked about 3 types of storage options available in web browsers. Each of them has its own use-cases. Therefore, to choose one of them you have to focus on the requirements of your application.

When should you use cookies?

  • If you want to store a small amount of data.
  • If you need to send data to the server for every request.
  • If you don't want to allow anyone to access it on the client side.
  • If you need to set any expiration date for the stored information.

When should you use local storage?

  • If we want to save a large piece of string.
  • If you need to access your data on the client side.
  • If you want to store it without any expiration date.
  • If you don't need to send it to the server for every request.

When should you use session storage?

  • If want to store more information than cookies.
  • If you need to access your data on the client side.
  • If you want to keep it for a specific tab in the browser.
  • If you need to delete it whenever the user closes the tab.
  • If you don't need to send data automatically on every HTTP request.

Now you can match your requirements with these situations to choose storage for your application.

Also Read: Easiest Way to Create Keyboard Shortcuts in JavaScript

Which Browser Storage is More Secure to Use?

When we talk about security let me clear that nothing is 100% secure. It is not possible. Because every piece of technology has its flaws. We just can try to make our application as secure as possible.

If we compare cookies, local storage, and session storage in terms of security, I would say cookies can provide more security for our information.

Because we can manually set an expiration date for our stored information and we also can restrict its accessibility on the client-side by using some security flag.

But we can't do the same thing for local storage and session storage. Therefore, they are more vulnerable to Cross-site script (XSS) attacks.

With this technique, hackers can steal the information stored in the browser if it is accessible by JavaScript. If we can set our cookies properly, JavaScript code will not be able to extract those cookies.

It doesn't mean cookies are completely secure. Because cookies are vulnerable to Cross-site request forgery (CSRF) attacks.

Between local storage and session storage, session storage will be a little more secure. Even though we can access this storage using JavaScript but it is tab specific.

One tab can not get data from another tab and the browser automatically deletes everything from the session storage when the tab is closed.

On the other hand, information from local storage never gets deleted, unless users remove them manually. It is also accessible using JavaScript from any browser tab.

Conclusion

We have talked about cookies, local storage, and session storage in detail. You have seen their characteristics and how they are different from each other.

I have tried to give you some situations so that you can decide when you should use which storage for your application. I know it totally depends on your choice and requirements.

You have seen how to add, modify, and delete information from these storage options. Different JavaScript methods are used to perform those activities. You can also learn more about those methods.

Now, you know which storage is more secure to use. Even if it seems like local storage has no security, it is the most used storage option in the browser. Because most of the time, we never save sensitive data on the browsers.

If we don't need security that much then local storage will be a good choice. Because it provides more space for us.

I hope you have understood the differences between cookies, local storage, and session storage from this post. It will help you to make the right choice.

Related Posts