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:
| Mechanism | Transport | Used for |
|---|---|---|
| Socket.IO | WebSocket / long-polling on the API host | Chat, stored notifications (notifications:new), escrow status, booking updates, test notifications |
| SSE | GET /api/v1/stream/events | Booking updates and test notifications only |
| Expo push | Expo push service | Phone 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.tson 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_ORIGINSenvironment variable (comma separated), methodsGET/POST,credentials: true. - The instance is stored in three places:
global.io,app.set("io", io), and the local variable passed toinitializeWebSocket.
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
Bearerprefix. - It is read from
socket.handshake.auth.tokenfirst, thensocket.handshake.query.token. - The token is verified with
verifyAccessToken, then the user is loaded from the database (so a deleted user cannot connect).isActiveis 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:
| Message | Cause |
|---|---|
Token required for WebSocket connection | No token in auth or query |
Invalid or expired token | Verification failed for any reason (expired, bad signature, missing user id in payload) |
Invalid token payload | Decoded token has no user_id (in practice verifyAccessToken already rejects this, so the previous message is what clients see) |
User not found | Token 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
| Room | Who is in it | How a socket joins |
|---|---|---|
user:<userId> | Every socket of that user | Automatically on connection |
room:<chatRoomId> | Sockets currently viewing that conversation | chat:join, or implicitly for the sender on chat:create_and_send; left with chat:leave |
notifications:global | Sockets that asked for it | notifications: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 }
- Checks the caller is a participant (see above), then joins the socket to
room:<roomId>. - Emits
chat:historyto the caller:{ roomId, messages }. - Emits
chat:user_joinedto the other sockets inroom:<roomId>:{ userId, username, timestamp }(timestampis 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 }
- Checks the caller is a participant (see above), then saves the message into the room's embedded
messagesarray and updates the room'slastMessage,lastMessageAt,lastMessageSenderId. - Emits
chat:messageto all sockets inroom:<roomId>(the sender included): the saved message plusroomIdandsender: { id, username }. - Emits
chat:room_updatedto the personal roomuser:<id>of every participant of the chat room:{ roomId, lastMessage, lastMessageAt }(lastMessageis the content,lastMessageAtan ISO string). This is how a conversation list updates for users who do not have the conversation open. - Calls
notifyNewChatMessage(see section 3) for offline participants.
Notes:
messageTypedefaults to lowercase"text"here, while the model enum and the REST endpoint use uppercaseTEXT,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:joinfirst; but they only receive thechat:messageecho if their socket is inroom:<roomId>. - If the room does not exist, or the caller is not a participant, the caller gets
chat:errorwith{ 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:
- 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'sagentId, or itslandlordIdwhen there is no agent. This auto-adding of the agent/landlord is only done here;POST /api/v1/chat/roomsdoes not do it. - Joins the sender's socket to
room:<roomId>. - Saves the message.
- Emits
chat:messagetoroom:<roomId>(same shape as above, withroomIdandsender). The other participant is normally not in that socket room yet, so they learn about the conversation from step 6. - If this is the first message in the room: for each other participant,
NotificationService.createAndEmitwith event typenew_chat_request, titleNew Chat Message, body<sender name> started a new conversation with you.,meta: { roomId, propertyId }. This one is stored in the notifications list and emitted asnotifications:new; push and email are sent only if the recipient is offline. Otherwise (room already had messages):notifyNewChatMessageas for a normal message. - Emits
chat:roomstouser:<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)
| Event | Payload | Target | Emitted by |
|---|---|---|---|
chat:history | { roomId, messages: Message[] } | Calling socket | chat:join |
chat:user_joined | { userId, username, timestamp } | room:<roomId> except caller | chat:join |
chat:user_left | { userId, username } | room:<roomId> except caller | chat:leave |
chat:typing | { userId, username, isTyping } | room:<roomId> except caller | chat:typing |
chat:message | Saved message + roomId + sender: { id, username } | room:<roomId> (all, sender included) | Socket chat:message, chat:create_and_send |
chat:message | Saved 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 participant | Socket chat:message only (not the REST send, not chat:create_and_send) |
chat:rooms | Room[] (full room list of the recipient) | Calling socket | chat:get_rooms |
chat:rooms | Room[] | user:<id> of each participant | chat:create_and_send; REST POST /api/v1/chat/rooms (creator plus the ids passed in participants) |
chat:error | { message } | Calling socket | Any failing chat handler |
notifications:subscribed | { success: true } | Calling socket | notifications:subscribe |
notifications:new | See below | user:<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 browserEventSource, which cannot set headers). - The token is the normal JWT access token.
streamAuthverifies signature and expiry only. It does not load the user from the database, so deleted or deactivated accounts with an unexpired token are accepted, andreq.user.roleis 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
EventSourceauto-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):
| Status | Body |
|---|---|
| 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.
| Event | Data | When |
|---|---|---|
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/notifybody{ title, body, type? }. Sendsnotification:newto 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):
- In-app + socket (when
inAppis on andstoreInAppis not disabled): creates aNotificationdocument and emitsnotifications:newtouser:<recipientId>on Socket.IO. - If
onlyWhenOfflineis set and the recipient is online (socket or SSE), stops here. - Push (when
inAppis on):PushService.sendToUser, Expo push to every registered device token, withtitle,bodyanddata: { notificationId, eventType, type, meta }, sounddefault, priorityhigh, Android channeldefault. Tokens Expo reports asDeviceNotRegisteredare removed from the user. - Email (when
emailis on): a custom template if the caller supplied one, otherwise the generic notification email; subject defaults to<title> | HomeLink Hub. Optional per-key throttle. - SMS (when
smsis on, the user has a phone, andSMS_NOTIFICATIONS_ENABLEDis 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:
| Caller | Event type | Recipient | Notes |
|---|---|---|---|
auth.controller (session helper, signin, googleCallback) | new_device_login | The user signing in | Title New Login Detected; sent when the account already had active sessions |
auth.controller.resetPassword, user.controller.changePassword | password_changed | The user | |
inspection.controller.requestInspection | inspection_request | Property host | |
inspection.controller.reviewInspection | inspection_reviewed | Visitor | |
review.controller.createReview | agent_review_received | Reviewed agent | |
booking.service (payment-request helper) | payment_request | Property's agent, else landlord | Title New Stay Request (short-let) or New Payment Request |
booking.service.createBooking | booking_requested | Host | |
booking.service.confirmBooking | payment_request_accepted (reservation/short-let) or booking_confirmed (viewing) | Tenant | Also emits booking:updated |
booking.service.cancelBooking | booking_cancelled | Other party | Also emits booking:updated |
escrow-notification.service.notifyEscrowStatus | escrow_funded, escrow_completed, escrow_disputed | Buyer (row escrowUpdates); seller and commission agent (row paymentConfirmations) | Called from the escrow controller and the Pandascrow webhook |
legal.service.assignLawyer / auto-assign / reassignLawyer | lawyer_assigned | The (new) lawyer | Title New Legal Assignment; email New Legal Assignment on HomeLink Hub |
legal.service.acceptAssignment | lawyer_review_started | User who assigned | Title Legal Review Started; email subject Legal Assignment Accepted |
legal.service.submitDecision | lawyer_verification_completed (verified, rejected) or lawyer_changes_requested | User who assigned | Title Legal Review Decision: <outcome>; generic email |
legal.service.submitDocuments | lawyer_documents_submitted | The lawyer | Title New Documents to Review |
sockets/web.socket.ts chat:create_and_send (first message in a room) | new_chat_request | Other participants | Stored in-app; push/email only when offline |
chat.service.notifyNewChatMessage | new_message | Other participants | See 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)
| Where | Event | Target | Payload |
|---|---|---|---|
message.controller.createRoom (POST /api/v1/chat/rooms) | chat:rooms | user:<id> for the creator and each id in the request's participants | That user's full room list |
message.controller.sendMessage (POST /api/v1/chat/rooms/{roomId}/messages) | chat:message | room:<roomId> | Saved message + sender: { id, username } (no roomId) |
escrow.controller.markEscrowPaymentMade (PATCH /api/v1/escrow/{id}/payment-made) | escrow:status_updated | user:<sellerId> | { escrowTxId, status: "funded" } |
escrow.controller.requestEscrowCompletion (PATCH /api/v1/escrow/{id}/request-completion) | escrow:status_updated | user:<sellerId> | { escrowTxId, status: "completed", propertyStatus } (propertyStatus omitted for short-lets) |
middleware/webhook.ts handleEscrowPaid (Pandascrow escrow.paid) | escrow:status_updated | user:<buyerId> | { escrowTxId, status: "funded" } |
middleware/webhook.ts handleEscrowCompleted (Pandascrow escrow.completed) | escrow:status_updated | user:<buyerId> | { escrowTxId, status: "completed" } |
sockets/web.socket.ts | all chat:* events, notifications:subscribed | see 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)
| Where | Call | Event | Target |
|---|---|---|---|
booking.service announceBookingChange (from confirmBooking, cancelBooking) | sendToUser | booking:updated | Tenant and landlord: their SSE streams and user:<id> socket rooms |
POST /api/v1/stream/notify | sendNotification -> sendToUser | notification:new | The caller: SSE streams and user:<id> socket room |
routes/stream.route.ts | registerClient / removeClient | connected (on register) | The new stream |
notification.service | isUserOnline | none | Presence check for onlyWhenOffline |
Admin, legal and chat REST endpoints: realtime side effects at a glance
- 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,decisionanddocumentsproducenotifications:new(to the lawyer or the assigner) plus push and email.partnership-invites/email,partnership-invites/{id}/acceptandstart-reviewsend email only.partnership-invites/{id}/rejectand all GETs send nothing. - Chat (
/api/v1/chat/*):POST /roomsemitschat:rooms;POST /rooms/{roomId}/messagesemitschat:messageand triggers offline push/email.DELETE /messages/{messageId}andPOST /rooms/{roomId}/reportemit nothing, so a deleted message stays on other clients' screens until they refetch.
Pitfalls
- Chat REST routes and the
chat:join/chat:messagesocket events are limited to room participants;chat:typingandchat:leaveonly work after a successfulchat:join. - There is no system-wide broadcast route; the old
POST /api/v1/stream/broadcastwas removed because it had no admin check. - Two near-identical event names:
notifications:new(real, stored, socket only) vsnotification:new(test, unstored, socket + SSE). - SSE carries only
connected,booking:updatedandnotification:new. The notification bell and chat need Socket.IO. chat:historyandGET .../messagesreturn the oldest messages first and page from the start of the conversation.- The REST send path and the socket send path are not equivalent: only the socket
chat:messagehandler emitschat:room_updated, and only socket-originatedchat:messagepayloads includeroomId. - Socket
chat:messagedefaultsmessageTypeto lowercase"text"; send the uppercase enum value explicitly. streamAuthdoes not check that the user still exists; the Socket.IO handshake does. Neither checksisActive.- No replay: events missed while disconnected are gone (no SSE event ids, no socket recovery configured). Refetch over REST after reconnecting.
- Everything is in-memory, single-instance: presence, SSE registry, socket rooms and the chat email throttle.
HomeLink Hub