Handling Browser Storage: cookies, local storage, session storage
Tags: learning, webdev, beginners, softwaredevelopment
Published: 2023-08-22 16:57:17

Modern web browsers offer some number of ways that enable browsers to store data on the user's computer system, and then retrieve it when it is needed, therefore, letting you persist data for long-term storage, retain the user's specific settings for your site, and more. In this article, we will explore three of the most used browser storage options, their use cases, security risks, and how to mitigate them.

In this article:

- [Cookies](#cookies)

- [Local Storage](#local-storage)

- [Session Storage](#session-storage)


## Cookies
Cookies (also called HTTP cookies) is a piece of data that a server sends to a user's web browser. The user's web browser stores the cookie and then sends it back to the same server with later requests.

To get a better understanding of how cookies work. let's use this example, imagine you are at a restaurant. The waiter gives you a special card (cookie) with your name on it. You keep the card and show it to the waiter whenever you go back to the restaurant. The waiter knows who you are and what you like. Cookies work the same way.

### Use Cases
Cookies are mainly used for the following purposes:

- **Session management:** Cookies are usually used to manage user sessions. They store temporary information, therefore, helping users stay logged in as they navigate through different pages of the website. Some other examples are shopping carts, game scores, or anything else the server should remember.

- **Personalization:** Cookies are also used to store user preferences and settings, enabling websites to tailor the experience to individual users. This could include things like theme settings, language preference and other settings.

- **Tracking:** Cookies are often used by websites and advertisers to record and analyze user behavior.


### Cookie Security
Cookie security is the act of protecting the information stored in cookies, which websites use as small text files to retain user preferences and sessions.

While cookies enhance user experiences, they can also expose security risks such as session hijacking, [cross-site scripting(XSS)](https://portswigger.net/web-security/cross-site-scripting), and [cross-site request forgery(CSRF)](https://www.synopsys.com/glossary/what-is-csrf.html).

Here are some ways to mitigate the security risks associated with cookies:

- Validate and sanitize user inputs to prevent XSS attacks that might target cookies
- Make sure to implement proper authentication and authorization mechanisms to prevent session hijacking
- Use secure HTTPS connections to transmit cookies
- Regularly audit and validate cookies to prevent unauthorized usage
- Implement secure cookie attributes like `HttpOnly` and `Secure` to limit cookie exposure

> Learn more: [using HTTP Cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)


## Local Storage
Local storage is a client-side web browser storage that enables websites and apps to store persistent data with no expiration date. This means that local storage holds the data even if the user refreshes the web page or closes the browser.

More properties of local storage include:
- Local storage offers a high storage limit of around `5MB`
- It is only accessible through client-side JavaScript and cannot be accessed by the server
- The syntax is straightforward
- Local storage data is not automatically sent to the server with every HTTP request, unless the data is specifically requested

### Use Cases 
Local storage can be used in:
- Keeping track of user's shopping cart until they make a purchase
- Storing frequently used data in order to reduce the need for repeated server requests therefore improving website performance and reducing costs 
- Storing user's preferences and settings, theme choices to personalize user experience
- Keeping track/saving of partially completed forms or drafts so users can resume their work later



### Accessing local storage
Local storage is an object that is accessed through the browser's window interface. The local storage object has a `setItem()` function that accepts two arguments:
- **key:** The key acts as a unique identifier to the stored data
- **Value:** The stored data itself


To store data in local storage, open the console tab in your browser's dev tools, and run the following command to assign the string value of `"How are you today?"` to the key-labeled `question`:

```
localStorage.setItem("question", "How are you today?");
```

To see what you have stored in local storage, you can use the developer tools in your web browser. For example, in Firefox, click the `storage` tab to view the contents of local storage.

You should see something like this:

![firefox dev tools](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jotrr7gi3rybd42mpahz.png)

The local storage object also offers two other functions `removeItem()` and `clear()`.

`removeItem()` deletes the data stored for a specific item. For example, the following command deletes the data we stored above using it's `key`:

```
localStorage.removeItem("question");
```
And the below command deletes all local storage data in the browser's memory:

```
localStorage.clear()
```

### Local Storage Security
Local storage in web browsers poses some security risks if not managed properly. Some of these risks include:

- If your application is vulnerable to XSS attacks, malicious scripts injected into your web pages can access and manipulate data in local storage, since JavaScript running on a page has access to it. This can lead to data theft or tampering.

- Storing sensitive data such as user authentication tokens and personal data in local storage without proper encryption can expose the data to potential attacks.

- Unless removed explicitly, data in local storage persist indefinitely thereby increasing the risk of data exposure.

- Although local storage follows the same-origin policy, there are techniques such as CSRF attacks that can be used to trick a user into performing actions that lead to data being stored in local storage. 


Here are some ways to mitigate local storage security risks in your application:
- Encrypt sensitive data such as user authentication and personal settings/data before storing it to local storage.
- Validate user inputs to prevent XSS attacks.
- Frequently clear outdated or unnecessary data from local storage.
- Implement proper access controls and authorization checks.


## Session Storage
Session storage is another form of client-side web browser storage. session storage shares similar properties with local storage but with **one key difference**: 
- The data stored in session storage is only available for as long as the user's browser session is active. When the user closes the tab or browser, the data is cleared automatically.

### Use Cases 
- Session storage is suitable for storing data that is only needed during a single user session, such as shopping cart or temporary user preferences.

- Session storage can help in maintaining the state of a web application across different views or components.

- Session storage can also be used to store form data temporarily as users navigate between pages to prevent data loss, if they accidentally close the browser or tab.


### Accessing Session Storage
Similar to what we have done in local storage, you can use the `setItem()` function to assign the string value of `"How are you today?"` to the key labeled `question`:

```
sessionStorage.setItem("question", "How are you today?")
```

As we've seen earlier, you can go to the `storage` tab of Firefox to view the contents of session storage.


![session storage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wgen8y88lml2eh93jw0d.png)

Similarly, like local storage, the data stored in session storage can also be deleted by clearing out the browser’s memory or with the `removeItem()` and `clear()` functions:

```
sessionStorage.removeItem("question")
```

```
sessionStorage.clear()
```

### Session Storage Security
Like other client-side storage, session storage has certain security considerations that you should be aware of, to ensure user data protection and to mitigate potential security risks. Here are some potential risks associated with session storage:

- Similar to other web storage mechanisms, session storage can be vulnerable to XSS attacks
- Potential attackers can hijack user's session and gain access to the data stored. This makes it crucial to implement robust session management and authentication mechanisms
- Sensitive data stored in session storage such as user authentication tokens can be exposed, if an attacker gains access to the user's device or compromises the browser session

To mitigate these security risks when using session storage, consider the following best practices:
- Encrypt sensitive data before storing it to add an additional layer of security
- Always validate user inputs to prevent XSS attacks
- Clear data from session storage as soon as it's no longer needed to reduce or prevent the risk of data exposure
- Implement strong session management to ensure your application is secure and includes mechanisms to prevent session hijacking

## Conclusion
Browser storages such as local storage and session storage help developers store and manage data on the client side, facilitating faster access to information, reducing server load, and improving user experiences in web applications.

In this article we explored the three most used browser storage options, their use cases, security risks, and ways to mitigate them.