Skip to Content
HomeLink Hub

Realtime Events

Socket.IO and server-sent events: how to connect, every event the server sends and listens for, and what triggers each one.

Live updates (chat, the notification bell, booking and escrow status) are pushed to clients over Socket.IO. A smaller set of events is also available as a server-sent events stream for browsers that only need to listen. Phone push notifications go through Expo.

There are three delivery mechanisms:

MechanismTransportUsed for
Socket.IOWebSocket / long-polling on the API hostChat, stored notifications (notifications:new), escrow status, booking updates, test notifications
SSEGET /api/v1/stream/eventsBooking updates and test notifications only
Expo pushExpo push servicePhone push for anything that goes through NotificationService.createAndEmit

Both the Socket.IO room registry and the SSE client registry live in process memory. No Socket.IO adapter is configured, so all of this assumes a single server instance (the code comments say so explicitly).

Socket.IO server (src/sockets/web.socket.ts)

Connecting

  • The server is created in src/index.ts on the same HTTP server as the REST API, with the default Socket.IO path (/socket.io). No namespace is used (default /).
  • Transports: ["websocket", "polling"].
  • CORS: origins from the ALLOWED_ORIGINS environment variable (comma separated), methods GET/POST, credentials: true.
  • The instance is stored in three places: global.io, app.set("io", io), and the local variable passed to initializeWebSocket.

Authentication

A connection middleware runs on every handshake.

  • The token is the normal JWT access token (the same one used as the REST bearer token), with no Bearer prefix.
  • It is read from socket.handshake.auth.token first, then socket.handshake.query.token.
  • The token is verified with verifyAccessToken, then the user is loaded from the database (so a deleted user cannot connect). isActive is not checked.
  • The token is only checked at handshake. An already-connected socket is not disconnected when its access token expires.
import { io } from "socket.io-client";
const socket = io(API_ORIGIN, { auth: { token: accessToken }, transports: ["websocket", "polling"] });

Handshake failures reach the client as a connect_error whose message is one of:

MessageCause
Token required for WebSocket connectionNo token in auth or query
Invalid or expired tokenVerification failed for any reason (expired, bad signature, missing user id in payload)
Invalid token payloadDecoded token has no user_id (in practice verifyAccessToken already rejects this, so the previous message is what clients see)
User not foundToken is valid but the user no longer exists
Authentication error: <message>Any other exception in the middleware

On success the socket gets userId and a user object (user_id, email, username = "<firstName> <lastName>", role, isEmailVerified, isKYCVerified).

Rooms

RoomWho is in itHow a socket joins
user:<userId>Every socket of that userAutomatically on connection
room:<chatRoomId>Sockets currently viewing that conversationchat:join, or implicitly for the sender on chat:create_and_send; left with chat:leave
notifications:globalSockets that asked for itnotifications:subscribe

Nothing in the codebase emits to notifications:global; joining it currently has no effect beyond the acknowledgement event.

Events the server listens for (client to server)

None of the handlers use Socket.IO acknowledgement callbacks. Results and errors come back as separate events. Handler errors are sent to the calling socket only, as chat:error with { message: string }.

Membership: chat:join and chat:message first check that the socket's user is a participant of the room (and that the room is not deleted); otherwise the caller gets chat:error with { message: "You are not a participant in this chat room" } and nothing is joined, sent or saved. chat:typing and chat:leave are ignored unless the socket has already joined room:<roomId> through chat:join.

chat:join

Payload: { roomId: string }

  1. Checks the caller is a participant (see above), then joins the socket to room:<roomId>.
  2. Emits chat:history to the caller: { roomId, messages }.
  3. Emits chat:user_joined to the other sockets in room:<roomId>: { userId, username, timestamp } (timestamp is an ISO string).

