The MDN WebSocket documentation is the definitive reference for the browser-native WebSocket API, covering the connection lifecycle, event handling, security requirements, and compatibility data developers need to build real-time communication features. The WebSocket API enables full-duplex, persistent connections between a browser and a server over a single TCP connection, as defined by RFC 6455. For production-grade real-time video and audio applications, developers often combine WebSocket signaling with specialized SDKs like VideoSDK to handle media transport.
When a developer needs to push live updates to a browser without polling, the MDN WebSocket page is usually the first stop. It documents the browser-native API that makes bidirectional, real-time communication possible over a single persistent connection. Unlike HTTP request-response cycles, WebSockets keep a channel open so the server can push data to the client the moment it arrives.
The MDN documentation stands out because it covers the full surface area of the WebSocket API with precision. You get the constructor signature, every property, every event, every method, and a compatibility matrix that tells you exactly which browsers support what. For developers building chat applications, live dashboards, multiplayer games, or any feature where latency matters, the MDN WebSocket reference is the canonical starting point.
By the end of this guide, you will understand the core concepts, the connection lifecycle, how to navigate the MDN documentation effectively, server-side considerations, performance tradeoffs, and the best practices that separate production-ready WebSocket implementations from fragile demos.

What is the MDN WebSocket API?

Architecture Diagram
The MDN WebSocket API is the browser-native interface for creating persistent, full-duplex communication channels between a web client and a server. The MDN WebSocket documentation on Mozilla Developer Network provides the authoritative reference for this API, including constructor parameters, instance properties, event handlers, and methods for sending and receiving data.
The WebSocket API is defined by the RFC 6455 specification and implemented natively in all modern browsers. The MDN documentation mirrors this specification while adding practical guidance, browser compatibility tables, and interactive examples that make the spec approachable. The API surface is intentionally minimal: you create a WebSocket object pointing to a server URL, attach event listeners, and send or receive messages as text or binary frames.
What makes the MDN WebSocket reference particularly valuable is that it documents not just the happy path but the edge cases. It covers the readyState constants that track connection status, the bufferedAmount property that tells you how much data is queued for transmission, and the extensions and protocol properties that reflect negotiated sub-protocols. For developers building real-time communication features, this level of detail is essential for writing robust client code that handles network instability, partial failures, and graceful shutdown.
VideoSDK builds on these same WebSocket principles for signaling and room management, then layers WebRTC media transport on top for actual audio and video streams. You can explore how VideoSDK uses real-time communication patterns in its video calling SDK documentation.

Core Concepts of WebSockets

WebSockets replace the HTTP request-response model with a persistent connection that allows both the client and server to send messages at any time after the initial handshake.

Connection Lifecycle

Every WebSocket connection moves through four defined states, tracked by the readyState property. The connection begins in the CONNECTING state (value 0) while the TCP handshake and HTTP upgrade are in progress. Once the upgrade completes successfully, the state transitions to OPEN (value 1), meaning the connection is ready for bidirectional data exchange. When either side initiates a close, the state moves to CLOSING (value 2) during the shutdown handshake. Finally, the connection enters CLOSED (value 3) when the transport is fully torn down. The MDN documentation enumerates these constants clearly, and understanding them is critical for writing event handlers that respond correctly to each phase.

Message Framing

WebSocket data travels in frames, which can carry either text or binary payloads. Text frames carry UTF-8 encoded strings, making them suitable for JSON messages, chat text, or any human-readable data. Binary frames carry raw bytes, which are used for images, audio chunks, file transfers, or any non-text data. The MDN WebSocket documentation specifies that the binaryType property on the WebSocket object controls how incoming binary data is exposed to JavaScript, defaulting to Blob but switchable to ArrayBuffer for finer-grained byte manipulation. Each frame includes an opcode that tells the receiver whether to expect text, binary, a continuation of a fragmented message, or a control frame like ping or close.

MDN Documentation Overview

The MDN WebSocket page is structured to serve both quick lookups and deep dives, with a table of contents that maps directly to the API surface.
When you land on the MDN WebSocket documentation, the page opens with a concise description of what the API does and a code example that demonstrates basic usage. The left sidebar contains a table of contents with anchor links to each major section: constructor, properties, methods, events, and examples. For developers who need to check whether a specific feature works in their target browser, the browser compatibility table near the bottom provides a color-coded matrix. The page also includes links to related interfaces like WebSocketStream and WebTransport, plus external references to the RFC 6455 specification and the WHATWG living standard.

Key Reference Sections

