September 19, 2020

Difference between cookies vs localstorage vs sessionstorage

Web applications prefer to store some information about application users on the client-side. This relieves the web servers from having to store information that provides personalized service to users on the server itself.

Client-side data storage is also a way to maintain state over stateless HTTP connections. HTTP requests are stateless because they don’t contain any information that informs the server on whether the current request is coming from a new user or a returning user. Client-side storage provides a compromise between the stateless nature of HTTP and the server’s need to know the user’s history.

This tutorial is focused on three such client-side data storage options: Cookies, Session Storage, and Local Storage. Let’s dive in and find out what are the similarities and differences between these three.

Cookies

You may have come across a website that asks you to “accept the cookies” during the first visit. Cookies have long been in use to store user data on the browsers. Unlike local storage and session storage, cookies are used to pass information back and forth between the browser and the server. Both the browser and the server can create and read cookies.

If a website uses cookies to keep track of user interactions, it creates a new cookie with your session information the first time you visit the website and store them in the browser. If you are logged in, session information includes the unique session-id that identifies you as a logged-in user. Cookies also store information that is used to personalize the web interface like your preferred language and location.

The stored cookie remains intact on the browser even if you reload the web page, visit another web page in the same domain, or close the tab or browser. When you visit the same website another day, the browser sends the cookie along with the HTTP request to tell the server that you have used this website before. The browser keeps the cookie until the expiration time if the user doesn’t manually delete the cookie.

Now, let’s see how to create and manipulate cookies on the client-side using Javascript. 

You can create a new cookie by accessing the cookie storage through document.cookie. Each cookie is stored as a key-value pair.

document.cookie = "name=adam" 
document.cookie = "age=24" 

Each key and value are encoded with EncodeURIComponent to escape invalid characters. Each key-value pair (each cookie) cannot exceed the size limit of 4 KB after the encoding. A single domain can store about 20 cookies at a time, a number that depends on the browser.

Cookie options are declared after the key-value pair, separated by semicolons.

You can set an expiration time or a maximum age for a cookie. If you don’t specify an expiration time or a maximum age, the cookie expires when the browser or the tab closes.

document.cookie = "name=adam; expires=Mon, expires=30 June 2020 20:04:20 UTC" // cookie expires on the specified date and time
document.cookie = "name=adam; max-age=3600" // maximum age 3600 seconds

To delete a cookie, you only have to set the expiration time to a past time or the maximum age to zero or minus value.

document.cookie = "name=adam; expires=30 June 2000 00:00:00 UTC"
document.cookie = "name=adam; max-age=0"
document.cookie = "name=adam; max-age=-1"

Setting the HttpOnly parameter prevents client-side scripts from accessing the cookie using document.cookie.

Web Storage API

Web storage API, which contains Local Storage and Session Storage, was introduced in HTML 5. Local storage and session storage have a larger storage space than a cookie. They store data as key-value pairs in the same way as a cookie, but the method of accessing and manipulating stored data is more intuitive.

Unlike cookies, web storage can be accessed only from the client-side. The browser does not send the data stored in local storage or session storage to the server with HTTP requests. You should not use web storage to store sensitive information because they are prone to cross-site scripting (unlike cookies with HttpOnly parameter).

Session and local storage function similar to one another in most cases, but there are a few key differences.

Session storage

Session storage can store, at most, 5 MB data that belongs to a particular domain. The data stored in session storage are preserved even after reloading the page or going to another web page in the same domain. But the data is destroyed when the tab or browser is closed. Session storage is used to persist data when moving from one web page to another in the same domain during a session.

Local Storage

Local Storage is the biggest of the three storage options. Unlike session storage, the data stored by the website is not destroyed after closing the browser or tab. In other words, data stored in local storage during one website visit are intact when you visit the same website a few days later unless they are manually cleared.

Local storage is used for tasks like storing data like shopping cart information on an E-Commerce website. With the shopping cart stored in the local storage, if you leave the website with a few items in your cart, these items will still be available in your cart the next time you visit.

Storing and Accessing Data with Web Storage

With session storage and local storage, storing data as key-value pairs and accessing stored data are performed in a similar manner.

You can add a key-value pair with Javascript like this.


localStorage.setItem("name", "adam")
localStorage.setItem("age", 34)

sessionStorage.setItem("name", "adam")
sessionStorage.setItem("age", 34)

You can access the stored value using the key.

localStorage.getItem("age") //34
localStorage.getItem("name") //adam

sessionStorage.getItem("age") //34
sessionStorage.getItem("name") //adam

Again, the key can be used to remove a key-value pair from the storage.


localStorage.removeItem("name")
sessionStorage.removeItem("age")

The built-in method clear is used to remove all the stored data and clear the storage.

localStorage.clear()
sessionStorage.clear()

All the stored key-value pairs must be strings. You can pass an object as the value after converting it to JSON format.


let person = {
    name: "adam",
    age: 34
}

localStorage.setItem('person', JSON.stringify(person))
sessionStorage.setItem('person', JSON.stringify(person))

When retrieving the value, in this case, remember to parse it back to an object.


let person = JSON.parse(localStorage.getItem('person'))

Conclusion:

Each storage option among local storage, session storage, and cookies has its own features and limitations. Considering the task at your hand, it is now your job as a programmer to select the best storage option for specific situations.

Leave a Reply

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