messages comes from chatService.getRecentMessages(roomId, 50), which despite its name returns the first (oldest) 50 non-deleted messages in stored order, oldest first. Each message is an embedded message document with senderId populated (_id, firstName, lastName, avatar, email). For older or newer pages use GET /api/v1/chat/rooms/{roomId}/messages with offset. An unknown or deleted room fails the participant check with chat:error. Joining does not mark messages as read (the service has a markMessagesAsRead method but nothing calls it).

chat:message

Payload: { roomId: string, content: string, messageType?: string, replyToId?: string }

  1. Checks the caller is a participant (see above), then saves the message into the room's embedded messages array and updates the room's lastMessage, lastMessageAt, lastMessageSenderId.
  2. Emits chat:message to all sockets in room:<roomId> (the sender included): the saved message plus roomId and sender: { id, username }.
  3. Emits chat:room_updated to the personal room user:<id> of every participant of the chat room: { roomId, lastMessage, lastMessageAt } (lastMessage is the content, lastMessageAt an ISO string). This is how a conversation list updates for users who do not have the conversation open.
  4. Calls notifyNewChatMessage (see section 3) for offline participants.

Notes:

  • messageType defaults to lowercase "text" here, while the model enum and the REST endpoint use uppercase TEXT, IMAGE, FILE, AUDIO. The write does not run schema validators, so the value is stored as sent. Clients should always send the uppercase value explicitly.
  • The sender does not have to have sent chat:join first; but they only receive the chat:message echo if their socket is in room:<roomId>.
  • If the room does not exist, or the caller is not a participant, the caller gets chat:error with { message: "You are not a participant in this chat room" }.

Saved message shape (as emitted):

{
  "_id": "6660a7d49b1d4a0012ab3551",
  "senderId": { "_id": "665f1c2e9b1d4a0012ab34c4", "firstName": "Amaka", "lastName": "Eze", "avatar": "https://..." },
  "content": "Is the flat still available?",
  "messageType": "TEXT",
  "readBy": [],
  "deletedAt": null,
  "editedAt": null,
  "replyToId": null,
  "createdAt": "2026-06-05T14:02:10.107Z",
  "updatedAt": "2026-06-05T14:02:10.107Z",
  "roomId": "6660a7d49b1d4a0012ab3550",
  "sender": { "id": "665f1c2e9b1d4a0012ab34c4", "username": "Amaka Eze" }
}

chat:typing

Payload: { roomId: string, isTyping: boolean }

Emits chat:typing to the other sockets in room:<roomId> (not the sender): { userId, username, isTyping }. Ignored silently if this socket has not joined room:<roomId> with chat:join. Nothing is stored. No error event.

chat:leave

Payload: { roomId: string }

Removes the socket from room:<roomId> and emits chat:user_left to the remaining sockets in it: { userId, username }. Ignored if the socket is not in that room.

chat:get_rooms

No payload.

Emits chat:rooms to the caller: an array of the user's rooms, identical to the data of GET /api/v1/chat/rooms (participant of, not deleted, sorted by lastMessageAt descending; createdBy, participants, lastMessageSenderId and referencedProperty populated; each room includes its full embedded messages array).

chat:create_and_send

Payload: { propertyId: string, content: string, messageType?: string } (messageType defaults to "TEXT")

The "message the agent about this property" flow. In order:

  1. Finds or creates (atomic upsert) the room keyed on (this user, propertyId). On creation the room is named after the sender (username, falling back to the user id), is private, and its participants are the sender plus the property's agentId, or its landlordId when there is no agent. This auto-adding of the agent/landlord is only done here; POST /api/v1/chat/rooms does not do it.
  2. Joins the sender's socket to room:<roomId>.
  3. Saves the message.
  4. Emits chat:message to room:<roomId> (same shape as above, with roomId and sender). The other participant is normally not in that socket room yet, so they learn about the conversation from step 6.
  5. If this is the first message in the room: for each other participant, NotificationService.createAndEmit with event type new_chat_request, title New Chat Message, body <sender name> started a new conversation with you., meta: { roomId, propertyId }. This one is stored in the notifications list and emitted as notifications:new; push and email are sent only if the recipient is offline. Otherwise (room already had messages): notifyNewChatMessage as for a normal message.
  6. Emits chat:rooms to user:<id> of every participant with that participant's full refreshed room list.

