Skip to content

WebSocket API

This lesson explains WebSocket API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 WebSocket API Overview

The HTML5 WebSocket API allows web applications to create a persistent, two-way communication channel between the browser and a server. Unlike normal HTTP requests, a WebSocket connection stays open so both the client and server can send data whenever needed.

WebSockets are commonly used for chat applications, live dashboards, multiplayer games, stock tickers, collaboration tools, real-time notifications, live location tracking, and any feature that needs fast bidirectional updates.

Feature Description
API Name WebSocket API
Main Object WebSocket
Secure Protocol wss://
Main Events open, message, error, close
Main Method socket.send()
Common Uses Chat, live feeds, games, presence, collaboration, real-time alerts.

Basic WebSocket Example

// HTML5 WebSocket API

const socket =
  new WebSocket("wss://example.com/socket");

socket.addEventListener(
  "open",
  () => {
    console.log("Connection opened.");

    socket.send("Hello server");
  }
);

socket.addEventListener(
  "message",
  (event) => {
    console.log("Server says:", event.data);
  }
);

This example creates a connection, waits for it to open, sends a message to the server, and logs messages received from the server.

How WebSocket API Works

Step Description Example Syntax
Create Connection Open a socket to the server endpoint. new WebSocket("wss://example.com/socket")
Wait for Open Listen for successful connection setup. socket.addEventListener("open", callback)
Send Data Push text or binary data to the server. socket.send(data)
Receive Data Handle messages sent from the server. socket.addEventListener("message", callback)
Close Connection Stop communication when no longer needed. socket.close()

WebSocket Ready States

State Value Meaning
CONNECTING 0 The browser is still establishing the connection.
OPEN 1 The connection is active and messages can be sent.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection is closed or failed to open.

Connection Open and Close Events

const socket =
  new WebSocket("wss://example.com/chat");

socket.addEventListener(
  "open",
  () => {
    console.log("Connected to chat server.");
  }
);

socket.addEventListener(
  "close",
  (event) => {
    console.log(
      "Socket closed:",
      event.code,
      event.reason
    );
  }
);

The open event confirms that communication can begin, while the close event helps you understand why a connection ended.

Send JSON Data to Server

const socket =
  new WebSocket("wss://example.com/chat");

socket.addEventListener(
  "open",
  () => {
    const message =
      {
        type: "chat-message",
        username: "Ava",
        text: "Hello everyone"
      };

    socket.send(
      JSON.stringify(message)
    );
  }
);

JSON is a common format for WebSocket messages because it keeps communication structured and easy to extend.

Receive and Parse JSON Messages

socket.addEventListener(
  "message",
  (event) => {
    const payload =
      JSON.parse(event.data);

    if (payload.type === "chat-message") {
      console.log(
        payload.username + ":",
        payload.text
      );
    }
  }
);

Parse incoming data carefully and validate its shape before using it in the UI.

Simple Chat Client Example

<input id="chatInput" type="text" />
<button id="sendButton">Send</button>
<ul id="messages"></ul>
const socket =
  new WebSocket("wss://example.com/chat");

const input =
  document.querySelector("#chatInput");

const button =
  document.querySelector("#sendButton");

const messages =
  document.querySelector("#messages");

button.addEventListener(
  "click",
  () => {
    const text = input.value.trim();

    if (!text || socket.readyState !== WebSocket.OPEN) {
      return;
    }

    socket.send(
      JSON.stringify(
        {
          type: "chat-message",
          text: text
        }
      )
    );

    input.value = "";
  }
);

socket.addEventListener(
  "message",
  (event) => {
    const data =
      JSON.parse(event.data);

    const item =
      document.createElement("li");

    item.textContent = data.text;
    messages.appendChild(item);
  }
);

This small client sends chat text to a server and appends received messages to a list in the page.

Handle WebSocket Errors

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

The error event tells you that something went wrong, but browsers usually provide limited detail. Pair it with close event handling for better diagnostics.

Basic Reconnection Pattern

let socket = null;
let reconnectTimer = null;

function connect() {
  socket =
    new WebSocket("wss://example.com/live");

  socket.addEventListener(
    "open",
    () => {
      console.log("Connected.");
      clearTimeout(reconnectTimer);
    }
  );

  socket.addEventListener(
    "close",
    () => {
      reconnectTimer =
        setTimeout(connect, 3000);
    }
  );
}

connect();

A reconnect strategy is useful for live dashboards and other real-time features where temporary network problems are expected.

Close a WebSocket Connection Cleanly

function disconnectSocket() {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.close(1000, "User left page");
  }
}

window.addEventListener(
  "beforeunload",
  disconnectSocket
);

Close sockets when leaving the page or switching app modes so the server does not keep stale connections alive longer than needed.

Feature Detection

function supportsWebSockets() {
  return "WebSocket" in window;
}

if (supportsWebSockets()) {
  console.log("WebSocket API supported.");
} else {
  console.log("WebSocket API not supported.");
}

Feature detection helps you provide fallbacks such as polling or Server-Sent Events when WebSockets are unavailable.

Important WebSocket Events

Event When It Fires Common Use
open The connection has been established. Enable message sending and update status UI.
message The server sends data to the client. Update chat messages, feeds, or dashboards.
error A connection problem occurs. Log errors and trigger recovery logic.
close The socket closes or disconnects. Show offline state or attempt reconnection.

Common WebSocket API Use Cases

  • Real-time chat and messaging systems.
  • Live sports, stock, or analytics dashboards.
  • Collaborative editors and whiteboards.
  • Multiplayer browser games.
  • Presence indicators such as online and typing status.
  • IoT device monitoring and command panels.
  • Live customer support or notification streams.

WebSocket API Best Practices

  • Prefer wss:// in production for secure communication.
  • Validate message format before rendering or processing data.
  • Handle open, message, error, and close events explicitly.
  • Reconnect carefully with delays instead of reconnecting in a tight loop.
  • Close unused sockets when pages or components are destroyed.
  • Use heartbeats or server ping strategies in long-lived connections when needed.
  • Keep messages small and structured.
  • Authenticate and authorize users on the server side.

Security and Performance Considerations

  • Use wss:// to protect data in transit.
  • Never trust incoming messages without validation.
  • Limit message frequency to prevent flooding or abuse.
  • Sanitize text before inserting it into the DOM.
  • Be careful with auto-reconnect loops on unstable networks.
  • Monitor memory and event listener cleanup in single-page apps.

Common WebSocket API Mistakes

  • Calling socket.send() before the connection is open.
  • Forgetting to parse JSON message payloads safely.
  • Leaving sockets open after the user leaves the page.
  • Reconnecting instantly and endlessly after every disconnect.
  • Assuming browser-side validation is enough for security.
  • Ignoring the difference between ws:// and wss://.

WebSocket API vs Server-Sent Events

Feature WebSocket API Server-Sent Events
Direction Two-way communication. Server to client only.
Best For Chat, games, collaborative tools. Live feeds, simple push updates.
Send Client Messages Yes. No, use normal HTTP for client requests.
Protocol ws:// or wss:// Normal HTTP streaming.

Key Takeaways

  • The WebSocket API enables persistent two-way communication between browser and server.
  • Use new WebSocket() to create a connection and socket.send() to transmit data.
  • Handle the open, message, error, and close events in production code.
  • JSON is a practical format for structured real-time messages.
  • Secure, validated, and well-managed connections are essential for reliable real-time apps.

Pro Tip

If a feature only needs server-to-client updates, consider whether Server-Sent Events are simpler. Use WebSockets when you truly need fast two-way communication.