Files
dmail-api/PUSH_NOTIFICATIONS_MULTI_DEVICE.md
T
2025-07-28 12:38:38 +03:30

215 lines
4.9 KiB
Markdown

# Multi-Device Push Notifications Implementation
## Overview
Updated the push notification system to support multiple devices per user. Users can now receive push notifications on all their logged-in devices (mobile, tablet, desktop, etc.).
## Database Changes
### Migration: `update_push_tokens_to_array.sql`
- Converted single `push_token` field to `push_tokens` JSON array
- Automatically migrates existing single tokens to array format
- Adds optimized GIN index for JSON array queries
## API Endpoints
### 1. Add Push Token (New Device Login)
```http
POST /users/push-token
Authorization: Bearer <jwt_token>
Content-Type: application/json
{
"pushToken": "device_push_token_from_najva_sdk",
"deviceId": "optional_device_identifier"
}
```
### 2. Remove Push Token (Device Logout)
```http
DELETE /users/push-token
Authorization: Bearer <jwt_token>
Content-Type: application/json
{
"pushToken": "device_push_token_to_remove"
}
```
### 3. Get All Push Tokens
```http
GET /users/push-tokens
Authorization: Bearer <jwt_token>
```
Response:
```json
{
"pushTokens": ["token1", "token2", "token3"],
"totalTokens": 3
}
```
### 4. Update Profile (Push Token Removed)
```http
PATCH /users/profile
Authorization: Bearer <jwt_token>
Content-Type: application/json
{
"profilePic": "https://example.com/profile.jpg"
}
```
## Features
### ✅ Multi-Device Support
- Users can have multiple push tokens (one per device)
- Notifications sent to all registered devices simultaneously
- Automatic deduplication prevents duplicate tokens
### ✅ Invalid Token Cleanup
- Automatically detects invalid/expired tokens from Najva API response
- Removes invalid tokens from user's token list
- Logs cleanup activities for monitoring
### ✅ Device Management
- Add tokens when user logs in on new device
- Remove tokens when user logs out from device
- View all registered devices/tokens
### ✅ Backward Compatibility
- Existing single token data automatically migrated to array format
- No breaking changes to existing notification flow
## Implementation Details
### User Entity Changes
```typescript
// Before
@Property({ type: "varchar", nullable: true })
pushToken?: string;
// After
@Property({ type: "json", nullable: true })
pushTokens?: string[];
```
### Service Methods
```typescript
// Add token for new device
await usersService.addPushToken(userId, { pushToken: "token" });
// Remove token when logging out
await usersService.removePushToken(userId, { pushToken: "token" });
// Send to all user devices
await notificationsService.sendPushNotificationToUserDevices(userId, userTokens, message);
```
### Automatic Token Cleanup
When sending notifications, invalid tokens are automatically:
1. Detected from Najva API response
2. Logged for monitoring
3. Removed from user's token array
4. Database updated to clean state
## Frontend Integration
### When User Logs In
```javascript
// Get push token from Najva SDK
const pushToken = await najva.getPushToken();
// Register token for this device
await fetch("/api/users/push-token", {
method: "POST",
headers: {
Authorization: `Bearer ${jwt}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
pushToken: pushToken,
deviceId: navigator.userAgent, // optional
}),
});
```
### When User Logs Out
```javascript
// Remove token for this device
await fetch("/api/users/push-token", {
method: "DELETE",
headers: {
Authorization: `Bearer ${jwt}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
pushToken: currentDeviceToken,
}),
});
```
## Environment Variables
```env
NAJVA_API_KEY=your_najva_api_key
NAJVA_WEBSITE_ID=your_website_id
NAJVA_API_URL=https://push.najva.com/v1/send/token/
PUSH_TTL=24
FRONTEND_URL=https://your-frontend-domain.com
```
## Benefits
1. **Multi-Device Support**: Users get notifications on all their devices
2. **Device Management**: Add/remove devices as needed
3. **Automatic Cleanup**: Invalid tokens automatically removed
4. **Scalable**: Efficient JSON array storage with GIN indexing
5. **Reliable**: Handles edge cases like duplicate tokens and API failures
6. **Monitoring**: Comprehensive logging for debugging and monitoring
## Migration Steps
1. **Run Database Migration**:
```sql
-- Execute: database/migrations/update_push_tokens_to_array.sql
```
2. **Update Frontend**:
- Use new `/users/push-token` endpoints
- Remove `pushToken` field from profile updates
3. **Deploy Backend**:
- All changes are backward compatible
- Existing tokens automatically migrated
## Testing
Test the multi-device functionality:
1. Login from Device A → Add token A
2. Login from Device B → Add token B
3. Create notification → Both devices receive push
4. Logout from Device A → Remove token A
5. Create notification → Only device B receives push
The system now properly supports users accessing your application from multiple devices while maintaining reliable push notification delivery!