0Pricing
React Academy · Lesson

WebSocket Fundamentals in the Browser

Open WebSocket connections, send messages, and handle events with the native WebSocket API.

WebSocket Fundamentals in the Browser is a free React Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is WebSocket?

WebSocket is a protocol providing full-duplex communication over a single TCP connection. Unlike HTTP, the connection stays open, allowing the server to push data to the client at any time.

Opening a Connection

Create a WebSocket object with a ws:// or wss:// URL. The connection opens asynchronously.

const ws = new WebSocket('wss://api.example.com/ws');

ws.onopen = () => {
  console.log('Connection established');
};

Sending Messages

Use ws.send() to send data. You can send strings or binary data (ArrayBuffer, Blob). JSON-encode objects before sending.

ws.onopen = () => {
  ws.send(JSON.stringify({ type: 'join', room: 'general' }));
  ws.send('Hello, server!');
};

Receiving Messages

The onmessage event fires whenever the server sends data. The data is in event.data as a string or binary type.

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
};

Handling Errors & Closing

Handle the onerror and onclose events. The close event includes a code and reason explaining why the connection ended.

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

ws.onclose = (event) => {
  console.log(`Closed: ${event.code} ${event.reason}`);
  if (event.wasClean) {
    console.log('Clean disconnect');
  } else {
    console.log('Connection lost — will retry');
  }
};

Close Codes

Standard WebSocket close codes: 1000 = normal, 1001 = going away, 1006 = abnormal (no close frame), 1008 = policy violation.

readyState

ws.readyState tells you the current connection state: CONNECTING (0), OPEN (1), CLOSING (2), or CLOSED (3). Always check before sending.

function sendSafely(ws, data) {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify(data));
  } else {
    console.warn('WebSocket not open, dropping message');
  }
}

Closing the Connection

Call ws.close(code, reason) to initiate a clean close. The server receives the close frame and can respond with its own.

// Normal close
ws.close(1000, 'User logged out');

// Close from a cleanup effect
return () => ws.close();

Binary Data

Set ws.binaryType = 'arraybuffer' (or 'blob') to receive binary messages. Useful for audio, images, or custom protocols.

ws.binaryType = 'arraybuffer';

ws.onmessage = (event) => {
  if (event.data instanceof ArrayBuffer) {
    const view = new Uint8Array(event.data);
    console.log('Binary message, bytes:', view.length);
  } else {
    console.log('Text message:', event.data);
  }
};

Heartbeat / Ping-Pong

The browser WebSocket API doesn't expose ping frames, but you can implement an application-level heartbeat: send a ping message every N seconds and expect a pong response.

function startHeartbeat(ws) {
  return setInterval(() => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ type: 'ping' }));
    }
  }, 30_000);
}

WebSocket vs Server-Sent Events

Use WebSocket for bidirectional communication (chat, games). Use Server-Sent Events (SSE) for server-to-client only streams (notifications, live feeds) — SSE works over plain HTTP and reconnects automatically.

Quick Check

What WebSocket readyState value indicates the connection is open and ready to send?

Recap

Create connections with new WebSocket(url), send JSON-stringified objects via ws.send(), and handle onmessage, onerror, and onclose events. Check readyState before sending, and close cleanly with ws.close(1000).

Frequently asked questions

Is the “WebSocket Fundamentals in the Browser” lesson free?

Yes — the full text of “WebSocket Fundamentals in the Browser” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “WebSocket Fundamentals in the Browser”?

Open WebSocket connections, send messages, and handle events with the native WebSocket API. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “WebSocket Fundamentals in the Browser” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. WebSocket Fundamentals in the Browser
  2. Using Socket.IO with React
  3. Building a Real-Time Chat Component
  4. Reconnection, Error Handling & Cleanup
← Back to React Academy