TrackMe API Docs
Flow guides

Chat & Realtime (SSE)

How to integrate 1:1 and group chat — durable REST endpoints plus the two realtime transports (Socket.IO and SSE) that deliver live messages, read receipts, and typing indicators.

Chat is a hybrid system. There is one durable surface — seven Bearer-guarded REST endpoints under /api/v1/chats* that own all persistent state (conversations, messages, read marks). Live delivery rides two independent transports layered on top:

  1. Socket.IO /chat namespace — the primary live path. It delivers the actual message and typing payloads into an open thread room.
  2. Adonis Transmit SSE on users/:id/notifications + silent FCM data pushes — the foreground/background signal layer for chat_message / chat_read / chat_typing events used to update inbox badges and read marks.

Every endpoint requires Authorization: Bearer <oat_...> (the api guard). New messages always persist to Postgres first, then fan out — so the REST/DB state is the source of truth and realtime is best-effort on top of it.

Audience: mobile application engineers. This guide leads with the end-to-end sequence, then per-step detail, lifecycle states, and implementation notes.

A conversation created via POST /api/v1/chats is EMPTY and effectively invisible to the peer until the first message is sent. A 201 response carries lastMessage: null and unreadCount: 0; the thread does not surface meaningfully in the peer's inbox until you POST /api/v1/chats/:id/messages. There is no draft/pending state to "publish" — sending the first message is the step that makes the thread live. Do not treat the 201 from create as a delivered conversation.

The flow at a glance

Step 1 — Authenticate and get a Bearer token

Obtain an access token from the auth endpoints. Send it as Authorization: Bearer <oat_...> on every REST call, and as socket.handshake.auth.token on the Socket.IO connection.

Step 2 — Open the inbox

GET /api/v1/chats returns every conversation already enriched with lastMessage, unreadCount, lastReadMessageId, and (for 1:1) the peer profile. No per-thread back-fill needed.

Step 3 — Start (or reuse) a conversation

POST /api/v1/chats with type + participantIds (+ contextType/contextId when anchored to a job post, listing, support ticket, etc.). For 1:1 this is find-or-reuse — you may get an existing thread back. The returned conversation is empty until you send.

Step 4 — Connect realtime

Open the Socket.IO /chat namespace with the token in handshake.auth.token, then emit join_conversation { conversationId } for each open thread — only then do you receive that thread's message/typing events. In parallel, subscribe to SSE users/<yourId>/notifications for chat_message / chat_read / chat_typing signals.

Step 5 — Send a message

Either send_message over Socket.IO (returns an ACK with the message id, then a message event to the room) or POST /api/v1/chats/:id/messages (returns the persisted message). Both persist to the DB first, bump lastMessageAt, and enqueue a localized push to recipients not in the room.

Step 6 — Page older history

GET /api/v1/chats/:id/messages?limit=&before=<oldestMessageId> returns newest-first. Walk meta.pagination.nextCursor until it is null.

Step 7 — Mark the thread read

POST /api/v1/chats/:id/read (or Socket.IO read_messages) advances your last_read_message_id and fires a chat_read event so the other side's read marks update live.

Step 8 — Broadcast typing

While composing, throttle POST /api/v1/chats/:id/typing (or Socket.IO typing) to ~1/sec. Receivers show a transient indicator and auto-clear after ~4s.

Per-step detail

Step 2 — List conversations

Ordered by lastMessageAt desc. Soft-deleted conversations and threads you have left (left_at set) are excluded. unreadCount excludes your own messages; peer is null for group threads.

