DEV Community

loading...

Cookies vs localStorage vs sessionStorage in JavaScript

Joe Steinbring
I write JavaScript (mostly Vue.js) by day and whatever interests me by night. I travel, have dogs, and enjoy playing with my ukulele.
Originally published at blog.jws.app on ・1 min read

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.

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.

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?

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.

Discussion (0)