The constructor section documents the URL parameter (which must use the ws or wss scheme), the optional protocols parameter for sub-protocol negotiation, and the exceptions thrown for invalid URLs or unsupported protocols. The properties section covers readyState, bufferedAmount, extensions, protocol, url, and binaryType. The methods section documents send for transmitting data and close for terminating the connection with optional code and reason parameters. The events section lists open, message, error, and close, each with handler assignment patterns and event object details. The compatibility table rounds out the page with per-browser version support data, which is critical for teams that need to support older or mobile browsers.

Implementing a WebSocket Client

Building a WebSocket client involves creating the connection object, wiring up event handlers, and managing the data flow between browser and server.

Creating the WebSocket Object

To instantiate a WebSocket, you call the WebSocket constructor with a URL that uses either the ws scheme for unencrypted connections or the wss scheme for connections secured with TLS. In production, you should always use wss to protect data in transit and avoid mixed-content warnings when your page is served over HTTPS. The constructor accepts an optional second parameter for sub-protocols, which lets the client and server agree on a specific application-level protocol during the handshake. For example, a chat application might negotiate a custom JSON-based sub-protocol, while a messaging system might use a standardized protocol like STOMP. If the URL is invalid or the protocol is unsupported, the constructor throws an exception synchronously, so wrapping instantiation in error handling is a good practice.

Handling Events (Open, Message, Error, Close)

The WebSocket API exposes four primary events that a developer must handle. The open event fires when the connection transitions to the OPEN state, signaling that the client can begin sending messages. This is where you typically perform initial setup like sending authentication tokens or subscribing to channels. The message event fires whenever a frame arrives from the server, providing access to the payload through the event's data property, which can be a string, Blob, or ArrayBuffer depending on the frame type and binaryType setting. The error event fires when a connection-level error occurs, though the event object provides limited diagnostic information, which is a known limitation documented on MDN. The close event fires when the connection terminates, providing a code and reason that can help distinguish between graceful shutdowns and unexpected failures. Developers should always clean up resources and UI state in the close handler.

Managing Backpressure and Buffering

When a client sends data faster than the network can transmit it, the WebSocket API queues outgoing messages in an internal buffer. The bufferedAmount property tells you how many bytes are currently queued. Monitoring this value is essential for preventing memory bloat in high-throughput scenarios like streaming binary data or rapid chat messages. The MDN documentation notes that WebSocketStream, a newer proposal, provides a streams-based API with built-in backpressure handling, allowing developers to use readable and writable stream patterns instead of manual buffering checks. For applications where backpressure is a concern, WebSocketStream offers a more ergonomic and safer alternative to the raw WebSocket API, though browser support is still limited as of 2026.

Server-Side Considerations

The server side of a WebSocket connection involves accepting the HTTP upgrade, validating the handshake, and managing persistent connections at scale.

Handshake Process

Every WebSocket connection begins as an HTTP request. The client sends an HTTP GET request with an Upgrade header set to websocket and a Connection header set to Upgrade. The request includes a Sec-WebSocket-Key header containing a base64-encoded random value. The server responds with an HTTP 101 Switching Protocols status, echoing back a Sec-WebSocket-Accept header that is derived by concatenating the client's key with a fixed GUID defined in RFC 6455 and hashing the result with SHA-1. This handshake confirms that both sides speak the WebSocket protocol and prevents cross-protocol attacks. Once the handshake completes, the HTTP connection is upgraded to a raw TCP connection and the bidirectional message exchange begins. The MDN documentation references this process at a high level, while the RFC provides the full technical detail.

Security Headers and Validation

Server-side WebSocket security involves several layers. First, the server should validate the Origin header on the upgrade request to ensure the connection is coming from a trusted domain, preventing cross-site WebSocket hijacking. Second, if the client requests a sub-protocol, the server should negotiate and echo back the agreed protocol in the response, rejecting the connection if no acceptable protocol is offered. Third, TLS is mandatory in production environments. The wss scheme encrypts the entire WebSocket session, protecting message contents and metadata from interception. Servers should also enforce size limits on incoming frames to prevent denial-of-service attacks through oversized messages, and they should implement rate limiting on message frequency to prevent abuse.

Scaling and Load Balancing

Scaling WebSocket servers introduces challenges that HTTP applications do not face. Because WebSocket connections are persistent, a load balancer must use sticky sessions or IP hashing to ensure that subsequent frames from a client reach the same server that handled the handshake. Reverse proxies like Nginx and HAProxy support WebSocket proxying with appropriate timeout and buffer configuration. For horizontal scaling across multiple server instances, a pub/sub message broker like Redis or RabbitMQ is typically used to broadcast messages between nodes, ensuring that a message sent to one server reaches clients connected to other servers. Connection draining during deployments is also critical, as abruptly terminating active WebSocket connections degrades user experience.

Performance and Compatibility

WebSocket performance depends on browser implementation quality, network conditions, and how well the application manages data flow and connection lifecycle.

