# 01 - Session Persistence using `localStorage`

Welcome to **Milestone 1, Step 1.8**: Client-side session persistence using `localStorage`.

---

## 1. What is `localStorage` and Why Do We Need It?

`localStorage` is a Web Storage API in web browsers that persists key-value data across page reloads and browser restarts.

### The Problem without `localStorage`:
If a visitor refreshes `demo.html` or navigates to another page on the same website, a new `sessionId` would be created on every page load (`sess_1`, `sess_2`, `sess_3`...), fragmenting the conversation history.

### The Solution with `localStorage`:
When the backend generates a `sessionId` (`sess_a1b2c3...`), the widget saves it to `localStorage`. On subsequent page loads, the widget retrieves the stored `sessionId` instead of calling `POST /api/v1/session/init` again!

---

## 2. Site-Scoped Storage Key Architecture

To prevent session collision when multiple chatbot widgets or tenant sites exist on the same browser origin, the storage key is scoped by `siteId`:

```javascript
const STORAGE_KEY = `chatbot_session_${siteId}`;
```

### Example:
- Site `site_demo_123` stores its session under key `chatbot_session_site_demo_123`.
- Site `site_acme_456` stores its session under key `chatbot_session_site_acme_456`.

---

## 3. First Visit vs. Page Reload Flow

```text
                  [Widget Initializes with siteId]
                                 │
                 Does localStorage.getItem(key) exist?
                                 │
             ┌───────────────────┴───────────────────┐
             ▼                                       ▼
          [YES]                                   [NO]
  (Page Reload / Return Visit)                (First Visit)
             │                                       │
  Reuse existing sessionId           Call POST /api/v1/session/init
  Console: "Session restored"                        │
  UI: "Session: sess_... (restored)" Receive new sessionId from backend
                                     Save to localStorage.setItem(...)
                                     UI: "Session: sess_... (new)"
```

---

## 4. Graceful Fallback Handling

In some browsers (e.g. Safari Incognito mode or third-party iframe restrictions), calling `localStorage.setItem()` throws a `DOMException`.

The widget wraps `localStorage` access in `try...catch` helper functions. If `localStorage` is blocked, the widget gracefully falls back to runtime memory without crashing the page.
