0Pricing
Frontend Academy · Lesson

WebSocket API: open message close error

Create a WebSocket connection, send and receive messages in the message event handler, and handle connection errors and clean closure.

WebSocket API: open message close error is a free Frontend 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 Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why WebSockets?

HTTP is request/response. For real-time apps (chat, multiplayer games, live updates), you need persistent two-way communication. WebSockets give you a single TCP connection that stays open and lets both sides send messages at any time.

Creating a WebSocket

Construct a WebSocket with a ws:// or wss:// URL. The browser handles the upgrade handshake.

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

// Always use wss:// (secure) in production

The Four Events

WebSocket has four event types: open (connected), message (data received), close (connection ended), error (problem).

ws.addEventListener('open', () => {
  console.log('Connected');
  ws.send(JSON.stringify({ type: 'subscribe', channel: 'updates' }));
});

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

ws.addEventListener('close', (event) => {
  console.log('Closed:', event.code, event.reason);
});

ws.addEventListener('error', (event) => {
  console.error('Error:', event);
});

Sending Messages

Use ws.send(). It accepts strings, ArrayBuffers, Blobs, or ArrayBufferView. For structured data, JSON.stringify first.

ws.send('hello');
ws.send(JSON.stringify({ type: 'chat', text: 'Hi' }));

// Binary:
const buffer = new ArrayBuffer(8);
ws.send(buffer);

Receiving Messages

Inspect event.data — its type matches what the server sent. JSON.parse for object payloads.

ws.addEventListener('message', (event) => {
  // typeof event.data: string | ArrayBuffer | Blob
  if (typeof event.data === 'string') {
    const msg = JSON.parse(event.data);
    handleMessage(msg);
  }
});

Connection State (readyState)

Check ws.readyState: CONNECTING=0, OPEN=1, CLOSING=2, CLOSED=3. Don't send before OPEN.

if (ws.readyState === WebSocket.OPEN) {
  ws.send(message);
} else {
  console.warn('Not connected yet');
}

Closing Cleanly

Call ws.close(code, reason). Standard close codes: 1000 (normal), 1001 (going away), 1008 (policy violation), 1011 (server error).

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

Reconnection Strategy

WebSockets disconnect on network changes, server restarts, etc. Implement reconnect with exponential backoff.

let reconnectDelay = 1000;

function connect() {
  const ws = new WebSocket('wss://api/realtime');
  ws.addEventListener('open', () => { reconnectDelay = 1000; });
  ws.addEventListener('close', () => {
    setTimeout(connect, reconnectDelay);
    reconnectDelay = Math.min(reconnectDelay * 2, 30000);
  });
  return ws;
}

Heartbeats / Keepalive

Idle WebSockets get killed by proxies and load balancers after ~60s. Send a ping every 25-30 seconds to keep the connection alive.

let pingInterval;
ws.addEventListener('open', () => {
  pingInterval = setInterval(() => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ type: 'ping' }));
    }
  }, 25000);
});
ws.addEventListener('close', () => clearInterval(pingInterval));

Authentication

WebSockets don't support custom headers. Options: 1) Auth via query string token (?token=jwt) on the WS URL. 2) Send an auth message after open. 3) Use a cookie (works automatically for same-origin).

// Query string:
const ws = new WebSocket(`wss://api/realtime?token=${jwt}`);

// Auth message:
ws.addEventListener('open', () => {
  ws.send(JSON.stringify({ type: 'auth', token: jwt }));
});

React Hook for WebSockets

Encapsulate WS lifecycle in a custom hook to avoid leaking connections.

function useWebSocket(url) {
  const [messages, setMessages] = useState([]);
  const wsRef = useRef(null);

  useEffect(() => {
    const ws = new WebSocket(url);
    wsRef.current = ws;
    ws.addEventListener('message', (e) => {
      setMessages(m => [...m, JSON.parse(e.data)]);
    });
    return () => ws.close();
  }, [url]);

  return { messages, send: (msg) => wsRef.current?.send(JSON.stringify(msg)) };
}

WebSocket vs HTTP/2 vs SSE

WebSocket: full duplex, both sides send. HTTP/2 server push: deprecated. Server-Sent Events: server-to-client only, simpler, auto-reconnect. Choose WS when client needs to send too (chat); SSE for one-way notifications.

Quick Check

What's the standard WebSocket close code for a normal, intentional close (e.g. user logged out)?

Recap: WebSocket API

new WebSocket('wss://...') opens the connection. Four events: open, message, close, error. send() accepts string/ArrayBuffer/Blob; JSON.stringify for objects. Check readyState before sending. close(1000) for clean close. Reconnect with exponential backoff. Heartbeat every 25s to keep alive. Auth via query string or auth message. Wrap in a hook for React.

Frequently asked questions

Is the “WebSocket API: open message close error” lesson free?

Yes — the full text of “WebSocket API: open message close error” is free to read here on the web, and the Frontend 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 Frontend Academy course, upgrade to CoddyKit PRO.

What will I learn in “WebSocket API: open message close error”?

Create a WebSocket connection, send and receive messages in the message event handler, and handle connection errors and clean closure. You practise Frontend 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 Frontend Academy?

No prior experience is required. Frontend 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 API: open message close error” 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 Frontend Academy lesson?

Yes. Every Frontend 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 API: open message close error
  2. Socket.io Client Integration
  3. Server-Sent Events for One-Way Streaming
  4. Real-time UI Patterns
← Back to Frontend Academy