Errors go to the caller as chat:error ({ message }), e.g. Failed to find or create room or a database/cast error message for a bad propertyId.

notifications:subscribe

No payload. Joins notifications:global and emits notifications:subscribed { success: true } to the caller. Not needed to receive personal notifications; those always go to user:<userId>.

disconnect

Logged. chatService.handleUserDisconnect is a stub (TODO in the source): no presence or last-seen event is broadcast.

Events the server emits (server to client)

EventPayloadTargetEmitted by
chat:history{ roomId, messages: Message[] }Calling socketchat:join
chat:user_joined{ userId, username, timestamp }room:<roomId> except callerchat:join
chat:user_left{ userId, username }room:<roomId> except callerchat:leave
chat:typing{ userId, username, isTyping }room:<roomId> except callerchat:typing
chat:messageSaved message + roomId + sender: { id, username }room:<roomId> (all, sender included)Socket chat:message, chat:create_and_send
chat:messageSaved message + sender: { id, username } (no roomId)room:<roomId>REST POST /api/v1/chat/rooms/{roomId}/messages
chat:room_updated{ roomId, lastMessage, lastMessageAt }user:<id> of each participantSocket chat:message only (not the REST send, not chat:create_and_send)
chat:roomsRoom[] (full room list of the recipient)Calling socketchat:get_rooms
chat:roomsRoom[]user:<id> of each participantchat:create_and_send; REST POST /api/v1/chat/rooms (creator plus the ids passed in participants)
chat:error{ message }Calling socketAny failing chat handler
notifications:subscribed{ success: true }Calling socketnotifications:subscribe
notifications:newSee belowuser:<recipientId>NotificationService.createAndEmit
escrow:status_updated{ escrowTxId, status, propertyStatus? }user:<buyerId> or user:<sellerId>Escrow controller and Pandascrow webhook (section 3)
booking:updated{ bookingId, propertyId, status, type }user:<tenantId> and user:<landlordId>Booking service via streamService.sendToUser (also SSE)
notification:new{ id, userId, title, body, type, metadata, read, createdAt }user:<callerId>POST /api/v1/stream/notify (also SSE)

notifications:new payload:

{
  "id": "6660a7d49b1d4a0012ab35a0",
  "eventType": "lawyer_assigned",
  "type": "property",
  "title": "New Legal Assignment",
  "body": "You have been assigned to review the legal status of property: 3-Bedroom Flat, Lekki Phase 1",
  "isRead": false,
  "createdAt": "2026-06-04T09:15:22.481Z",
  "meta": { "assignmentId": "6660a7d49b1d4a0012ab3501", "propertyId": "665f1c2e9b1d4a0012ab34cd" }
}

id is the stored Notification document id. type is a UI grouping derived from eventType: messages (new_chat_request, new_message), payments (payment_request, payment_request_accepted, escrow_funded, escrow_completed, escrow_disputed), security (new_device_login, password_changed), otherwise property. meta differs per event.

Naming trap: notifications:new (plural, stored notifications from the notification service, Socket.IO only) and notification:new (singular, the unstored test notification from POST /api/v1/stream/notify, Socket.IO and SSE) are different events.

SSE stream (src/routes/stream.route.ts)

Mounted at /api/v1/stream. (The comment in the route file shows /api/stream/events; the real path is /api/v1/stream/events.)

Connection and auth

