learn react ui logoLearnReactUI
WebSocket Chat App Example with MSW

WebSocket Chat App Example with MSW

A demonstration app showcasing how to implement real-time WebSocket communication with Mock Service Worker (MSW). This example is ideal for learning how to mock WebSocket interactions and build dynamic chat functionality in a controlled development environment.

[Demo]

Features

  • Real-time Communication: Send and receive messages instantly through WebSocket.
  • MSW Integration: Mock WebSocket interactions for testing and development without relying on an external server.
  • State Management: Manage chat responses with Zustand.
  • Responsive UI: User-friendly and responsive chat interface styled with Emotion and Ant Design.

Usage

Start the Mock Server

The application uses MSW to mock WebSocket connections. The mock server is automatically initialized in the example wrapper

// const wssUri = 'wss://onurdayibasi.dev'
// src/mocks/handlers.js
import { ws } from "msw";

import { wssUri } from "../server/api-uris";

const chat = ws.link(wssUri);

export const wsHandlers = [
  chat.addEventListener("connection", ({ client }) => {
    client.addEventListener("message", (event) => {
      client.send(event.data);
    });
  }),
];

ChatApp is an UI App which uses Websocket connections

const ws = new WebSocket(wssUri);

React.useEffect(() => {
  const handleMsg = (event) => {
    addResponse({ role: "user", content: event.data });
  };

  ws.addEventListener("message", handleMsg);
  return () => {
    ws.removeEventListener("message", handleMsg);
  };
}, []);

///
///

<Button
  type="primary"
  shape="circle"
  icon={<ArrowCircleUp size={42} />}
  onClick={() => ws.send(value)}
/>;

Technologies Used

  • React: Component-based architecture.
  • WebSocket: Real-time bidirectional communication.
  • MSW: Mock Service Worker for intercepting network requests.
  • Zustand: Lightweight state management.
  • Ant Design: UI components for consistent design.
  • Emotion: CSS-in-JS styling for React components.