# Web Storage APIs

Modern web applications often need to save data directly in the browser of the user, whether it is preserving a shopping cart, keeping a user logged in, or remembering dark mode preferences. While Cookies were once the only option, the **Web Storage API** provides a more intuitive way to handle client side data.

By the end of this blog, you will have a clear understanding of Web Storage APIs, how to implement them, and most importantly, when **not** to use them.

### Prerequisites

To get the most out of this guide, you should have a basic understanding of:

* **JavaScript** (Objects, Strings, and basic syntax)
    
* **APIs** (How interfaces interact with the browser)
    
* **Client side rendering** (How the browser paints the UI)
    

---

## What is the Web Storage API?

The Web Storage API provides mechanisms for browsers to store key value pairs. Unlike cookies, this data is never sent to the server with every HTTP request, reducing network traffic.

There are two main mechanisms within this API:

1. **LocalStorage**
    
2. **SessionStorage**
    

Both share the same storage limit (typically around **5MB** per origin) and use the same methods to set and retrieve data.

### 1\. LocalStorage

`localStorage` persists data even after the browser window is closed. It has no expiration date; the data remains until the user manually clears the cache or your web app clears it programmatically.

**Common Use Cases**

* Storing User Theme preferences (Dark or Light mode).
    
* Persisting authentication tokens (caution advised).
    
* Saving "draft" data for long forms.
    

**Syntax**

```javascript
// Save data (Key, Value)
localStorage.setItem('theme', 'dark');

// Retrieve data
const currentTheme = localStorage.getItem('theme');

// Remove specific data
localStorage.removeItem('theme');

// Clear all data
localStorage.clear();
```

### 2\. SessionStorage

`sessionStorage` works almost exactly like LocalStorage, but with one key difference: **Persistence**. Data stored in `sessionStorage` is cleared as soon as the tab or window is closed.

**Common Use Cases**

* One time login redirects.
    
* Sensitive banking session data (where you want automatic cleanup).
    
* Filtering or sorting states for a specific tab.
    

**Syntax**

```javascript
// Save data
sessionStorage.setItem('sessionID', '12345');

// Retrieve data
const session = sessionStorage.getItem('sessionID');
```

---

## Cons of Web Storage API

While `localStorage` and `sessionStorage` are incredibly easy to use, they come with a significant architectural flaw: **They are Synchronous.**

JavaScript runs on a **single main thread**. This thread is responsible for everything: executing your JavaScript, parsing HTML, and rendering the UI (painting pixels to the screen).

Because Web Storage APIs are synchronous, when your code reads from or writes to storage, the browser **halts the entire main thread** until that operation is complete.

### The Performance Impact

If you are storing a small string, the delay is negligible (microseconds). However, if you are storing large datasets (approaching the 5MB limit) or complex JSON objects that need to be serialized or deserialized, the impact becomes noticeable.

1. **UI Freezing:** While the browser is writing to `localStorage`, it cannot respond to clicks, scrolling, or animations. The app will feel "janky" or unresponsive.
    
2. **I/O Blocking:** Reading data from the disk (where storage lives) is much slower than reading from memory (RAM).
    

> **Warning:** Never use Web Storage for high frequency data (like tracking mouse movements) or large datasets (like a list of 10,000 products).

---

## Summary: Advantages and Disadvantages

**Ease of Use**

* **Pros:** Extremely simple API (`setItem` and `getItem`). No setup required.
    
* **Cons:** Limited to Strings only (must `JSON.stringify` objects).
    

**Persistence**

* **Pros:** Great for saving state across sessions (LocalStorage).
    
* **Cons:** Data can accumulate and waste space if not managed.
    

**Performance**

* **Pros:** Fast for very small amounts of data.
    
* **Cons:** **Synchronous and Blocking.** Can freeze the main thread and degrade UI performance.
    

**Security**

* **Cons:** **Vulnerable to XSS.** Any JavaScript running on your page can read this data. Never store sensitive secrets here.
    

---

## Better Alternatives and Best Practices

If you need to store complex data or large files without slowing down your app, consider **IndexedDB**. It is an asynchronous, transactional database system built into the browser. It does not block the main thread and can store significantly more data than Web Storage.

I have listed down a few articles below that dive deeper into these alternatives and best practices. Do check them out to deepen your understanding.

### References and Further Reading

* [Storage for the Web (web.dev)](https://web.dev/storage-for-the-web/)
    
* [The Different Types of Browser Storage](https://betterprogramming.pub/the-different-types-of-browser-storage-82b918cb3cf8)
    
* [Client Side Storage Options Comparison](https://www.sitepoint.com/client-side-storage-options-comparison/)
    
* [JavaScript.info: LocalStorage](https://javascript.info/localstorage)
    
* [MDN Web Docs: Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)
    
* [GeeksForGeeks: LocalStorage and SessionStorage](https://www.geeksforgeeks.org/localstorage-and-sessionstorage-web-storage-apis/)
    
* [Complete Guide to Local Storage](https://codesource.io/complete-guide-to-local-storage-in-javascript/)