GET /api/v1/stream/events, guarded by the streamAuth middleware:

  • Token from Authorization: Bearer <token>; if absent, from the ?token=<token> query parameter (for browser EventSource, which cannot set headers).
  • The token is the normal JWT access token. streamAuth verifies signature and expiry only. It does not load the user from the database, so deleted or deactivated accounts with an unexpired token are accepted, and req.user.role is a placeholder "user"; no stream route authorizes on it.
  • Checked once at connect. The stream is not closed when the token later expires; conversely, when EventSource auto-reconnects it re-sends the same URL, so a reconnect after expiry gets a 401 and the client must rebuild the URL with a fresh token.
  • Putting the token in the query string means it can appear in access logs and proxies.

Auth failures use their own JSON shape (not the standard API envelope):

StatusBody
401{ "success": false, "error": "No token provided" }
401{ "success": false, "error": "Token expired" }
401{ "success": false, "error": "Invalid token" }
500{ "success": false, "error": "Auth failed" }

On success the response is 200 with headers Content-Type: text/event-stream, Cache-Control: no-cache, Connection: keep-alive, X-Accel-Buffering: no.

const es = new EventSource(`${API_ORIGIN}/api/v1/stream/events?token=${accessToken}`);
es.addEventListener("connected", (e) => console.log(JSON.parse(e.data)));
es.addEventListener("booking:updated", (e) => refreshBooking(JSON.parse(e.data)));

All events are named events, so es.onmessage never fires; use addEventListener(name, ...).

A user can hold any number of simultaneous streams (the registry is Map<userId, Set<Response>>); every stream gets every event for that user. The entry is removed when the request closes.

Heartbeat

Every 30 seconds the server writes the SSE comment line :heartbeat followed by a blank line. Comments keep intermediaries from timing the connection out and do not trigger client handlers. No id: or retry: fields are ever sent, so there is no replay on reconnect (Last-Event-ID is not supported); events emitted while a client is disconnected are lost.

Events

Frame format is event: <name>\ndata: <JSON>\n\n.

EventDataWhen
connected{ "userId": string, "timestamp": ISO string }Immediately after the stream opens
booking:updated{ "bookingId": string, "propertyId": string, "status": "requested" | "confirmed" | "completed" | "cancelled", "type": "viewing" | "reservation" | "shortlet" }A booking is confirmed or cancelled; sent to both the tenant and the landlord
notification:new{ "id": "notif_<ms timestamp>", "userId", "title", "body", "type" (default "info"), "metadata": {}, "read": false, "createdAt": ISO string }POST /api/v1/stream/notify; to the caller's own streams only

What is not on SSE: the stored platform notifications (notifications:new), all chat:* events and escrow:status_updated. Those are emitted with global.io directly and are Socket.IO only. A client that needs the notification bell or chat to update live must use Socket.IO.

The POST route

Guarded by streamAuth (bearer header or ?token=), so it is not public. It has no role check and only ever reaches the caller's own streams.

  • POST /api/v1/stream/notify body { title, body, type? }. Sends notification:new to the caller's own SSE streams and Socket.IO personal room. Marked "test/demo" in the source. Nothing is stored. Response { "success": true, "data": <payload> }.

Handler failures: 500 { "success": false, "error": "<message>" }.

Presence

streamService.isUserOnline(userId) returns true when the user has at least one open SSE stream or at least one socket in user:<userId>. It is used only to decide whether to fall back to push/email for chat notifications (onlyWhenOffline). An idle open SSE stream therefore suppresses chat push and email even though chat messages themselves are never delivered over SSE.

Who emits what

NotificationService.createAndEmit (the main notify helper)

src/services/notification.service.ts. One call fans out to up to four channels, each gated by the recipient's notificationPreferences[<row>] (defaults when unset: inApp: true, email: true, sms: false):

  1. In-app + socket (when inApp is on and storeInApp is not disabled): creates a Notification document and emits notifications:new to user:<recipientId> on Socket.IO.
  2. If onlyWhenOffline is set and the recipient is online (socket or SSE), stops here.
  3. Push (when inApp is on): PushService.sendToUser, Expo push to every registered device token, with title, body and data: { notificationId, eventType, type, meta }, sound default, priority high, Android channel default. Tokens Expo reports as DeviceNotRegistered are removed from the user.
  4. Email (when email is on): a custom template if the caller supplied one, otherwise the generic notification email; subject defaults to <title> | HomeLink Hub. Optional per-key throttle.
  5. SMS (when sms is on, the user has a phone, and SMS_NOTIFICATIONS_ENABLED is set): HomeLink Hub: <title>. <body> cut to 300 characters.

