Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 74 ยท Projects

Project: Realtime Chat with WebSockets

Build a realtime chat in Angular with RxJS webSocket, a signal-based message list, validated incoming messages and automatic reconnect with backoff, using a fake socket in the runnable stand-ins.

HTTP is a question-and-answer protocol: the client asks, the server answers. A chat needs the server to speak first, whenever another user posts a message. WebSockets give you one long-lived, two-way connection for that. The Angular side is mostly about three things: turning the socket into a stream, keeping the connection alive when the network drops, and not trusting what arrives.

You should know RxJS Observables, RxJS Operators and Signals and RxJS Interop. The plan: define the message protocol, write a service that wraps the socket and reconnects, keep messages in signals, and build the screen.

Real versus stand-in. The typescript blocks are the real Angular app, to read and copy into a project made with ng new. The URL wss://chat.example.com/room is an invented endpoint: you need your own WebSocket server. The site cannot compile Angular and its sandbox cannot reach a server of yours, so the runnable examples use a fake socket that lives in the page and can be told to drop the connection. They demonstrate the logic: validation, status, reconnect delays and the UI.

Step 1: the plan

flowchart LR
  U["User types a message"] --> S["ChatService.send()"]
  S --> W["WebSocketSubject<br/>(rxjs/webSocket)"]
  W <--> SRV[("Chat server")]
  W --> P["parse + validate<br/>incoming JSON"]
  P --> M["messages signal"]
  W -. "error or close" .-> R["retry with backoff<br/>status: reconnecting"]
  M --> T["Template"]

Outgoing messages go straight to the subject; incoming ones are validated before they reach the signal.

The protocol

Both sides send JSON text. Agree on the shapes first:

  • Client to server: { "type": "say", "text": "hello" }
  • Server to client: { "type": "message", "id": 7, "user": "Maya", "text": "hello", "at": "2026-05-14T09:30:00Z" }

Anything else must be ignored, because the connection is a trust boundary: a bug or an attacker can send arbitrary text.

Step 2: types and a validating parser

TypeScript
// chat.ts
export interface ChatMessage {
  id: number;
  user: string;
  text: string;
  at: string;
}

export function parseMessage(raw: unknown): ChatMessage | null {
  if (typeof raw !== 'object' || raw === null) return null;
  const m = raw as Record<string, unknown>;
  if (m['type'] !== 'message') return null;
  if (typeof m['id'] !== 'number' || typeof m['user'] !== 'string') return null;
  if (typeof m['text'] !== 'string' || typeof m['at'] !== 'string') return null;
  if (m['text'].length > 2000) return null;
  return { id: m['id'], user: m['user'].slice(0, 40), text: m['text'], at: m['at'] };
}

Rendering is safe because Angular escapes interpolation by default (Security and Accessibility); never put chat text into innerHTML or [innerHTML].

Step 3: the service

webSocket() from rxjs/webSocket returns a subject: subscribing opens the connection, next() sends a message (serialized as JSON by default), and unsubscribing closes it. Reconnecting is a matter of subscribing again, which retry does for us. The delay option can be a function, so we can implement exponential backoff.

TypeScript
// chat.service.ts
import { computed, DestroyRef, inject, Injectable, signal } from '@angular/core';
import { retry, timer } from 'rxjs';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
import { ChatMessage, parseMessage } from './chat';

export type ConnectionStatus = 'connecting' | 'open' | 'reconnecting';

@Injectable({ providedIn: 'root' })
export class ChatService {
  private readonly messagesState = signal<ChatMessage[]>([]);
  private readonly statusState = signal<ConnectionStatus>('connecting');
  private socket?: WebSocketSubject<unknown>;

  readonly messages = this.messagesState.asReadonly();
  readonly status = this.statusState.asReadonly();
  readonly canSend = computed(() => this.statusState() === 'open');

  constructor() {
    const destroyRef = inject(DestroyRef);

    this.socket = webSocket({
      url: 'wss://chat.example.com/room', // invented endpoint
      openObserver: { next: () => this.statusState.set('open') },
      closeObserver: { next: () => this.statusState.set('reconnecting') },
    });

    const subscription = this.socket
      .pipe(
        retry({
          delay: (_error, attempt) => {
            this.statusState.set('reconnecting');
            return timer(Math.min(1000 * 2 ** (attempt - 1), 30_000)); // 1s, 2s, 4s ... 30s
          },
        }),
      )
      .subscribe(raw => {
        const message = parseMessage(raw);
        if (message) this.messagesState.update(list => [...list, message].slice(-200));
      });

    destroyRef.onDestroy(() => subscription.unsubscribe());
  }

