DEV Community

Joe Steinbring
Joe Steinbring

Posted on • Originally published at blog.jws.app on

2 2

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.

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more