Storage Wars: Cookies vs. Local Storage & Session Storage
Published: 2024-01-03 22:32:40



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/el48s6h5pekplxfbuayg.png)


**Cookies** are data blocks created by the web server and stored on our computers by our browsers when we visit a website.

Cookies make our online experience smoother by saving browsing information. Thanks to cookies, the websites can keep us logged in and save information such as name, address, password and payment card that we have previously filled out for future use.

Let’s examine the storage issue chronologically. We will learn about the cookies first and then discuss local storage and session storage along the way.

#### Where Does the Term “Cookie” Come From?


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oly0sj4cco3xsujvgdh1.png)


The term “cookie” was first used in 1994 by Lou Montulli, a web programmer. One theory is that the name “cookie” derives from the 1979 term “magic cookie” used for a data package.

Another theory claims that Hansel and Gretel’s story is why these data blocks are called “cookies”. In the story, Hansel and Gretel get lost in the forest but are able to trace their tracks by leaving cookie crumbs behind. Inspired by this story and the logic of tracking online activities, this concept was named “cookies”.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oa07luu2qfv3ouwu0hgd.png)

Lou wanted to keep online shoppers’ products in a virtual shopping cart. Based on this idea, he redesigned the cookies for browsers.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1lsnplg803q90bptypvk.png)

#### What is a Cookie and How are Cookies Used?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c6cdfghnn1qauzwxvez0.png)
HTTP cookies are small pieces of data that a server sends to a user’s web browser. The server creates this data, and the data is stored with a user-specific ID.

#### Set a Cookie 

With the “document.cookie” feature, cookies can be created, read and deleted in JavaScript. Cookies are saved in name-value (key-value) pairs. We can create a cookie with the following code block:


```
document.cookie = ‘newCookie’

document.cookie = “username=John Doe”;
```

#### 1. Setting the Expiry Date of Cookies 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m51kwcxlcehdn4785xby.png)
We can also add an expiration date to cookies and when the expiration time is up, the cookie value is deleted. This can be done with the “expires” parameter as in the example below:

`document.cookie = “username=John Doe; expires=Thu, 14 Dec 2034 12:00:00 UTC”;`

**Note:** UTC is a time standard (the coordinated universal time). If no expiration date is specified, the cookie is deleted by default when the browser is closed.

#### 2. Setting the Path Variable of Cookies

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdmvkuonvthfgk3qj39o.png)
With the Path parameter, we can tell the browser which path the cookie belongs to. If we have set the path variable of our cookie as path=/admin, our cookies will appear when our URL is “/admin” or” /admin/…”. However, our cookie will not be visible on pages “ /cart/…”.

If we did not use any path parameter, our cookie belongs to the current page by default.

```
document.cookie = "username=John Doe; expires=Thu, 14 Dec 2034 12:00:00 UTC; path=/";
```


**Note:** It is not recommended to store sensitive data in the root path of your application.


#### Disadvantages of Cookies

- Cookies reload data on each request of the server, which affects the performance negatively
- Provide a maximum of 4KB of memory space
- Security problems


#### HTML5 Web Storage (Local Storage and Session Storage)

In HTML5, web pages can store the data locally in the browser. As with cookies, it is not possible to reload the data in every server request. The data is used only when there is a query.

Another great advantage of HTML5 is that it allows the storage of large amounts of data without adversely affecting the website’s performance. (Up to 5 MB of data can be kept.)

HTML5 Web Storage data, unlike cookies, is not moved to the server via HTTP. Thus, Web Storage data can only be accessed by the client side. This means that the server cannot directly access the data in the web storage. Thus, data is stored more securely in web storage.

There are two new objects HTML5 provides for storing data locally: **Local Storage** and **Session Storage**.

The main difference between Local Storage and Session Storage is that Session Storage keeps the data until the session ends. While our data is lost when we close the browser, the data is stored in Local Storage even after the browser is closed.






#### 5 Basic Web Storage Functions

1. setItem()
2. getItem()
3. removeItem()
4. key()
5. clear()



1. **setItem( ):** This method adds records in local storage and session storage. This method takes two parameters. The first is “key”, that is, the key name and the second is “value”, that is, the value corresponding to that key.


```
localStorage.setItem('key','value');
sessionStorage.setItem('key', 'value');
localStorage.setItem('name', 'John Doe');
sessionStorage.setItem('color', 'red');
```



2. **getItem( ):** This method reads the recorded data in local storage and session storage. When we try to read an unsaved data, it returns null.


```
localStorage.getItem('key');
sessionStorage.getItem('key');
localStorage.getItem('name'); output: John Due sessionStorage.getItem('color'); output: red
sessionStorage.getItem('age'); output: null
```


3. **removeItem( ):** This method is used when deleting selected data in local storage and session storage. It takes the “key” value as a parameter.


```
localStorage.removeItem('key');
sessionStorage.removeItem('key');

localStorage.removeItem('name'); 
localStorage.getItem('name');     output:null

sessionStorage.removeItem('color');
sessionStorage.getItem('color');  output: null
```


4. **key( ):** This method returns the “key” value in the index selected for local storage and session storage.

```
localStorage.key(0);     output: "name"
sessionStorage.key(0);   output: "color"
```


5. **clear( )**: Clears all data in local storage and session storage.

```
localStorage.clear();
```




#### Cookies vs. Web Storage



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28rhm3mtzna7as6d8d0t.png)

I hope the article was helpful. I’m sending you all on a journey with the Cookie Monster, which I love dearly.

Happy coding!


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u5qsxe7c2ptix6pbbntp.png)



 “Give me a book about little red bikes and a box of cookies, please.”





#### References

[Cookies and Security | Human Who Codes](https://humanwhocodes.com/blog/2009/05/12/cookies-and-security/)

[Getting from Idea to Execution with Lou Montulli | Nick Ruffini](https://nickruffini.com/lou-montulli-interview/)
[HTML Web Storage API | W3Schools
](https://www.w3schools.com/html/html5_webstorage.asp)How to [Use Cookies with JavaScript | tabnine.com](https://www.tabnine.com/academy/javascript/how-to-set-cookies-javascript/)
[JavaScript Cookies | W3Schools
](https://www.w3schools.com/js/js_cookies.asp)[JavaScript localStorage | Geeks for Geeks
](https://www.geeksforgeeks.org/javascript-localstorage/)

[Local Storage vs. Session Storage vs. Cookies | LoginRadius
](https://www.loginradius.com/blog/engineering/guest-post/local-storage-vs-session-storage-vs-cookies/)

[Storage API | W3Schools
](https://www.w3schools.com/jsref/api_storage.asp)[Web Storage API vs. Cookies for Browser Data Storage | developer.com
](https://www.developer.com/guides/web-storage-api-vs-cookies-for-browser-data-storage/)[LocalStorage Kullanımı ve Özellikleri | webolog.net
](https://webolog.net/localstorage-kullanimi-ve-ozellikleri-hakkinda-hersey/)[LocalStorage ile Veri Eklemek, Düzenlemek ve Silmek | patika.dev
](https://academy.patika.dev/courses/javascript/localstorage-ile-veri-eklemek-duzenlemek-ve-silmek)