# 🔧 Fix Service Worker Cache Issue - Flutter Web

## The Problem

Your browser console shows:
```
Loading from existing service worker.
Service worker already active.
main.dart.js:5658 Uncaught Error
```

This means the **service worker is caching old/broken JavaScript code** and serving it instead of the new version!

---

## ⚡ IMMEDIATE FIX (User Side)

### Option 1: Clear Service Worker (Recommended)

1. **Open DevTools** (F12)
2. Go to **Application** tab (Chrome) or **Storage** tab (Firefox)
3. Click **Service Workers** (left sidebar)
4. Find your service worker for `chitfund.deepteklabs.com`
5. Click **Unregister**
6. **Hard refresh**: `Ctrl + Shift + R`

### Option 2: Clear All Site Data

1. Open DevTools (F12)
2. Application tab → **Clear storage** (left sidebar)
3. Check all boxes (Cookies, Cache, Storage, Service workers)
4. Click **Clear site data**
5. Close DevTools
6. Refresh page

### Option 3: Incognito Mode (Quick Test)

```
Ctrl + Shift + N (Windows/Linux)
Cmd + Shift + N (Mac)
```
No service worker cache in incognito!

---

## 🛠️ PERMANENT FIX (Developer Side)

The service worker needs to be disabled or properly managed during deployments.

### Solution 1: Disable Service Worker (Simplest)

Edit `luckychit/web/index.html`:

```html
<head>
  <!-- Existing content -->
  
  <!-- Disable service worker during development/frequent updates -->
  <script>
    // Unregister all service workers on load
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.getRegistrations().then(function(registrations) {
        for (let registration of registrations) {
          registration.unregister();
        }
      });
    }
  </script>
</head>
```

### Solution 2: Force Service Worker Update

Edit `luckychit/web/flutter_bootstrap.js` or add to `index.html`:

```html
<script>
  // Force service worker update on page load
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations().then(function(registrations) {
      registrations.forEach(function(registration) {
        registration.update(); // Force update check
      });
    });
    
    // Listen for updates
    navigator.serviceWorker.addEventListener('controllerchange', function() {
      window.location.reload(); // Reload when new service worker takes over
    });
  }
</script>
```

### Solution 3: Build Without Service Worker

Build Flutter without service worker:

```bash
flutter build web --release --pwa-strategy=none
```

This completely disables the service worker.

---

## 🔧 Fix for Current Production

### Step 1: Update index.html

```bash
# On your dev machine
cd luckychit
nano web/index.html
```

Add this script before `</body>`:

```html
<body>
  <!-- Existing content -->
  
  <!-- Force clear service worker on load -->
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.getRegistrations().then(function(registrations) {
        for (let registration of registrations) {
          console.log('Unregistering service worker:', registration);
          registration.unregister();
        }
      });
      
      // Clear all caches
      if ('caches' in window) {
        caches.keys().then(function(cacheNames) {
          cacheNames.forEach(function(cacheName) {
            console.log('Deleting cache:', cacheName);
            caches.delete(cacheName);
          });
        });
      }
    }
  </script>
  
  <script src="flutter_bootstrap.js" async></script>
</body>
```

### Step 2: Rebuild and Deploy

```bash
# Commit changes
git add web/index.html
git commit -m "Fix service worker caching issue"
git push origin prodnew

# SSH to production
ssh luckychit@192.168.8.148
cd /home/luckychit/apps/chitfund

# Pull and rebuild
git pull origin prodnew
cd luckychit
flutter clean
flutter pub get
flutter build web --release --pwa-strategy=none
pm2 restart luckychit-frontend

# Also clear nginx cache
ssh root@<nginx-proxy-ip>
sudo rm -rf /var/cache/nginx/*
sudo systemctl reload nginx
```

### Step 3: Tell Users to Clear Service Worker

Create an announcement:
```
⚠️ Important: Clear your browser cache!
1. Press F12 to open DevTools
2. Go to Application tab
3. Click Service Workers
4. Click "Unregister" for chitfund.deepteklabs.com
5. Hard refresh: Ctrl + Shift + R
```

---

## 🔍 Understanding the Error

### What Happened:

```
1. Old version deployed with service worker
2. Service worker cached main.dart.js (JavaScript)
3. You deployed new version
4. Browser loads new HTML
5. Service worker serves OLD cached JavaScript
6. Old JS + New HTML = Error!
```

### The Error Chain:

```javascript
main.dart.js:5658 Uncaught Error
  at Object.l (main.dart.js:3396:20)
```

This is a JavaScript error in compiled Dart code. Usually means:
- **Version mismatch** between HTML and cached JS
- **Corrupted cache** from incomplete deployment
- **Service worker** serving stale files

---

## 📋 Complete Fix Procedure

### On Your Dev Machine:

```bash
cd /home/user/workspace/chitfund/luckychit

# Add service worker clearing script
nano web/index.html
# (Add the script shown above)

# Commit and push
git add web/index.html
git commit -m "Add service worker clearing on load"
git push origin prodnew
```

### On Production Server (192.168.8.148):