Browser Support Matrix

As of 2026, the WebSocket API is universally supported across all major browsers. Chrome, Firefox, Safari, and Edge have supported the core API since their early versions, and the MDN compatibility table confirms full support across desktop and mobile platforms. The binaryType property, sub-protocol negotiation, and the close event with codes and reasons are all broadly supported. Where support becomes fragmented is with newer additions like WebSocketStream, which is still behind flags or in limited rollout in some browsers. Developers targeting a broad audience should check the MDN compatibility table for each feature they plan to use, especially if they need to support older mobile browsers or embedded webviews that may lag behind desktop browsers in API support.

Latency, Backpressure, and When to Use WebSocketStream

Raw WebSocket connections achieve very low latency for small messages, typically in the range of a few milliseconds over a good network. However, when an application sends large volumes of data, the lack of built-in backpressure in the raw API becomes a problem. The bufferedAmount property provides visibility into the outgoing queue, but developers must manually poll it and implement their own throttling logic. WebSocketStream addresses this by exposing the connection as a pair of readable and writable streams, where backpressure is handled automatically through the streams API's flow control. If your application streams continuous data like live audio frames, sensor telemetry, or large file chunks, WebSocketStream is worth adopting where browser support allows. For simple request-response or low-frequency messaging, the raw WebSocket API remains the simpler and more compatible choice.

Choosing WebSocket vs WebTransport

WebTransport is a newer API built on HTTP/3 (QUIC) that provides multiple communication patterns: bidirectional streams, unidirectional streams, and unreliable datagrams. WebSockets, by contrast, provide a single reliable, ordered, bidirectional stream over TCP. WebTransport is a better fit when you need multiple independent streams, when you want unreliable datagram delivery for real-time gaming or live media where dropped packets are preferable to delayed ones, or when you want to leverage HTTP/3's connection migration for mobile clients switching networks. WebSockets remain the better choice when you need broad browser compatibility, a simpler programming model, or integration with existing WebSocket server infrastructure. The MDN documentation covers both APIs, and developers should evaluate their specific latency, reliability, and compatibility requirements before choosing.

Common Pitfalls and Best Practices

Production WebSocket implementations fail in predictable ways, and the MDN documentation provides the signals you need to avoid these pitfalls.

Avoiding Memory Bloat

Memory bloat in WebSocket clients typically occurs when the application sends data faster than the network can transmit it. The WebSocket API buffers outgoing data internally, and if the application never checks bufferedAmount, this buffer can grow unbounded. The best practice is to check bufferedAmount before sending large payloads and to pause transmission when the buffer exceeds a threshold you define based on your application's memory budget. For high-frequency message scenarios, consider batching small messages into larger frames to reduce per-message overhead. Additionally, always remove event listeners and null out references to the WebSocket object after the connection closes, because lingering references prevent garbage collection and can cause memory leaks in long-running single-page applications.

Properly Closing Connections

Graceful connection shutdown is one of the most commonly skipped practices in WebSocket development. The close method accepts an optional status code and a human-readable reason string, allowing the server to understand why the client is disconnecting. Developers should always call close with an appropriate code rather than simply letting the browser close the connection on page unload. One important consideration is the browser's back-forward cache (bfcache). If a page is placed in bfcache while a WebSocket connection is open, the connection may be terminated unexpectedly. To handle this, listen for the pageshow event and check the persisted property to reconnect if the page was restored from bfcache. The MDN documentation notes this interaction and recommends explicit connection management around page lifecycle events.

Enforcing Secure Wss Scheme

In production, every WebSocket connection should use the wss scheme, which wraps the WebSocket protocol in TLS. Mixing wss connections into pages served over HTTPS is required to avoid mixed-content warnings, which browsers increasingly block by default. Using plain ws on an HTTPS page will fail in modern browsers. Certificate management is also critical: the TLS certificate on the WebSocket server must be valid and trusted by the browser, or the connection will fail silently or with a cryptic error. For development, you can use self-signed certificates with local CA tools, but production requires certificates from a trusted authority. If you are terminating TLS at a reverse proxy, ensure that the proxy forwards the WebSocket upgrade headers correctly and that the connection between the proxy and the backend server is also secured or runs on a trusted network.

Visualizing WebSocket Flow

