Skip to main content

Overview

The unread count endpoint returns the total number of unread messages across all conversations for the authenticated user. This is useful for displaying notification badges in your application’s UI.

Authentication

This endpoint requires authentication via JWT token in the Authorization header.

Get Unread Count

GET /api/chat/unread-count

Returns the total number of unread messages for the authenticated user across all their conversations.

Response Fields

boolean
required
Indicates if the request was successful
number
required
Total number of unread messages across all conversations. Returns 0 if there are no unread messages.
string
Error message (only present when success is false)

How It Works

The endpoint:
  1. Finds all conversations where the authenticated user is a participant
  2. Counts all messages in those conversations where:
    • The sender is NOT the authenticated user
    • The is_read field is false
  3. Returns the total count

Error Responses

  • 401 Unauthorized: Missing or invalid authentication token
  • 500 Internal Server Error: Server error occurred

Usage Examples

Display Notification Badge

React

Real-time Updates with Socket.io

For better user experience, combine the unread count endpoint with Socket.io message notifications:

Mobile App Integration

Swift

Best Practices

Polling Strategy

The recommended polling interval depends on your use case:
  • Active chat view: Poll every 10-30 seconds
  • Background/other views: Poll every 1-2 minutes
  • Mobile apps: Poll when app comes to foreground
Always combine with Socket.io for real-time updates when possible to reduce unnecessary API calls.
To minimize server load and improve performance:
  1. Use Socket.io’s message_notification event to increment the count client-side
  2. Only fetch the actual count periodically or when the user opens the app
  3. Store the count in local state and update it optimistically
  4. Reset the count when users read messages (mark them as read)
If the unread count request fails:
  • Keep showing the last known count
  • Don’t show “0” as it may be misleading
  • Retry with exponential backoff
  • Show a visual indicator if the count is stale

Optimistic Updates

Update the count optimistically when users interact with messages:


Implementation Checklist

1

Initial Load

Fetch the unread count when your application loads to display the initial badge state.
2

Socket.io Integration

Listen to message_notification events to increment the count in real-time when new messages arrive.
3

Optimistic Updates

Decrease the count optimistically when users open conversations and read messages.
4

Periodic Sync

Poll the endpoint periodically (every 1-2 minutes) to sync with the server and correct any client-side drift.
5

Error Handling

Handle network errors gracefully by keeping the last known count and retrying with exponential backoff.