TalkNest

YearFeb, 2024 - March, 2024
TechnologyReact, Node.js (Express), 实时聊天, 视频通话, WebRTC, Socket.IO
Project

TalkNest demo

TalkNest video cover
0:00 / 0:14Conversations

Full-Stack Real-Time Application · 2024

TalkNest — Real-Time Chat and Peer-to-Peer Video Calls

A web chat application with live messaging, presence and one-to-one video calls. The interesting part is the routing: three kinds of data take three different paths, and the server never carries a single frame of video.

React Socket.IO WebRTC · simple-peer Firebase Auth Firestore Realtime Database Express Jest + Supertest GitHub Actions Heroku

▶ Demo Front-end source Back-end source

Start Here — a Map You Can Click

Two browsers, one small server and three Firebase services. The arrows follow one message and one call from A to B; the same paths run the other way. Click a box to jump to the part that explains it.

%%{init: {"themeCSS": "a { transition: none !important; }"}}%% flowchart LR A["Browser A<br/>React app"] B["Browser B<br/>React app"] Auth["Firebase Auth<br/>sign-in · ID tokens"] API["Express API + Socket.IO<br/>profiles · search · signalling"] FS[("Firestore<br/>users · chats · userChats")] RT[("Realtime Database<br/>presence · socket ids")] A -->|sign in| Auth A -->|REST · profiles, search| API A -->|write a message| FS FS -->|live update| B A -->|call set-up events| API API -->|forwarded to the callee| B API --> FS API --> RT A -.->|video + audio · peer to peer| B click Auth href "#tn-auth" "Sign-up and profiles" _self click FS href "#tn-chat" "Real-time messaging" _self click API href "#tn-call" "Video call signalling" _self click RT href "#tn-call" "Presence and signalling" _self

Three paths Sign-up and profiles Messaging Video calls CI/CD and tests Limits and next steps


1. Three Kinds of Data, Three Paths

A chat product moves data with very different needs. TalkNest gives each one the transport that fits it instead of pushing everything through one socket.

Data Path Why this path
Identity Firebase Auth in the browser: email and password, Google sign-in, password reset, email verification No passwords ever reach the application server.
Profiles and search REST calls to the Express API, which reads and writes Firestore through the Admin SDK Writes that change a profile are checked on the server against a verified ID token.
Chat messages The browser writes to Firestore and every open client receives the change through a live listener Durable history and real-time delivery come from the same write.
Presence and call set-up Socket.IO events, with each user's current socket id kept in the Realtime Database Signalling is small, short-lived and needs to reach one specific connection.
Video and audio WebRTC, directly between the two browsers Media is heavy and latency-sensitive; relaying it through the server would add cost and delay.

Design insight. The server is a matchmaker, not a carrier. It introduces two browsers to each other and steps aside, so call quality does not depend on server bandwidth.


2. Sign-Up and Profiles

Authentication stays with Firebase. The API only stores the profile that goes with an account, and it protects changes to that profile by verifying the caller's ID token.

sequenceDiagram autonumber actor User participant App as React app participant Auth as Firebase Auth participant API as Express API participant FS as Firestore User->>App: register · email, password, profile App->>Auth: createUserWithEmailAndPassword Auth-->>App: uid App->>Auth: sendEmailVerification App->>API: POST /api/users · uid + profile API->>FS: set users/{uid} · profile, timestamps API-->>App: 201 created App->>Auth: getIdToken Auth-->>App: ID token App->>API: PATCH or DELETE /api/user/{uid} · Bearer token API->>API: verifyIdToken · Firebase Admin SDK alt token valid API->>FS: update or delete users/{uid} API-->>App: 200 / 204 else missing or invalid API-->>App: 403 Unauthorized end
Endpoint Purpose Protection
POST /api/users Create the profile document after Firebase creates the account Rejects a request without uid or displayName (400)
GET /api/user/:id Read a profile 404 when the user does not exist
PATCH / DELETE /api/user/:id Update or remove a profile Firebase ID token verified on the server
GET /api/users/search Find people by name, email or id Returns only the public fields: id, display name, photo

3. Real-Time Messaging

A message is one write. The sender appends it to the chat document, and Firestore pushes the new state to every client that is listening, including the sender's own screen. There is no separate “deliver” step to get wrong.

sequenceDiagram autonumber actor Alice participant A as Alice · React app participant FS as Firestore participant B as Bob · React app actor Bob Alice->>A: pick Bob in search A->>A: chatId = larger uid + smaller uid A->>FS: create chats/{chatId} if missing A->>FS: add the chat to userChats of both users A->>FS: listen · onSnapshot(chats/{chatId}) B->>FS: listen · onSnapshot(chats/{chatId}) Alice->>A: type a message, send A->>FS: updateDoc · arrayUnion(message) A->>FS: update userChats of both · lastMessage, date FS-)A: snapshot · new message FS-)B: snapshot · new message B-->>Bob: message appears

One Id That Both Sides Can Compute

The chat id is the two user ids joined in a fixed order (the larger one first). Either user can derive it without asking the server, and both always arrive at the same document, so two people can never end up with two parallel conversations.

Data Model

classDiagram direction LR class User { +String uid +String email +String displayName +String photoURL +String bio +String location +Date createdAt +Date updatedAt } class UserChats { +Map chatId to ChatSummary } class ChatSummary { +UserInfo userInfo +Object lastMessage +Timestamp date } class Chat { +String chatId +Message[] messages } class Message { +String id +String text +String senderId +Timestamp date +String img } class Presence { +boolean online +String socketId } User "1" --> "1" UserChats : userChats/uid UserChats "1" --> "many" ChatSummary : one per chat ChatSummary --> Chat : chatId Chat "1" *-- "many" Message User "1" --> "0..1" Presence : Realtime Database
  • users, chats and userChats live in Firestore. userChats is a per-user index of conversations with the last message and its time, so the sidebar loads from one document.
  • Images go to Firebase Storage first; the message then carries the download URL.
  • Presence is the only data in the Realtime Database: it changes on every connect and disconnect and is never needed as history.

