DEV Community

Cover image for Cookies vs LocalStorage Vs SessionStorage
gaurbprajapati
gaurbprajapati

Posted on

Cookies vs LocalStorage Vs SessionStorage

Cookies vs Local Storage Vs Session Storage

Session Storage:

Session storage is a web storage mechanism provided by modern browsers to store data temporarily on the client-side. The data stored in session storage remains available as long as the browser tab or window is open and gets cleared when the tab or window is closed.

To use session storage in JavaScript, you can use the sessionStorage object, which provides methods to set, retrieve, and remove data. Here's an example that demonstrates how to use session storage:



// Storing data in session storage
sessionStorage.setItem("name", "John");
sessionStorage.setItem("age", "30");

// Retrieving data from session storage
const name = sessionStorage.getItem("name");
const age = sessionStorage.getItem("age");

console.log(name); // Output: John
console.log(age); // Output: 30

// Removing data from session storage
sessionStorage.removeItem("age");

// Clearing all data from session storage
sessionStorage.clear();


Enter fullscreen mode Exit fullscreen mode

In the above code, we use the setItem() method to store data in session storage. The first argument is the key, and the second argument is the value. To retrieve the data, we use the getItem() method, passing the key as the argument. To remove a specific item, we use the removeItem() method, and to clear all data, we use the clear() method.

Local Storage:

Local storage is another web storage mechanism provided by modern browsers to store data on the client-side. Unlike session storage, data stored in local storage persists even after the browser is closed and reopened. It remains available until explicitly cleared by the user or through JavaScript code.

To use local storage in JavaScript, you can use the localStorage object, which provides methods similar to session storage. Here's an example that demonstrates how to use local storage:



// Storing data in local storage
localStorage.setItem("name", "John");
localStorage.setItem("age", "30");

// Retrieving data from local storage
const name = localStorage.getItem("name");
const age = localStorage.getItem("age");

console.log(name); // Output: John
console.log(age); // Output: 30

// Removing data from local storage
localStorage.removeItem("age");

// Clearing all data from local storage
localStorage.clear();


Enter fullscreen mode Exit fullscreen mode

The code for local storage is similar to session storage. We use the setItem() method to store data, the getItem() method to retrieve data, the removeItem() method to remove a specific item, and the clear() method to clear all data.

Cookies:

Cookies are small pieces of data stored on the client-side by a website. They can be used to persist data between different requests or sessions. Cookies have an expiration date and can be set to be persistent or session-only.

To work with cookies in JavaScript, you can use the document.cookie property, which provides a string representation of all the cookies associated with the current document. Here's an example that demonstrates how to work with cookies:



// Setting a cookie
document.cookie = "name=John; expires=Thu, 1 Jan 2023 00:00:00 UTC; path=/";

// Retrieving a cookie
const cookies = document.cookie.split("; ");
cookies.forEach(cookie => {
  const [key, value] = cookie.split("=");
  console.log(key, value);
});

// Removing a cookie
document.cookie = "name=; expires=Thu, 1 Jan 1970 00:00:00 UTC; path=/";


Enter fullscreen mode Exit fullscreen mode

In the above code, to set a cookie, we assign a string to the document.cookie

property. The string follows the format "key=value". We can also set additional properties like expiration date, path, and domain.

To retrieve cookies, we split the document.cookie string by "; " to get an array of individual cookies. We can then split each cookie by "=" to get the key-value pairs.

To remove a cookie, we can set its expiration date to a past date, effectively invalidating it.

When choosing between session storage, local storage, and cookies, consider the following factors:

  • Session storage is suitable for data that needs to be available only during the user's session.
  • Local storage is suitable for data that needs to persist across sessions.
  • Cookies are suitable for small amounts of data and have additional options like expiration dates and domain restrictions.

Choose the appropriate storage mechanism based on your specific requirements and data persistence needs.

The main differences between session storage, local storage, and cookies are as follows:

  1. Data Persistence:

    • Session Storage: The data stored in session storage is available as long as the browser tab or window is open. It gets cleared when the tab or window is closed.
    • Local Storage: The data stored in local storage persists even after the browser is closed and reopened. It remains available until explicitly cleared by the user or through JavaScript code.
    • Cookies: Cookies can be set with an expiration date, making them either persistent or session-only. Persistent cookies remain on the user's device until the expiration date, while session cookies are cleared when the browser session ends.
  2. Storage Limit:

    • Session Storage: Typically, session storage allows a larger storage limit compared to cookies. It can store more data per domain.
    • Local Storage: Local storage also offers a larger storage limit compared to cookies. It can store significantly more data per domain.
    • Cookies: Cookies have a smaller storage limit compared to session storage and local storage. Each cookie can store a limited amount of data (usually a few kilobytes) per domain.
  3. Automatic Handling:

    • Session Storage: Session storage does not require manual handling of data expiration. The data is automatically cleared when the browser tab or window is closed.
    • Local Storage: Local storage does not have an automatic expiration mechanism. The data remains until explicitly cleared by the user or through JavaScript code.
    • Cookies: Cookies can have an expiration date set. Once the expiration date is reached, the browser automatically removes the cookie.
  4. Data Access:

    • Session Storage and Local Storage: Data stored in session storage and local storage can be accessed directly using JavaScript APIs, providing easy access and manipulation.
    • Cookies: Cookies can be accessed and modified using JavaScript APIs, but the access is more limited compared to session storage and local storage.
  5. Network Traffic:

    • Session Storage and Local Storage: Data stored in session storage and local storage does not get sent to the server with every HTTP request. It stays on the client-side, reducing unnecessary network traffic.
    • Cookies: Cookies are automatically sent to the server with every HTTP request for the corresponding domain, increasing the network traffic.

Conclusion
Session storage is suitable for storing temporary data during a user's session, local storage is ideal for persistent data that needs to be available across sessions, and cookies are useful for small amounts of data and have options for expiration and domain restrictions. Choose the storage mechanism based on your specific data requirements and the desired persistence behavior.

Top comments (3)

Collapse
 
panino5001 profile image
Andrés Fernández

It is also possible to use window.name, which allows storing 2MB of data, as a replacement for sessionStorage.

Collapse
 
tracker1 profile image
Michael J. Ryan

It's also available through frames and iframe boundaries, not sure if it still allows cross domain access though, it at least used to.

The article should also mention indexdb

Collapse
 
denys_dev profile image
denkochev

I'm looking for this kinda material for so long. Thank you, very usefull!