GET /api/v1/chats HTTP/1.1
Authorization: Bearer oat_xxx
Accept-Language: en
{
  "data": {
    "items": [
      {
        "id": "cnv_01jq8z...",
        "type": "hiring",
        "contextType": "job_post",
        "contextId": "job_01jq8zk...",
        "title": null,
        "isGroup": false,
        "lastMessageAt": "2026-06-21T09:14:02.110Z",
        "participants": ["usr_me...", "usr_peer..."],
        "createdAt": "2026-06-20T18:02:00.000Z",
        "lastMessage": {
          "id": "msg_01jq9a...",
          "senderId": "usr_peer...",
          "body": "Thursday at 4pm works.",
          "hasAttachment": false,
          "createdAt": "2026-06-21T09:14:02.110Z"
        },
        "unreadCount": 1,
        "lastReadMessageId": "msg_01jq98...",
        "peer": { "id": "usr_peer...", "name": "Layla", "avatarUrl": "https://.../thumb.jpg" }
      }
    ]
  },
  "meta": { "requestId": "req_abc" }
}

Step 3 — Create or reuse a conversation

Body: { type, participantIds (1–50), contextType?, contextId?, title? }. Valid type values: direct, group, support, hiring, marketplace, community. The caller is auto-added as owner; other participantIds are added as member.

  • 1:1 (≤2 total participants) is find-or-reuse, under a Redis lock keyed on the sorted participant pair + type + context. A 201 may return a pre-existing thread.
  • >2 participants always create a fresh group.

Returns the conversation with empty enrichment (lastMessage: null, unreadCount: 0). Returns 422 on validation (bad type, empty participantIds, over-length fields); 409 CONFLICT if fewer than 2 distinct participants resolve (e.g. participantIds contains only your own id — you are auto-added, so you must name at least one other user).

POST /api/v1/chats HTTP/1.1
Authorization: Bearer oat_xxx
Content-Type: application/json

{
  "type": "hiring",
  "participantIds": ["usr_peer..."],
  "contextType": "job_post",
  "contextId": "job_01jq8zk..."
}
{
  "data": {
    "conversation": {
      "id": "cnv_01jq8z...",
      "type": "hiring",
      "contextType": "job_post",
      "contextId": "job_01jq8zk...",
      "isGroup": false,
      "lastMessageAt": null,
      "participants": ["usr_me...", "usr_peer..."],
      "lastMessage": null,
      "unreadCount": 0,
      "lastReadMessageId": null,
      "peer": { "id": "usr_peer...", "name": "Layla", "avatarUrl": null }
    }
  },
  "meta": { "requestId": "req_abc" }
}

1:1 reuse is scoped by contextType + contextId. Omitting context vs. passing a job_post id produces different threads; contacting two different job posts yields two separate hiring conversations. Pass context consistently or you will fork threads. Always read the returned conversation.id — a 201 does not guarantee a brand-new thread.

GET /api/v1/chats/:id returns the same inbox enrichment as the list (lastMessage, unreadCount, lastReadMessageId, peer). Use it to render a conversation header when opening via a deep link with no prior context. Non-participants get 403; a soft-deleted thread 404s.

Step 4 — Connect Socket.IO + subscribe SSE

The two transports do two different jobs:

TransportCarriesUse it for
Socket.IO /chat (room conversation:<id>)the live message and typing payloadsrendering messages/typing inside an open thread
SSE users/:id/notifications + FCM data pushchat_message / chat_read / chat_typing signalsinbox/badge updates, read marks, background wake

Socket.IO connection — token goes in handshake.auth.token:

const socket = io("https://api.example.com/chat", {
  auth: { token: "oat_xxx" }, // or Authorization header
});

socket.emit("join_conversation", { conversationId: "cnv_01jq8z..." });

socket.on("message", (m) => { /* { id, conversationId, senderId, body, attachments, replyId, replyToMessageId, createdAt } */ });
socket.on("typing", (t) => { /* { userId, isTyping } */ });

SSE: subscribe to your own channel only — users/<yourId>/notifications. The authorize callback requires ctx.auth.user.id === :id, so you cannot subscribe to anyone else's channel. Transmit is mounted automatically (pingInterval 30s, Redis-backed for multi-instance). Chat content is not available on any SSE channel — there is no users/:id/messages channel. SSE only carries notification/event signals about chat.

