Difference between session vs Localstorage vs Cookies in JS

In this blog, I’m going to explain the difference between Session, LocalStorage, and Cookies in Javascript.

Difference between SessionStorage and LocalStorage

SessionStorage and localStorage are two JavaScript web storage classes that let you store key-value data pairs on the client-side. The amount of time that the data is kept is the primary distinction between the two:

SessionStorage : Data is kept for the length of a single browser session in sessionStorage. When the browser is closed, the data is removed.

LocalStorage: Information is kept on the client side indefinitely unless it is specifically erased by the user or the developer.

But What about cookies ?

On the other hand, cookies are tiny text files that the server stores on the client’s computer. They are frequently used to store data such as user preferences, login information, and the contents of shopping carts. Cookies can be configured to expire after a certain period of time or when the browser is closed, unlike sessionStorage and localStorage. Every request also includes cookies that are sent back to the server, enabling it to keep track of and retain the state across different requests made by the same client.

Here is some sample JavaScript code that demonstrates how to utilise localStorage, sessionStorage, and cookies:

// Local Storage
localStorage.setItem("username", "JohnDoe");
console.log(localStorage.getItem("username")); // Output: "JohnDoe"

// Session Storage
sessionStorage.setItem("cart", JSON.stringify([1, 2, 3]));
console.log(JSON.parse(sessionStorage.getItem("cart"))); // Output: [1, 2, 3]

// Cookies
function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)===' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
    return null;

setCookie("username", "JohnDoe", 7);
console.log(getCookie("username")); // Output: "JohnDoe"

In this example, I am showing how to add, remove and get the values from LocalStorage, SessionStorage, and cookies, respectively. Note that in the case of cookies, I also included a function to set the expiration time of the cookie in days.

In summary, sessionStorage and localStorage are client-side storage options and cookies are stored on the client side and sent back to the server on every request and used for maintaining state across multiple requests

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories