# WebSocket

> The `WebSocket` JS object opens a persistent two-way connection between the browser and a server.

## How do I use WebSocket in JavaScript?

The object that opens a persistent connection over which the browser and the server can send messages to each other at any time. Used for chats, live updates and collaboration. Unlike `fetch()`, the connection stays open after the first response.

- Topic: Fetching Data
- Type: object
- Browser support: Chrome 5+, Chrome Android 18+, Edge 12+, Firefox 11+, Firefox Android 14+, Safari 5+, Safari iOS 4.2+

## Example

Wrong:

```js
const ws = new WebSocket('wss://example.com/chat');
ws.send('hello');
```

Right:

```js
function connect() {
  const ws = new WebSocket('wss://example.com/chat');
  ws.addEventListener('open', () => ws.send('hello'));
  ws.addEventListener('close', () => setTimeout(connect, 1000));
}
connect();
```

Sending waits for the `open` event, and the socket reconnects after a delay when it closes.

## Common mistakes

- Calling `send()` right after creating the socket, before the `open` event.

## Key points

- The URL uses 'wss://' in production, not 'ws://'.
- There are handlers for `close` and `error`, and the code reconnects with a delay.
- Messages are sent only when `readyState` equals `WebSocket.OPEN`.

## Interview questions

### WebSocket vs server-sent events: which should I use?

Use server-sent events when only the server sends updates. Use WebSocket when both sides send messages often.

### Can I set custom headers on a WebSocket in the browser?

No. The browser API cannot set headers, so pass auth through cookies, the first message, or a short-lived token in the URL.

### How do I send JSON over a WebSocket?

Call `ws.send(JSON.stringify(data))`, and parse with `JSON.parse(event.data)` in the `message` handler.

## Related cards

- [WebSocket](https://wonderium.dev/web/websocket.md)
- [EventSource](https://wonderium.dev/js/event-source.md)
- [Real-Time Communication](https://wonderium.dev/web/real-time-communication.md)
- [JSON](https://wonderium.dev/js/json.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/web-socket
- Last updated: 2026-11-25
