PHP 7.4.33
Preview: PWA_SETUP.md Size: 8.41 KB
/var/www/sitesecurity.bitkit.dk/httpdocs/PWA_SETUP.md
# PWA Notification System Setup Guide

This guide explains how to set up and configure the PWA notification system that has been implemented in your Site Security application.

## 🚀 Features Implemented

### ✅ Core Features
- **PWA Installation Overlay**: Cross-platform overlay to prompt users to install the app
- **Notification Subscription Overlay**: Cross-platform overlay to subscribe to push notifications
- **Health Checks**: Automatic verification of notification subscriptions on app open
- **Service Worker**: Background notification handling and PWA window focus
- **Device Detection**: Smart detection of mobile/desktop, iOS version, PWA status
- **Notification Settings UI**: Complete settings page for managing subscriptions

### ✅ Platform Support
- **iOS PWA** (≥16.4 for notifications)
- **Android PWA/Chrome/Firefox/Edge/Samsung Internet**
- **Desktop Chrome/Firefox/Edge/Safari**

## 📁 Files Created/Modified

### New Files Created:
```
src/
├── lib/
│   ├── firebase.ts                    # Firebase configuration
│   ├── deviceDetection.ts            # Device detection utilities
│   └── serviceWorker.ts              # Service worker registration
├── hooks/
│   ├── useNotifications.ts           # Notification lifecycle hook
│   └── useHealthCheck.ts             # Health check hook
├── components/
│   ├── onboarding/
│   │   ├── InstallPWAOverlay.tsx     # PWA installation overlay
│   │   ├── SubscribeNotificationsOverlay.tsx # Notification subscription overlay
│   │   └── OnboardingManager.tsx     # Manages overlay flow
│   ├── notifications/
│   │   └── NotificationSettings.tsx  # Settings UI component
│   └── pwa/
│       └── PWAProvider.tsx           # Main PWA integration
├── app/
│   ├── api/
│   │   ├── subscribe-device/route.ts # Device subscription API
│   │   ├── subscribed-device/[id]/route.ts # Individual device management
│   │   └── subscribed-devices/route.ts # List all devices
│   └── notifications/page.tsx        # Notification settings page
public/
└── sw.js                            # Service worker
```

### Modified Files:
```
package.json                         # Added Firebase and UUID dependencies
public/manifest.json                 # Enhanced PWA manifest
src/app/index.tsx                    # Integrated PWA provider
```

## 🔧 Setup Instructions

### 1. Firebase Configuration