You must emit join_conversation { conversationId } per thread before any message/typing event arrives, and the join is silently rejected for non-participants. A socket that is connected but never joined the room receives nothing for that thread.

Step 5 — Send a message

Body: { body? (≤5000 chars), fileIds? (≤10), replyId? / replyToMessageId? }. You must include a body OR at least one fileId, else 422.

  • Attachments must be pre-uploaded via the uploads endpoint with purpose=chat_attachment and referenced by fileId — you cannot inline file bytes. They are atomically rebound to the new message id (ownership + per-message cap of 10 checked at attach time).
  • Persisted with status: 'sent'. Bumps conversation.lastMessageAt and enqueues a localized chat_message / chat_attachment push to every other participant.
  • 403 for non-participants; 404 if the conversation is missing.
POST /api/v1/chats/cnv_01jq8z.../messages HTTP/1.1
Authorization: Bearer oat_xxx
Content-Type: application/json
Accept-Language: ar

{
  "body": "Happy to chat — can we do Thursday at 4pm?",
  "fileIds": [],
  "replyToMessageId": null
}
{
  "data": {
    "message": {
      "id": "msg_01jq9a...",
      "conversationId": "cnv_01jq8z...",
      "senderId": "usr_me...",
      "body": "Happy to chat — can we do Thursday at 4pm?",
      "attachments": [],
      "replyId": null,
      "replyToMessageId": null,
      "status": "sent",
      "createdAt": "2026-06-21T09:14:02.110Z",
      "editedAt": null,
      "deletedAt": null
    }
  },
  "meta": { "requestId": "req_abc" }
}

Sending over Socket.IO instead — the ACK callback returns the persisted id, then a message event lands in the room:

socket.emit(
  "send_message",
  { conversationId: "cnv_01jq8z...", body: "Thursday at 4pm works." },
  (ack) => { /* { ok: true, messageId, replyId, replyToMessageId } | { ok: false, error } */ }
);

Step 6 — Page message history

Query: ?limit= (1–100, default 50) and ?before=<messageId>. Returns descending createdAt (newest first). Soft-deleted messages are filtered out. meta.pagination.nextCursor is the oldest returned message id when a full page came back, else null. Non-participants get 403 even on a valid id.

GET /api/v1/chats/cnv_01jq8z.../messages?limit=50&before=msg_01jq98... HTTP/1.1
Authorization: Bearer oat_xxx
{
  "data": { "items": [ /* messages, newest first */ ] },
  "meta": {
    "requestId": "req_abc",
    "pagination": { "nextCursor": "msg_01jq77...", "limit": 50 }
  }
}

The list is newest-first. To render top-down chronologically, reverse each page client-side. To load older history, pass ?before=<the oldest message id you currently hold>; stop when nextCursor is null.

Step 7 — Mark read

Sets your last_read_message_id to the latest message, then broadcasts chat_read over SSE to every other participant plus a silent high-priority FCM data push. No-op (still 200) on an empty thread. Same effect via Socket.IO read_messages { conversationId }.

POST /api/v1/chats/cnv_01jq8z.../read HTTP/1.1
Authorization: Bearer oat_xxx
{ "data": { "success": true }, "meta": { "requestId": "req_abc" } }

The other side receives, on their SSE channel:

{ "type": "chat_read", "conversationId": "cnv_01jq8z...", "userId": "usr_me...", "lastReadMessageId": "msg_01jq9a...", "at": "2026-06-21T09:15:00.000Z" }

Step 8 — Typing indicator

Pure broadcast, no DB write. Each other participant receives a chat_typing event on their SSE channel plus a normal-priority silent FCM data push. Throttle to ~1/sec; receivers auto-clear after ~4s.

POST /api/v1/chats/cnv_01jq8z.../typing HTTP/1.1
Authorization: Bearer oat_xxx
{ "data": { "success": true }, "meta": { "requestId": "req_abc" } }

