javascriptwebsocketxmlhttprequestfetch-apistreams-api

Is it possible to implement websockets in Javascript with Streams api?


Is it possible to use the Streams API in JavaScript to implement the WebSockets protocol for a browser client (not in Node.JS)?

The built-in WebSocket class does not work for my needs because it does not support sending an HTTP header, and I need to send a specific header to the server. I have no control over the server. Here's a related SO question.

Streams API appears to leverage the Fetch API to send the initial HTTP/HTTPS request, and I think this will allow me to send the required header. My question is more specific to whether Streams API can handle the subsequent WebSocket streaming.


Solution

  • Appears that the answer is "not possible" because sending the initial upgrade request requires a GET request but fetch() does not expose the request body as a writeable stream for GET requests so you won't be able to write to the websocket. Another possible reason is that websockets upgrade request must be a http 1.1 request but it's not clear how/whether it's possible to set the http protocol version with fetch().