feat(unstable): WebSocket headers field (#30321)

This changes the second argument in the WebSocket constructor to be able
to take an object, which can contain a headers field with which the
headers for the connection can be set.

---------

Co-authored-by: Luca Casonato <hello@lcas.dev>
This commit is contained in:
Leo Kettmeir 2025-08-28 11:44:59 +02:00 committed by GitHub
parent b88c621f22
commit c217928649
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 148 additions and 23 deletions

View file

@ -267,6 +267,13 @@ interface WebSocket extends EventTarget {
* // Using URL object instead of string
* const url = new URL("ws://localhost:8080/path");
* const wsWithUrl = new WebSocket(url);
*
* // WebSocket with headers
* const wsWithProtocols = new WebSocket("ws://localhost:8080", {
* headers: {
* "Authorization": "Bearer foo",
* },
* });
* ```
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket
@ -274,13 +281,34 @@ interface WebSocket extends EventTarget {
*/
declare var WebSocket: {
readonly prototype: WebSocket;
new (url: string | URL, protocols?: string | string[]): WebSocket;
new (
url: string | URL,
protocolsOrOptions?: string | string[] | WebSocketOptions,
): WebSocket;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
};
/**
* Options for a WebSocket instance.
* This feature is non-standard.
*
* @category WebSockets
*/
interface WebSocketOptions {
/**
* The sub-protocol(s) that the client would like to use, in order of preference.
*/
protocols?: string | string[];
/**
* A Headers object, an object literal, or an array of two-item arrays to set handshake's headers.
* This feature is non-standard.
*/
headers?: HeadersInit;
}
/**
* Specifies the type of binary data being received over a `WebSocket` connection.
*