Lifecycle

State table

StateMeaningHow you got hereWhat's allowed next
conversation:active (empty)Created, ≥1 active participant, no messages yetPOST /chats (or find-or-reuse)Send first message → becomes visible in peer inbox
conversation:active (has lastMessage)Has ≥1 message; surfaces in peer inboxFirst POST /chats/:id/messages or Socket.IO send_messageMore messages, read, typing
conversation:soft-deleteddeletedAt setServer-side deletion404 on fetch; excluded from list
participant:activeleft_at nullAdded on create / joined groupReceives messages, read/typing fanout
participant:leftleft_at setLeft the threadExcluded from listForUser and from message/typing/read fanout
message:sentThe only status ever written (status is a freeform string(16), default 'sent')POST /chats/:id/messages or send_messageSoft-delete; read tracked per-participant (not on the row)
message:delivered / read / moderatedDocumented in the column comment, never set by any REST/WS path—— (do not rely on them)
message:soft-deleteddeletedAt setServer-side deletionFiltered from listMessages and from lastMessage enrichment

Transitions

  • (none) → conversation:active via POST /api/v1/chats (or find-or-reuse of an existing 1:1). Actor: authenticated user (auto-added owner); other participantIds added as member.
  • conversation:active (empty) → conversation:active (has lastMessage, surfaces in peer inbox) via POST /api/v1/chats/:id/messages OR Socket.IO send_message. Actor: any active participant.
  • message unread by peer → peer last_read_message_id advanced via POST /api/v1/chats/:id/read OR Socket.IO read_messages. Actor: the reading participant; fires chat_read to others.
  • no typing signal → transient chat_typing broadcast via POST /api/v1/chats/:id/typing OR Socket.IO typing. Actor: the typing participant; auto-clears on receivers after ~4s.

Implementation Notes

Integration issueCorrect handling
Treating the 201 from POST /chats as a delivered conversation.It is empty (lastMessage: null). Send the first message — that is what makes the thread live and visible in the peer's inbox.
Assuming POST /chats always creates a new 1:1.It is find-or-reuse (Redis-locked). Read the returned conversation.id; the same pair + type + context returns the existing thread.
Forking threads by passing context inconsistently.1:1 reuse is scoped by contextType + contextId. Omitting context vs. a job_post id are different threads. Pass context the same way every time.
Expecting chat messages on an SSE channel.There is no users/:id/messages SSE channel. Live message bodies come over Socket.IO; SSE only carries chat_message/chat_read/chat_typing signals.
Socket connected but no messages arrive for a thread.You forgot join_conversation { conversationId }. Emit it per thread; non-participants are silently rejected.
Relying on per-message delivered/read status.status is always 'sent'; 'delivered'/'read'/'moderated' are documented but never set. Read state is per-participant via last_read_message_id + the chat_read event.
Sending an empty payload.Include a body OR at least one fileId, else 422. Files must be pre-uploaded with purpose=chat_attachment (max 10) and referenced by id.
Confusing 403 with a bad id.requireParticipant returns 403 (not 404) for non-members even on a valid id. 403 means "not your thread"; 404 means missing/soft-deleted.
Rendering message pages bottom-up as returned.GET /chats/:id/messages is newest-first. Reverse each page for chronological display; page older via ?before=<oldest id> until nextCursor is null.
unreadCount not matching total message count.It excludes your own messages and is computed relative to last_read_message_id; soft-deleted messages are excluded from counts and the preview.
Assuming every realtime event was delivered.All fanout (push, SSE, FCM) is best-effort — a transmit/FCM hiccup is swallowed and never fails the underlying call. Treat REST/DB as truth and reconcile via GET on reconnect.
Expecting localized wire timestamps.Send Accept-Language: ar for Arabic push/notification copy. Wire timestamps (createdAt, lastMessageAt, chat_read.at) are always UTC ISO-8601 with Z regardless of X-Timezone.

On this page