It never throws, and push/email/SMS are not awaited. It does not write to SSE.

Preference row per event type: inspection_request, inspection_reviewed, booking_requested, booking_confirmed, booking_cancelled -> inspectionBookings; new_device_login, password_changed, agent_review_received -> systemUpdates; new_chat_request, new_message -> newMessages; lawyer_* -> lawyerVerificationUpdates; payment_request -> propertyInquiries; payment_request_accepted, escrow_funded, escrow_completed, escrow_disputed -> escrowUpdates. Callers can override the row (chat and escrow payees do).

Callers:

CallerEvent typeRecipientNotes
auth.controller (session helper, signin, googleCallback)new_device_loginThe user signing inTitle New Login Detected; sent when the account already had active sessions
auth.controller.resetPassword, user.controller.changePasswordpassword_changedThe user
inspection.controller.requestInspectioninspection_requestProperty host
inspection.controller.reviewInspectioninspection_reviewedVisitor
review.controller.createReviewagent_review_receivedReviewed agent
booking.service (payment-request helper)payment_requestProperty's agent, else landlordTitle New Stay Request (short-let) or New Payment Request
booking.service.createBookingbooking_requestedHost
booking.service.confirmBookingpayment_request_accepted (reservation/short-let) or booking_confirmed (viewing)TenantAlso emits booking:updated
booking.service.cancelBookingbooking_cancelledOther partyAlso emits booking:updated
escrow-notification.service.notifyEscrowStatusescrow_funded, escrow_completed, escrow_disputedBuyer (row escrowUpdates); seller and commission agent (row paymentConfirmations)Called from the escrow controller and the Pandascrow webhook
legal.service.assignLawyer / auto-assign / reassignLawyerlawyer_assignedThe (new) lawyerTitle New Legal Assignment; email New Legal Assignment on HomeLink Hub
legal.service.acceptAssignmentlawyer_review_startedUser who assignedTitle Legal Review Started; email subject Legal Assignment Accepted
legal.service.submitDecisionlawyer_verification_completed (verified, rejected) or lawyer_changes_requestedUser who assignedTitle Legal Review Decision: <outcome>; generic email
legal.service.submitDocumentslawyer_documents_submittedThe lawyerTitle New Documents to Review
sockets/web.socket.ts chat:create_and_send (first message in a room)new_chat_requestOther participantsStored in-app; push/email only when offline
chat.service.notifyNewChatMessagenew_messageOther participantsSee below

notifyNewChatMessage (called from socket chat:message, socket chat:create_and_send for non-first messages, and REST POST /api/v1/chat/rooms/{roomId}/messages): for each participant other than the sender, createAndEmit with storeInApp: false (so no Notification document and no notifications:new event), onlyWhenOffline: true, and an email throttle of one email per recipient per room per 30 minutes (in-memory). Net effect: an online user gets nothing extra; an offline user gets a push per message and at most one email per half hour. Title New message from <sender>; body is the content cut to 140 characters, or Sent a photo / Sent a file / Sent a voice note for IMAGE / FILE / AUDIO, followed by About: <property title> when the room references a property. meta: { roomId, propertyId }. Preference row is agentMessages when the recipient is the room creator (the tenant) and newMessages otherwise.

Legal actions that send email only (notifyByEmail, no in-app/socket/push): sendInviteByEmail (to the lawyer), acceptPartnershipInvite (to the inviter), startReview (to the assigner). rejectPartnershipInvite sends nothing.

Direct Socket.IO emits (not through the notification service)