1. **Create a Firebase project** at [Firebase Console](https://console.firebase.google.com/)
2. **Enable Cloud Messaging** in your Firebase project
3. **Generate a VAPID key**:
   - Go to Project Settings → Cloud Messaging
   - Generate a new key pair
4. **Create environment file**:
   - Copy `env.example` to `.env.local`
   - Replace placeholder values with your actual Firebase configuration:
   ```env
   # Firebase Web App Configuration
   NEXT_PUBLIC_FIREBASE_API_KEY=your-api-key
   NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
   NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
   NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
   NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=123456789
   NEXT_PUBLIC_FIREBASE_APP_ID=your-app-id
   NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=your-measurement-id
   
   # Firebase VAPID Key for Push Notifications
   NEXT_PUBLIC_FIREBASE_VAPID_KEY=your-vapid-key
   
   # Backend API URL (optional)
   NEXT_PUBLIC_API_BASE_URL=https://your-backend-api.com/api
   ```

**Note:** The Firebase configuration is now loaded from environment variables for security.

### 2. Backend API Integration

The system includes placeholder API endpoints that you need to connect to your actual backend:

#### API Endpoints to Implement:
- `POST /api/subscribe-device` - Subscribe a device
- `GET /api/subscribed-device/{id}` - Check device subscription
- `DELETE /api/subscribed-device/{id}` - Unsubscribe a device
- `GET /api/subscribed-devices` - List all subscribed devices

#### Required Request/Response Format:

**Subscribe Device:**
```typescript
// Request
{
  token: string,      // FCM token
  device: string,     // Device ID (UUID)
  browser: string,    // Browser name
  platform: 'Web' | 'PWA'
}

// Response
{
  success: boolean,
  message: string,
  deviceId: string
}
```

**Device Subscription:**
```typescript
// Response
{
  id: string,
  token: string,
  device: string,
  browser: string,
  platform: 'Web' | 'PWA',
  createdAt: string,
  lastNotification?: string
}
```

### 3. Authentication Integration

Update the authentication check in `src/app/index.tsx`:

```typescript
// Replace this placeholder with your actual auth logic
const checkAuthStatus = () => {
  // Example implementations:
  
  // Option 1: Check Redux store
  const isAuthenticated = useSelector(state => state.auth.isAuthenticated);
  setIsLoggedIn(isAuthenticated);
  
  // Option 2: Check localStorage token
  const token = localStorage.getItem('auth_token');
  setIsLoggedIn(!!token);
  
  // Option 3: Check cookies
  const token = Cookies.get('auth_token');
  setIsLoggedIn(!!token);
};
```

### 4. Environment Variables

Create a `.env.local` file:
```env
NEXT_PUBLIC_API_URL=https://your-backend-api.com
NEXT_PUBLIC_FIREBASE_API_KEY=your-firebase-api-key
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=123456789
NEXT_PUBLIC_FIREBASE_APP_ID=your-app-id
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID=your-measurement-id
NEXT_PUBLIC_FIREBASE_VAPID_KEY=your-vapid-key
```

## 🎯 Usage

### 1. Access Notification Settings
Navigate to `/notifications` to access the notification settings page.

### 2. Overlay Behavior
- **Install PWA Overlay**: Shows on all platforms when not already installed as PWA
- **Subscribe Overlay**: Shows on all platforms when user is logged in and hasn't subscribed
- **iOS Requirements**: Subscribe overlay only shows on iOS ≥16.4 when installed as PWA

### 3. Health Checks
Health checks run automatically:
- On app initialization
- When app regains focus
- When app becomes visible (user returns from background)

## 🔍 Testing

### 1. PWA Installation
1. Open the app on any device (mobile or desktop)
2. The install overlay should appear
3. Click "Install App" or "Add to Home Screen"
4. Verify the app installs as a PWA

### 2. Notification Subscription
1. After installing PWA, the subscribe overlay should appear
2. Click "Enable me to receive"
3. Grant notification permission
4. Verify subscription in notification settings

### 3. Cross-Platform Testing
Test on:
- **iOS Safari** (≥16.4 for notifications)
- **Android Chrome**
- **Desktop Chrome/Firefox/Edge**

## 🐛 Troubleshooting

### Common Issues:

1. **Service Worker not registering**
   - Check browser console for errors
   - Ensure `/public/sw.js` is accessible
   - Verify HTTPS in production

2. **Firebase token not generated**
   - Check Firebase configuration
   - Verify VAPID key is correct
   - Ensure service worker is registered

3. **Overlays not showing**
   - Check device detection logic
   - Verify localStorage dismissal flags
   - Ensure user is logged in for subscribe overlay

4. **Notifications not working on iOS**
   - Verify iOS version ≥16.4
   - Ensure app is installed as PWA
   - Check notification permissions

## 📱 Browser Support

| Feature | iOS Safari | Android Chrome | Desktop Chrome | Firefox | Edge |
|---------|------------|----------------|----------------|---------|------|
| PWA Install | ✅ | ✅ | ✅ | ✅ | ✅ |
| Push Notifications | ✅ (≥16.4) | ✅ | ✅ | ✅ | ✅ |
| Service Worker | ✅ | ✅ | ✅ | ✅ | ✅ |
| Background Sync | ✅ | ✅ | ✅ | ✅ | ✅ |

## 🔄 Next Steps

1. **Replace placeholder APIs** with your actual backend endpoints
2. **Configure Firebase** with your project credentials
3. **Update authentication logic** to match your auth system
4. **Customize overlay designs** to match your app's branding
5. **Test thoroughly** across all supported platforms
6. **Set up notification sending** from your backend

## 📞 Support

If you encounter any issues or need help with the implementation, please refer to:
- [Firebase Cloud Messaging Documentation](https://firebase.google.com/docs/cloud-messaging)
- [PWA Documentation](https://web.dev/progressive-web-apps/)
- [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)

Directory Contents

Dirs: 5 × Files: 19
Name Size Perms Modified Actions
.git DIR
- drwxr-xr-x 2026-04-28 09:11:00
Edit Download
.next DIR
- drwxr-xr-x 2026-04-28 09:12:04
Edit Download
- drwxr-xr-x 2026-04-28 09:11:47
Edit Download
public DIR
- drwxr-xr-x 2026-04-28 09:11:00
Edit Download
src DIR
- drwxr-xr-x 2026-04-28 09:11:00
Edit Download
73 B lrw-r--r-- 2026-04-28 09:11:00
Edit Download
757 B lrw-r--r-- 2026-04-28 09:11:00
Edit Download
757 B lrw-r--r-- 2026-04-28 09:11:00
Edit Download
1.37 KB lrw-r--r-- 2026-04-28 09:11:00
Edit Download
484 B lrw-r--r-- 2026-04-28 09:11:00
Edit Download
447 B lrw-r--r-- 2026-04-28 09:11:00
Edit Download
2.13 KB lrw-r--r-- 2026-04-28 09:11:00
Edit Download
5.88 KB lrw-r--r-- 2026-04-28 09:11:00
Edit Download
247 B lrw-r--r-- 2026-04-28 09:11:55
Edit Download
3.05 KB lrw-r--r-- 2026-04-28 09:11:00
Edit Download
271.06 KB lrw-r--r-- 2026-04-28 09:11:47
Edit Download
2.06 KB lrw-r--r-- 2026-04-28 09:11:00
Edit Download
82 B lrw-r--r-- 2026-04-28 09:11:00
Edit Download
8.41 KB lrw-r--r-- 2026-04-28 09:11:00
Edit Download
1.07 KB lrw-r--r-- 2026-04-28 09:11:00
Edit Download
68.59 MB lrw-r--r-- 2026-04-28 09:11:00
Edit Download
2.17 KB lrw-r--r-- 2026-04-28 09:11:00
Edit Download
757 B lrw-r--r-- 2026-04-28 09:11:00
Edit Download
132.31 KB lrw-r--r-- 2026-04-28 09:11:47
Edit Download
If ZipArchive is unavailable, a .tar will be created (no compression).