  send(text: string): boolean {
    const clean = text.trim();
    if (!clean || clean.length > 2000 || !this.canSend()) return false;
    this.socket?.next({ type: 'say', text: clean });
    return true;
  }
}

Four details are worth noticing:

  • The status is a signal, so the screen can disable the Send button and show "Reconnecting..." without any subscription code in the component.
  • The backoff doubles each attempt up to 30 seconds. Retrying immediately in a tight loop would hammer a server that is already struggling. Real apps often add random jitter so thousands of clients do not reconnect at the same instant.
  • Only the last 200 messages are kept, so a long session does not grow memory without limit.
  • A message sent while offline is refused (send returns false) rather than silently lost. Queueing and resending is a possible extension.

The browser's WebSocket cannot send custom headers, so do not plan to put a token in an Authorization header. Authenticate with a short-lived token in the URL query or in the first message, and always use wss:// (encrypted) in production.

Step 4: the component

TypeScript
// chat-page.ts
import { Component, inject } from '@angular/core';
import { DatePipe } from '@angular/common';
import { ChatService } from './chat.service';

@Component({
  selector: 'app-chat-page',
  imports: [DatePipe],
  template: `
    <p role="status">
      @switch (chat.status()) {
        @case ('open') { Connected }
        @case ('reconnecting') { Reconnecting... }
        @default { Connecting... }
      }
    </p>

    <ul aria-live="polite">
      @for (m of chat.messages(); track m.id) {
        <li><b>{{ m.user }}</b> <time>{{ m.at | date: 'shortTime' }}</time>: {{ m.text }}</li>
      } @empty { <li>No messages yet.</li> }
    </ul>

    <form (submit)="$event.preventDefault(); send(box)">
      <input #box aria-label="Message" autocomplete="off" />
      <button type="submit" [disabled]="!chat.canSend()">Send</button>
    </form>
  `,
})
export class ChatPage {
  protected readonly chat = inject(ChatService);

  protected send(box: HTMLInputElement): void {
    if (this.chat.send(box.value)) box.value = '';
  }
}

The list is a live region so new messages are announced politely. The input is cleared only when send succeeded, so text typed while offline is not lost.

Step 5: run the reconnect and validation logic

The stand-in has a fake socket and a service with the same rules: validated messages, a status, and backoff delays. The delays are shortened (100 ms base) so the demo finishes quickly.

TypeScript Fake socket: validation, status and backoff

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The last three server pushes show why parsing matters: a message with a wrong id type, an unknown type, and text that is not even JSON are all counted as rejected and never reach the list. The text <b>team</b> is stored as plain text; Angular's interpolation will display it literally, not as bold.

Step 6: see it as a UI

The final stand-in is a chat screen in plain JavaScript with a fake server that answers after a moment. The Drop connection button simulates a network failure so you can watch the status change and the Send button disable until the socket comes back.

A working chat UI with a fake server

Ideas to extend it

  • Add random jitter to the backoff delay.
  • Show a "user is typing" indicator from a typing message type.
  • Queue messages typed while offline and send them after reconnect.
  • Add rooms by putting the room name in the URL and a signal for the current room.
  • Test ChatService by replacing webSocket with a WebSocketSubject created from a webSocketCtor test double (Testing Angular Applications).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the chat parse and validate every incoming message?

    Never assume the other end follows your protocol. Check the shape and size of the data before it enters your state.
  2. 2. What does the retry delay function with exponential backoff do?

    Doubling the delay (1 s, 2 s, 4 s, up to 30 s) spreads reconnect attempts out in time.
  3. 3. Why is the connection status stored as a signal in the service?

    A signal is a simple, readable piece of state. The component reads status() and canSend() directly.
  4. 4. Why does the service keep only the last 200 messages?

    An unbounded list grows forever. A cap keeps the app responsive; older history can be loaded on demand.

Summary

  • Define a small JSON protocol and validate every incoming message before it reaches your state.
  • Use webSocket() from rxjs/webSocket, retry with an exponential backoff delay, and a DestroyRef to close the connection.
  • Keep messages and the connection status in signals; derive canSend with computed().
  • Refuse to send while offline instead of losing messages silently, and cap the history length.
  • Render chat text only through interpolation, and use wss:// with a short-lived token for authentication.

Back to the first project: Project: Todo App with Signals.