WhereEventTargetPayload
message.controller.createRoom (POST /api/v1/chat/rooms)chat:roomsuser:<id> for the creator and each id in the request's participantsThat user's full room list
message.controller.sendMessage (POST /api/v1/chat/rooms/{roomId}/messages)chat:messageroom:<roomId>Saved message + sender: { id, username } (no roomId)
escrow.controller.markEscrowPaymentMade (PATCH /api/v1/escrow/{id}/payment-made)escrow:status_updateduser:<sellerId>{ escrowTxId, status: "funded" }
escrow.controller.requestEscrowCompletion (PATCH /api/v1/escrow/{id}/request-completion)escrow:status_updateduser:<sellerId>{ escrowTxId, status: "completed", propertyStatus } (propertyStatus omitted for short-lets)
middleware/webhook.ts handleEscrowPaid (Pandascrow escrow.paid)escrow:status_updateduser:<buyerId>{ escrowTxId, status: "funded" }
middleware/webhook.ts handleEscrowCompleted (Pandascrow escrow.completed)escrow:status_updateduser:<buyerId>{ escrowTxId, status: "completed" }
sockets/web.socket.tsall chat:* events, notifications:subscribedsee section 1

Each of the four escrow emitters also calls notifyEscrowStatus, so the same transition additionally produces notifications:new + push + email for the buyer, seller and agent. The webhook's dispute handler calls notifyEscrowStatus(..., "disputed") but does not emit escrow:status_updated.

streamService (SSE + Socket.IO together)

WhereCallEventTarget
booking.service announceBookingChange (from confirmBooking, cancelBooking)sendToUserbooking:updatedTenant and landlord: their SSE streams and user:<id> socket rooms
POST /api/v1/stream/notifysendNotification -> sendToUsernotification:newThe caller: SSE streams and user:<id> socket room
routes/stream.route.tsregisterClient / removeClientconnected (on register)The new stream
notification.serviceisUserOnlinenonePresence check for onlyWhenOffline
  • Admin (/api/v1/admin/*): none. No admin endpoint emits a socket/SSE event, push or email (resolving a duplicate flag, changing a role, deactivating a user and withdrawing funds are all silent).
  • Legal (/api/v1/legal/*): assign-lawyer, reassign, accept, decision and documents produce notifications:new (to the lawyer or the assigner) plus push and email. partnership-invites/email, partnership-invites/{id}/accept and start-review send email only. partnership-invites/{id}/reject and all GETs send nothing.
  • Chat (/api/v1/chat/*): POST /rooms emits chat:rooms; POST /rooms/{roomId}/messages emits chat:message and triggers offline push/email. DELETE /messages/{messageId} and POST /rooms/{roomId}/report emit nothing, so a deleted message stays on other clients' screens until they refetch.

Pitfalls

  1. Chat REST routes and the chat:join / chat:message socket events are limited to room participants; chat:typing and chat:leave only work after a successful chat:join.
  2. There is no system-wide broadcast route; the old POST /api/v1/stream/broadcast was removed because it had no admin check.
  3. Two near-identical event names: notifications:new (real, stored, socket only) vs notification:new (test, unstored, socket + SSE).
  4. SSE carries only connected, booking:updated and notification:new. The notification bell and chat need Socket.IO.
  5. chat:history and GET .../messages return the oldest messages first and page from the start of the conversation.
  6. The REST send path and the socket send path are not equivalent: only the socket chat:message handler emits chat:room_updated, and only socket-originated chat:message payloads include roomId.
  7. Socket chat:message defaults messageType to lowercase "text"; send the uppercase enum value explicitly.
  8. streamAuth does not check that the user still exists; the Socket.IO handshake does. Neither checks isActive.
  9. No replay: events missed while disconnected are gone (no SSE event ids, no socket recovery configured). Refetch over REST after reconnecting.
  10. Everything is in-memory, single-instance: presence, SSE registry, socket rooms and the chat email throttle.

On this page