Understanding the WebSocket communication flow helps developers reason about the timing of events and the relationship between client and server. The complete lifecycle proceeds from the initial handshake through message exchange to graceful closure.
The flow begins when the browser client sends an HTTP GET request with upgrade headers to the WebSocket server. The server responds with an HTTP 101 Switching Protocols status, completing the protocol upgrade. At this point, the connection state transitions to OPEN on the client, and the open event fires, signaling that the channel is ready for data exchange. The client can now send text or binary frames to the server, which receives and processes each message. The server can similarly send text or binary frames back to the client, triggering the message event on the client side. This bidirectional exchange continues indefinitely, with both sides sending and receiving messages as needed, until either side initiates a close.
When the client calls close with a status code and reason, the close handshake begins. The server acknowledges the close request, the connection state transitions to CLOSED, and the close event fires on both the client and the server, completing the lifecycle.
This flow illustrates why event handling is central to WebSocket development. The open event is your signal that the channel is ready, the message event is your data pipeline, and the close event is your cleanup trigger. The error event, not shown in this description, can fire at any point between OPEN and CLOSED and should always be paired with a close event handler to ensure resources are released.

Real-World Use Cases

WebSockets power some of the most interactive experiences on the web, and the MDN documentation provides the foundation for building all of them.
Live chat applications are the most common WebSocket use case. Messages from one user must appear on other users' screens instantly, without polling. The MDN WebSocket reference covers the message event handling and binaryType configuration that chat apps rely on.
Collaborative editing tools, like document editors and whiteboard applications, use WebSockets to broadcast cursor positions, text changes, and shape updates in real time. The low-latency, bidirectional nature of WebSocket connections makes them ideal for these interactive scenarios.
Multiplayer browser games use WebSockets for real-time state synchronization. Where WebTransport's datagrams might be preferred for unreliable, low-latency game state updates, WebSockets remain the reliable choice for turn-based games and lobby systems.
IoT telemetry dashboards stream sensor data from devices to browser-based monitoring interfaces. The binary frame support in the WebSocket API is essential here, as sensor data is often transmitted as compact binary payloads rather than text.
For applications that need real-time video and audio communication, developers typically use WebSockets for signaling and then switch to WebRTC for media transport. VideoSDK handles this entire pipeline, from WebSocket-based room signaling to WebRTC media streams, in its video calling SDK. You can also explore interactive live streaming for one-to-many broadcast scenarios.

Definitions Glossary

WebSocket: A communication protocol providing full-duplex, persistent communication channels over a single TCP connection, standardized in RFC 6455 and exposed in browsers through the WebSocket API documented on MDN.
readyState: A read-only property on the WebSocket object that indicates the current connection state, with values 0 (CONNECTING), 1 (OPEN), 2 (CLOSING), and 3 (CLOSED).
bufferedAmount: A read-only property that returns the number of bytes of data queued for transmission but not yet sent over the network, used for backpressure management.
WebSocketStream: A newer API proposal that wraps a WebSocket connection in readable and writable streams, providing built-in backpressure handling through the streams API flow control.
WebTransport: A modern communication API built on HTTP/3 (QUIC) that supports bidirectional streams, unidirectional streams, and unreliable datagrams as alternatives to the single reliable stream model of WebSockets.
Sub-protocol: An optional application-level protocol negotiated during the WebSocket handshake, allowing client and server to agree on a message format or interaction pattern before data exchange begins.

Key Takeaways

The MDN WebSocket documentation is the canonical reference for the browser-native WebSocket API, covering the constructor, properties, methods, events, and browser compatibility data that developers need for real-time communication features.
Every WebSocket connection moves through four states (CONNECTING, OPEN, CLOSING, CLOSED), and writing correct event handlers requires understanding which state transitions trigger which events.
Production WebSocket implementations must use the wss scheme for TLS encryption, validate origins on the server side, and monitor bufferedAmount to prevent memory bloat from unbounded send buffers.
WebSocketStream offers built-in backpressure handling through the streams API and is worth adopting for high-throughput scenarios, though browser support remains limited compared to the raw WebSocket API as of 2026.
For real-time video and audio applications, WebSockets handle signaling while WebRTC handles media transport, and SDKs like VideoSDK abstract this entire pipeline into a unified developer experience.

Conclusion

The MDN WebSocket documentation remains the go-to resource for developers building real-time communication features in the browser. It covers the full API surface with the precision and authority that comes from Mozilla's stewardship of web standards documentation. Whether you are building a simple chat client or a complex collaborative editing platform, the MDN reference gives you the constructor details, event semantics, compatibility data, and edge-case notes you need to write robust client code.
Take the time to read through the MDN WebSocket page and experiment with a simple client-server demo to see the connection lifecycle in action. When you are ready to build production real-time video and audio features, explore the VideoSDK documentation to see how WebSocket signaling and WebRTC media transport come together in a single SDK. You can start for free at app.videosdk.live/login and join the VideoSDK Discord community to connect with other developers building real-time applications.
What are you building with WebSockets or VideoSDK? Drop a comment and share what kind of real-time communication use case you are working on.

Free $20 Balance for AI Voice Agents & Video Calls

FAQ