Get to know MDN better
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
Note: This feature is available in Web Workers.
Non-standard: This feature is not standardized. We do not recommend using non-standard features in production, as they have limited browser support, and may change or be removed. However, they can be a suitable alternative in specific cases where no standard option exists.
The WebSocketStream() constructor creates a new WebSocketStream object instance.
A string representing the URL of the WebSocket server you want to connect to with this WebSocketStream instance. Allowed URL schemes are "ws", "wss", "http", and "https".
options OptionalAn object that can contain the following properties:
protocols OptionalA single string or an array of strings representing the sub-protocol(s) that the client would like to use, for example "amqp" or "mqtt". Subprotocols may be selected from the IANA WebSocket Subprotocol Name Registry or may be custom names jointly understood by the client and the server. A single server can implement multiple WebSocket sub-protocols, and handle different types of interactions depending on the specified value. If it is omitted, an empty array is used by default. If protocols is included, the connection will only be established if the server reports that it has selected one of these sub-protocols.
signal OptionalAn AbortSignal, which can be used to abort the connection before the handshake has completed (that is, before the opened promise resolves). This is primarily intended to help implement connection timeouts. As such, it does nothing after the connection is established.
Thrown if the URL scheme is not one of "ws", "wss", "http", or "https".
The most basic example takes the URL of a WebSocket server as an argument:
The following example uses the signal option to implement a timeout if the connection is not established within 5 seconds:
Note that if you're connecting to localhost, it's likely to succeed or fail before the connection attempt times out.
Once the connection is established, signal has no effect: to close a connection that's already established, call the WebSocketStream.close() method. Closing the underlying WritableStream or WritableStreamDefaultWriter also closes the socket.
See Using WebSocketStream to write a client for a complete example with full explanation.
Not currently a part of any specification. See https://github.com/whatwg/websockets/pull/48 for standardization progress.
Enable JavaScript to view this browser compatibility table.
This page was last modified on May 9, 2026 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.