4. Video Calls — Signalling Through the Server, Media Around It

The Problem

Two browsers cannot open a WebRTC connection until each has the other's session description, and they have no way to exchange it directly. Something both can already reach has to pass those two messages along, to the right person, on the connection that person is using right now.

The Flow

sequenceDiagram autonumber actor Caller participant CA as Caller app participant S as Socket.IO server participant RT as Realtime Database participant CB as Callee app actor Callee CA->>S: register(userId) · on connect S->>RT: users/{userId} = online, socketId CB->>S: register(userId) · on connect S->>RT: users/{userId} = online, socketId Caller->>CA: click the video button CA->>CA: getUserMedia · new Peer(initiator) CA->>S: callUser(userToCall, offer, from) S->>RT: look up the callee's socketId alt callee is online S-)CB: callUser(offer, from) CB-->>Callee: show Answer else offline or unknown S->>S: log it, send nothing end Callee->>CB: Answer CB->>CB: getUserMedia · new Peer · signal(offer) CB->>S: answerCall(answer, to) S->>RT: look up the caller's socketId S-)CA: callAccepted(answer) CA->>CA: peer.signal(answer) CA-)CB: video + audio · peer to peer CB-)CA: video + audio · peer to peer Callee->>CB: Hang Up CB->>S: hangUp(to) S-)CA: hangUp

A Call as a State Machine

stateDiagram-v2 [*] --> Idle: socket registered Idle --> Calling: video button, offer sent Idle --> Ringing: callUser event arrives Calling --> Connected: callAccepted, answer applied Ringing --> Connected: Answer pressed, answer sent Connected --> Ended: Hang Up, or the peer hung up Ended --> [*]: page reloads to a clean state

The Signalling Contract

Event Sent by Carries Server action
register Each client on connect userId Marks the user online and stores the socket id
callUser Caller Callee id, WebRTC offer, caller id Looks up the callee's socket and forwards the offer
answerCall Callee WebRTC answer, caller id Looks up the caller's socket and emits callAccepted
hangUp The side that ends the call Peer id Forwards hangUp to the peer
disconnect Socket.IO — Removes the presence record

Two Decisions Worth Explaining

  • Socket ids are looked up, not remembered. A socket id changes on every reconnect, so the server keys presence by user id and resolves the current socket at the moment of the call. A stale id can never receive someone else's offer.
  • One offer, one answer. The peers are created with trickle: false, so each side sends a single message that already contains its network candidates. Set-up takes a little longer, but the whole handshake is two messages and the server needs no per-call state.

Design insight. The offer and the answer are opaque to the server. It routes them by user id and never parses them, which keeps the signalling layer independent of WebRTC itself.


5. CI/CD and Tests

flowchart LR Push["Push or pull request<br/>to main"] Install["Install<br/>Node 20 · npm install"] Test["Jest + Supertest<br/>API tests"] Gate{"Tests pass?"} Deploy["Deploy job<br/>Heroku"] Live["API + signalling server<br/>node server.js"] Stop["Run fails<br/>nothing is deployed"] Push --> Install Install --> Test Test --> Gate Gate -- Yes --> Deploy Deploy --> Live Gate -- No --> Stop

The back end is built and tested by GitHub Actions on every push and pull request to main. The deploy job depends on the test job, so a failing test stops the release.

Level Tool What it covers
API Jest + Supertest, run in CI Root route; validation of a new profile (400 without required fields); 404 for an unknown user; creating or selecting a chat
End to end Cypress, configured in the front end Target scenarios: start and accept a call, both video streams visible, hang up, chat still working during a call
Delivery Heroku for the API, a Dockerfile for the React build The server starts from a one-line Procfile; the front end is built once and served as static files

6. Limits and Next Steps

TalkNest was built in early 2024 as a complete, working product. Reading the code again, these are the changes that would matter most at larger scale:

Today Limit Next step
Default STUN servers only Peers behind strict NATs or firewalls may not connect Add a TURN relay as a fallback path
Offer and answer sent whole Call set-up waits for candidate gathering Trickle ICE: connect on the first working route
No call state on the server No busy, declined or missed-call handling A small per-call state machine on the server
Search scans the user collection Cost grows with the number of users Indexed prefix queries or a search service
Messages in one array per chat A long conversation approaches the document size limit A message subcollection with pagination

Technology Stack

Layer Technology Purpose
Front end React, React Router, context + reducer Chat UI, call UI, auth and chat state
Calls WebRTC through simple-peer Peer-to-peer video and audio
Signalling Socket.IO Presence and call set-up events
Back end Node.js, Express, Firebase Admin SDK Profiles, search, token verification, signalling
Data Firestore, Realtime Database, Firebase Storage Messages and profiles, presence, images
Identity Firebase Auth Email and password, Google sign-in, password reset
Quality and delivery Jest, Supertest, Cypress, GitHub Actions, Heroku, Docker API tests, end-to-end setup, automated build and deploy

Outcome

TalkNest is a small system with clear boundaries: identity delegated to a provider, durable data written once and fanned out by the database, a signalling server that only routes, and media that flows peer to peer. The same habit of matching each kind of data to the right path carries through to the event-driven platforms built later.

↑ Back to the map TalkNest on GitHub

Comments

Be kind. Comments are reviewed before appearing.