```bash
cd /home/luckychit/apps/chitfund

# Pull latest
git pull origin prodnew

# Rebuild Flutter WITHOUT service worker
cd luckychit
flutter clean
rm -rf .dart_tool build
flutter pub get
flutter build web --release --pwa-strategy=none

# Restart PM2
pm2 restart luckychit-frontend

# Verify
pm2 logs luckychit-frontend --lines 20
```

### On Nginx Proxy LXC:

```bash
# Clear nginx cache
sudo rm -rf /var/cache/nginx/*
sudo systemctl reload nginx
```

### On Cloudflare:

1. Login to dashboard
2. Go to **Caching**
3. Click **Purge Everything**

### In Browser:

1. Open DevTools (F12)
2. Application → Service Workers → Unregister all
3. Application → Clear storage → Clear site data
4. Hard refresh: `Ctrl + Shift + R`
5. Close and reopen browser

---

## 🎯 Update Your Deployment Scripts

### Modify `deploy-frontend-only.sh`:

```bash
# Add --pwa-strategy=none to disable service worker
flutter build web --release --web-renderer html --pwa-strategy=none --build-number=$BUILD_NUMBER
```

### Modify `deploy-full.sh`:

```bash
# Same change
flutter build web --release --web-renderer html --pwa-strategy=none --build-number=$BUILD_NUMBER
```

---

## 🧪 Verify It's Fixed

### Check Browser Console:

After refresh, you should NOT see:
```
❌ Loading from existing service worker
❌ Service worker already active
❌ Uncaught Error
```

You SHOULD see:
```
✅ No stored auth data found (normal)
✅ App loads without errors
✅ Login screen appears
```

### Check Service Workers:

```
F12 → Application → Service Workers
Should be empty or show "No service workers"
```

### Check Caches:

```
F12 → Application → Cache Storage
Should be empty or minimal
```

---

## 🎓 Why Service Workers Are Problematic

### For Static Sites:
✅ **Good**: Offline support, faster loading  
✅ **Good**: PWA functionality

### For Frequently Updated Apps:
❌ **Bad**: Caches old code  
❌ **Bad**: Hard to invalidate  
❌ **Bad**: Users see old version  
❌ **Bad**: Version conflicts cause errors

### Recommendation:
**Disable service workers** until your app is stable and updates are infrequent.

---

## 🛡️ Prevention

### 1. Build Without Service Worker

Always use:
```bash
flutter build web --release --pwa-strategy=none
```

### 2. Add Clear Script to index.html

Force clear service workers on every load (shown above).

### 3. Proper Cache Headers

Already done in `index.html`:
```html
<meta http-equiv="Cache-Control" content="no-cache">
```

### 4. Version Your Builds

Already done in deployment scripts:
```bash
--build-number=$(date +%s)
```

### 5. Update Deployment Documentation

Add "Clear service worker" step to deployment checklist.

---

## 📱 Mobile Browsers

Service worker issues are WORSE on mobile!

### iOS Safari:
```
Settings → Safari → Advanced → Website Data
Find your site → Swipe left → Delete
```

### Android Chrome:
```
Settings → Site Settings → chitfund.deepteklabs.com
Clear & reset
```

### Or Use Private Mode:
Always test updates in private/incognito first!

---

## 🔍 Debug Service Worker

### Check Registration:

Open console and run:
```javascript
navigator.serviceWorker.getRegistrations().then(registrations => {
  console.log('Service Workers:', registrations);
  registrations.forEach(r => console.log('Scope:', r.scope));
});
```

### Check Caches:

```javascript
caches.keys().then(keys => {
  console.log('Cache Keys:', keys);
  keys.forEach(key => {
    caches.open(key).then(cache => {
      cache.keys().then(requests => {
        console.log(`Cache ${key}:`, requests.length, 'items');
      });
    });
  });
});
```

### Force Update:

```javascript
navigator.serviceWorker.getRegistrations().then(registrations => {
  registrations.forEach(r => r.update());
});
```

### Unregister All:

```javascript
navigator.serviceWorker.getRegistrations().then(registrations => {
  registrations.forEach(r => r.unregister());
  console.log('All service workers unregistered');
});
```

---

## ✅ Checklist

- [ ] Add service worker clearing script to `index.html`
- [ ] Build with `--pwa-strategy=none`
- [ ] Update deployment scripts to include `--pwa-strategy=none`
- [ ] Clear nginx cache on proxy LXC
- [ ] Purge Cloudflare cache
- [ ] Tell users to clear service workers
- [ ] Test in incognito mode
- [ ] Verify no errors in console
- [ ] Update deployment documentation

---

## 🎯 Quick Fix Summary

**Problem**: Service worker caching old JavaScript  
**Symptom**: `Uncaught Error` in console  
**Root Cause**: Flutter service worker serving stale cached files  
**Solution**: Disable service workers + rebuild + clear all caches

**Do This Now**:
```bash
# 1. Rebuild without service worker
flutter build web --release --pwa-strategy=none

# 2. Clear browser service worker
F12 → Application → Service Workers → Unregister

# 3. Hard refresh
Ctrl + Shift + R
```

---

**Service workers are caching old code! Rebuild with `--pwa-strategy=none` and clear all caches.** 🚀

