Skip to content

WebSocket Documentation

Overview

The BidScript backend uses WebSockets to provide real-time communication between the server and clients. WebSockets are used for features that require instant updates without polling, such as collaborative editing, chat notifications, and processing status updates.

Connection

Establishing a Connection

WebSocket connections are established at the following endpoint:

ws://localhost:3000/socket

For secure connections in production:

wss://api.bidscript.co.uk/socket

Authentication

Authentication is required for WebSocket connections. Include the JWT token as a query parameter when connecting:

const socket = io("https://api.bidscript.co.uk/socket", {
  query: {
    token: "your_jwt_token",
  },
});

Namespaces

The WebSocket server is organised into different namespaces for specific functionality:

Main Namespace (/)

The default namespace for general events and notifications.

Events

Connection Events:

  • connect: Triggered when connection is established
  • disconnect: Triggered when connection is closed
  • error: Triggered when an error occurs

Notification Events:

  • notification: General notifications
    // Event payload
    {
      "type": "info", // "info", "warning", "error", "success"
      "message": "string",
      "timestamp": "ISO date string"
    }
    

Status Update Events:

  • status:update: Processing status updates
    // Event payload
    {
      "jobId": "string",
      "status": "string", // "queued", "processing", "completed", "failed"
      "progress": number, // 0-100
      "details": "string"
    }
    

Chat Namespace (/chat)

Dedicated to chat functionality.

Events

Message Events:

  • message:new: New message received
// Event payload
{
  "sessionId": "string",
  "messageId": "string",
  "role": "string",
  "content": "string",
  "timestamp": "ISO date string"
}
  • message:update: Message content updated (for streaming responses)
    // Event payload
    {
      "sessionId": "string",
      "messageId": "string",
      "content": "string",
      "isComplete": boolean
    }
    

Session Events:

  • session:update: Chat session updated
    // Event payload
    {
      "sessionId": "string",
      "action": "string", // "created", "updated", "deleted"
      "data": object
    }
    

Editor Namespace (/editor)

For collaborative document editing.

Events

Document Events:

  • document:update: Document content updated
// Event payload
{
  "documentId": "string",
  "updates": [
    {
      "type": "string", // "insert", "delete", "format"
      "index": number,
      "length": number,
      "attributes": object,
      "userId": "string"
    }
  ]
}
  • document:cursor: User cursor position update
    // Event payload
    {
      "documentId": "string",
      "userId": "string",
      "position": {
        "index": number,
        "length": number
      }
    }
    

Collaboration Events:

  • user:join: User joined the editing session
// Event payload
{
  "documentId": "string",
  "userId": "string",
  "username": "string"
}
  • user:leave: User left the editing session
    // Event payload
    {
      "documentId": "string",
      "userId": "string"
    }
    

YJS Integration

The editor uses YJS for conflict-free collaborative editing:

import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";

// Create YJS document
const ydoc = new Y.Doc();

// Connect to WebSocket server with YJS provider
const provider = new WebsocketProvider(
  "wss://api.bidscript.co.uk/editor/yjs",
  "document-id",
  ydoc,
  { params: { token: "your_jwt_token" } }
);

// Access shared types
const ytext = ydoc.getText("content");

// Listen for updates
ytext.observe((event) => {
  console.log("Document updated:", event);
});

Client Implementation Example

import { io } from "socket.io-client";

// Connect to the WebSocket server
const socket = io("https://api.bidscript.co.uk/socket", {
  query: { token: "your_jwt_token" },
  transports: ["websocket"],
  reconnection: true,
  reconnectionAttempts: 5,
});

// Connect to specific namespace
const chatSocket = io("https://api.bidscript.co.uk/chat", {
  query: { token: "your_jwt_token" },
});

// Listen for events
socket.on("connect", () => {
  console.log("Connected to WebSocket server");
});

socket.on("status:update", (data) => {
  console.log("Status update:", data);
});

chatSocket.on("message:new", (message) => {
  console.log("New message:", message);
});

// Emit events
chatSocket.emit("join:session", { sessionId: "session-id" });

Error Handling

WebSocket errors are emitted through the error event:

socket.on("error", (error) => {
  console.error("WebSocket error:", error);
});

Common error codes:

  • 1000: Normal closure
  • 1001: Going away
  • 1002: Protocol error
  • 1003: Unsupported data
  • 1008: Policy violation
  • 1011: Internal server error

Reconnection Strategy

Socket.IO clients automatically handle reconnection. Configure reconnection settings:

const socket = io("https://api.bidscript.co.uk/socket", {
  reconnection: true,
  reconnectionAttempts: 10,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000,
  randomizationFactor: 0.5,
});