Cartoon space rocket flying in the stars

Cookie, localStorage and sessionStorage in Javascript

Bien Vu

|

In the current development process, increasing the user experience when accessing websites is very necessary and important.
From those specific requirements, we have technologies to improve the performance and quality of web pages such as using cookie, localStorage, or sessionStorage.

To understand more deeply we will go into specific current technologies, let's find out what those technologies are and how to use them as well as compare the differences between those technologies.

1, What is cookie?

Cookie is data that is stored in a text file, and is located on the computer, so the storage of cookie will be permanent or a specific time, all set by you. However, each domain only has a maximum cookie size, so be careful in case you need to save too much data.

Here are the basic way to create a cookie with Javascript:

// Create a simple cookie without expires
document.cookie = "website=lilengine.co";

// Create a simple cookie with expires
document.cookie = "website=lilengine.co; expires=Thu, 14 OCT 2022 12:00:00 UTC";

// Create a simple cookie with expires and path
document.cookie = "website=lilengine.co; expires=Thu, 14 OCT 2022 12:00:00 UTC; path=/";

// Delete a cookie we need to set a time in the pass.
// Example
document.cookie = "website=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

 

2, What is localStorage?

Local Storage is a new feature introduced to HTML5, which allows you to store data locally on the client machine via JavaScript. Data stored in Local Storage is stored in key-value pairs and has no expiration date, meaning everything will be retained even after the browser window is closed.

Local Storage is synchronous, meaning that it cannot be accessed in parallel, but it will respond to each execution call in order.

Another big minus of Local Storage is that it has no method to protect data stored in the browser. Any javascript code in the website can access the values stored in Local Storage.

Local Storage provides 5 methods to manage data storage for web applications:

// Save data to localStorage
sessionStorage.setItem("key", "value");

// Get saved data from localStorage
let data = sessionStorage.getItem("key");

// Remove saved data from localStorage
sessionStorage.removeItem("key");

// Remove all saved data from localStorage
sessionStorage.clear();

// localStorage.key() is commonly used to cycle through all objects in localStorage.
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
  console.log( localStorage.getItem( localStorage.key( i ) ) );
}

3, What is sessionStorage?

Session Storage is basically the same as Local Storage but it only stores data for one session, and it will be deleted when we close the browser tab or close the browser.

sessionStorage provides 5 methods to manage data storage for web applications:

// Save data to sessionStorage
sessionStorage.setItem("key", "value");

// Get saved data from sessionStorage
let data = sessionStorage.getItem("key");

// Remove saved data from sessionStorage
sessionStorage.removeItem("key");

// Remove all saved data from sessionStorage
sessionStorage.clear();

// localStorage.key() is commonly used to cycle through all objects in localStorage.
sessionStorage.key()

4, Compare between Cookie, localStorage, and sessionStorage.
 

 

Cookie

 Local Storage 

 Section Storage 

Location

Browser and Server

Browser Only

Browser Only

Data Type

String only

String only

String only

Sent with request

Yes

No

No

Capacity

4KB

10MB

5MB

Browser support

HTML 4 / 5

HTML 5

HTML 5

Accessible from

Window

Window

Same Tab

Expiration

Manually Set

Never

On tab close

5, When do we use Cookie, localStorage, or sessionStorage?

Cookie is usually used to log in, and save some basic and simple values. Cookie are not limited by size or characters. However, because it moves from Client to Server and vice versa according to the Header Request. So they are as light as possible. Among the ways to speed up the website, reducing Cookie is a good idea

localStorage or sessionStorage is used in several user preferences: languages, themes, selected product categories, custom skins, dashboards, layouts, and wishlists...

6, Some notes when using Cookie, localStorage, or sessionStorage

Cookie

  • The expire/max-age time should be specified. Normally, only one cookie containing authentication information should be allowed for about 3-4 months. To avoid the user having to login multiple times, we provide an option to store the information so that the user does not need to log in again next time.
  • Never store a user's original password, encrypt it, or use token-based authentication.

Local Storage and sessionStorage

  • Do not store sensitive data on Local Storage, as no security measures are in place. Although domains cannot cross-access each other's Local Storage, cross-site scripting attacks can still expose passwords or other sensitive things in Local Storage.
  • It is not an alternative to databases at the server because it only stores data in the browser as strings, with limited size.
  • The 5MB limit may be large compared to cookie, but to cache, an entire web application running without a server is still quite limited.
  • It is synchronous, so data requests cannot be accommodated simultaneously
  • sessionStorage: limited to one browser window or tab. A web page opened in two tabs of the same browser also cannot access each other's data. So, when you close the website, the data stored in the current sessionStorage is also deleted.

  • localStorage: mutually accessible between browser windows. Data will be stored indefinitely.

 

 

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Comments

  • Allowed HTML tags: <em> <strong> <cite> <blockquote cite> <ul type> <ol start type> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
  • Use [gist:#####] where ##### is your gist number to embed the gist
    You may also include a specific file within a multi-file gist with [gist:####:my_file].

Spread the word