4.9 KiB
4.9 KiB
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_tokenfield topush_tokensJSON 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)
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)
DELETE /users/push-token
Authorization: Bearer <jwt_token>
Content-Type: application/json
{
"pushToken": "device_push_token_to_remove"
}
3. Get All Push Tokens
GET /users/push-tokens
Authorization: Bearer <jwt_token>
Response:
{
"pushTokens": ["token1", "token2", "token3"],
"totalTokens": 3
}
4. Update Profile (Push Token Removed)
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
// Before
@Property({ type: "varchar", nullable: true })
pushToken?: string;
// After
@Property({ type: "json", nullable: true })
pushTokens?: string[];
Service Methods
// 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:
- Detected from Najva API response
- Logged for monitoring
- Removed from user's token array
- Database updated to clean state
Frontend Integration
When User Logs In
// 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
// 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
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
- Multi-Device Support: Users get notifications on all their devices
- Device Management: Add/remove devices as needed
- Automatic Cleanup: Invalid tokens automatically removed
- Scalable: Efficient JSON array storage with GIN indexing
- Reliable: Handles edge cases like duplicate tokens and API failures
- Monitoring: Comprehensive logging for debugging and monitoring
Migration Steps
-
Run Database Migration:
-- Execute: database/migrations/update_push_tokens_to_array.sql -
Update Frontend:
- Use new
/users/push-tokenendpoints - Remove
pushTokenfield from profile updates
- Use new
-
Deploy Backend:
- All changes are backward compatible
- Existing tokens automatically migrated
Testing
Test the multi-device functionality:
- Login from Device A → Add token A
- Login from Device B → Add token B
- Create notification → Both devices receive push
- Logout from Device A → Remove token A
- 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!