Master Client-Side Data Storage: Cookies, Local Storage, and Session Storage
Published: 2023-11-13 07:17:11

Hello 👋 Everyone, welcome to a new post on **Storage Mechanisms in Browser**. Modern browsers provide different ways to store the data on the client side. This article will look at the most commonly used storage mechanisms. They are

1. **Local Storage**
2. **Session Storage**
3. **Cookies**

For each storage type, we will discuss the following aspects.

- Persistence
- Accessibility on the Client Side
- Transmission to Server
- Use cases

### Local Storage
LocalStorage is a data storage, that is used to store data across sessions. We usually store non-sensitive information like theme, language, and preferences in LocalStorage.

- **Persistence**:
    - Data will persist across sessions, meaning closing the tab or window or Closing the browser will not delete data.
    - The user needs to explicitly delete the data from Local Storage.

- **Accessibility**
    - LocalStorage items can be accessed by the client-side Javascript.

- **Transmission To Server**
    - LocalStorage items will not be transferred on HTTP requests. The user needs to explicitly include these if they want to send it to the Server.

- **Usage**
    - Storing non-sensitive data that should persist between the sessions.
    
Browsers expose an API called `localStorage` to set and access the items. We store the values in `key-value` pairs.

```js
// setting a value into localStorage
localStorage.setItem("theme" , "Dark");

// accessing a value from localStorage
localStorage.getItem("theme");
```

![Set and Get a value to Local Storage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b3se8uwhe9vlzjb4vgfi.png)

To see all the stored items for a domain, we can open Developer Tools -> Application and then under Storage we can select localStorage


![Viewing the LocalStorage Items](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/10jqpxyyoamzn93v7awe.png)

---

### Session Storage
SessionStorage is same as LocalStorage, but it stores the data only for that current session.

- **Persistence**:
    - Data will persist till the session, closing the tab/window or closing the browser will delete the data.

- **Accessibility**
    - SessionStorage items can be accessed by the client-side Javascript.

- **Transmission To Server**
    - SessionStorage items will not be transferred to the Server via HTTP requests. The user needs to explicitly include these if they want to send.

- **Usage**
    - Storing non-sensitive data that should persist for a single session.
    
Browsers expose an API called `sessionStorage` to set and access the items. We store the values in `key-value` pairs.

```js
// setting a value into sessionStorage
const cart = ["1","2","3"];
sessionStorage.setItem("cart" , JSON.stringify('cart'));

// accessing a value from sessionStorage
const storedItems = sessionStorage.getItem("cart");
console.log(JSON.parse(storedItems));
```

![Set and Get an item from SessionStorage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3dju1hg47qu2hetxy6js.png)

To see all the stored items for a domain, we can open Developer Tools -> Application and then under Storage we can select SessionStorage.


![Viewing the SessionStorage Items](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmx2bs70ureicwtviic1.png)

---

### Cookies
   Cookies are a storage mechanism that stores information across sessions. The maximum size of the cookies is 4KB. We use cookies to store the information, that needs to be sent to the server on every request.

- **Persistence**:
    - Data will persist across sessions, closing the tab/window or closing the browser will not delete the data.
    - We can create cookies with an expiration time so that they get deleted after the expiration time.

- **Accessibility**
    - Cookie items can be accessed by the client-side Javascript if they are allowed.
    - If a cookie is inserted by the server, then the server can restrict the client accessibility using the `httpOnly` property.
    - Cookies that are HTTPOnly can't be accessible by the client.

- **Transmission To Server**
    - Cookies will be automatically added to every HTTP request to the Server.

- **Usage**
    - Storing the data that needs to be sent to the server.

We can use `document.cookie` in the Browser to add value to the cookies Storage.

```js
document.cookie = "name = userName";
```
The above cookie can be accessible in the browser through JavaScript.Let's see how we can make a cookie not accessible on the client side.

We are making an API call to the server, and the server sets a cookie for the authCookie. So this cookie should not be accessible to the client side. we can use the `httpOnly` option to restrict access.

```js
res.cookie("authCookie", "user123", { httpOnly: true });
```

---


When using Browser storage we should be aware of the normal Security Attacks. Let's look at some common attacks where users can get access to the browser data.

1. **XSS (Cross Site Scripting)**: Injecting scripts on the client side and getting access to the data.
  - Both LocalStorage and SessionStorage are accessible via ClientSide. So if an attacker injects a Javascript script, then can get access to the data stored in localStorage and sessionStorage.
 - Because of this reason we normally don't store any sensitive information in LocalStorage and SessionStorage.
 - Cookies stored in the browser are not accessible to clientSide scripts if we used `httpOnly` while creating the cookies.

2. **CSRF (Cross-Site Request Forgery)**: Making a Request to another domain or site, so that they can get access to Cookies stored in the browser.
  - As cookies get added to every HTTP request, an attacker can make a request to a different or malicious site and get access to all the cookies.
  - We can use the `SameSite` attribute for cookies, which helps protect against cross-site request forgery (CSRF) and cross-site scripting (XSS) attacks.

---

For more information refer : <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API" target="_blank">Storage API</a>


Hope you liked it, Happy coding! 🎉💻✨

Thank you.