Cookies vs localStorage vs sessionStorage in JavaScript

Back in 2012, I posted How to store JavaScript values persistently, locally (a post that is apparently a bit broken).  I figured that it might be time to revisit the topic.

Let’s start by looking at how to create and read cookies, first.

See the Pen
How to use cookies!
by Joe Steinbring (@steinbring)
on CodePen.

In the above example, we are creating a cookie called “cookieName” and setting it to expire in 365 days.  Cookies have the downside that you can only store 4kb of data per domain and you have to set the expiry manually.

So, let’s look at localStorage, next.

See the Pen
How to use localStorage!
by Joe Steinbring (@steinbring)
on CodePen.

In the above localStorage example, we are creating a localStorage object that’s called “lsName”.  It has the benefit of never expiring and having a capacity of 5mb per domain.

So, what about sessionStorage?

See the Pen
How to use sessionStorage!
by Joe Steinbring (@steinbring)
on CodePen.

In the above sessionStorage example, we are creating an object called “ssName”.  Like localStorage, sessionStorage has a capacity of 5mb per domain.  Unlike localStorage, the object is only available on the tab where the object was created.  As soon as the tab is closed, the object expires.

Local storage and session storage are also referred to as web storage.  Really, the only reason to use cookies instead of web storage is if you are writing for an HTML4-based browser, which would be crazy.

 

[ Cover photo by JOSHUA COLEMAN on Unsplash ]

3 thoughts on “Cookies vs localStorage vs sessionStorage in JavaScript

  1. OK.. well I hope the formatting isn’t too bad here…

    My approach was to store a stringified object into localstorage. That allows me to add an “expiresAt” variable to the object.

    Here is the code that creates the ls object. Note: I have already read in a “band” object from my API:

    // (the expiry var & key var were passed into the function)
    const key = cleanBandname;
    const expiry = 2 * 604800000; // 2 weeks
    const now = new Date();
    const expiry = now.getTime() + ttl;
    band.expiresAt = expiry;
    // console.log(‘writing ls cache for:’, key);
    localStorage.setItem(key, JSON.stringify(band));

    Here is the code that reads in the localstorage object if the current time is less than the 2 week expiration date, otherwise it deletes it:

    const cleanBandname = bandname.toLowerCase().replace(/\s/g, ‘+’);
    const now = new Date();
    let cachedArtist = null;
    const cachedArtistString = localStorage.getItem(cleanBandname);
    if (cachedArtistString && cachedArtistString.length) {
    cachedArtist = JSON.parse(cachedArtistString);
    // This code will delete the ls object if it is expired
    if (cachedArtist.expiresAt < now.getTime()) {
    localStorage.removeItem(cleanBandname);
    cachedArtist = null;
    }
    }

Leave a Reply

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