WebTransport: createBidirectionalStream() method

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The createBidirectionalStream() method of the WebTransport interface opens a bidirectional stream; it returns a WebTransportBidirectionalStream object containing readable and writable properties, which can be used to reliably read from and write to the server.

"Reliable" means that transmission and order of data are guaranteed. This provides slower delivery (albeit faster than with WebSockets) than datagrams, but is needed in situations where reliability and ordering are important, like chat applications.

Note: This feature is available in Web Workers

Syntax

createBidirectionalStream();

Parameters

None.

Return value

Exceptions

InvalidStateError DOMException

Thrown if createBidirectionalStream() is invoked while the WebTransport is closed or failed.

Examples

An initial function is used to get references to the WebTransportBidirectionalStream.readable and WebTransportBidirectionalStream.writable properties. These are references to ReadableStream and WritableStream instances, which can be used to read from and write to the server.

async function setUpBidirectional() {
  const stream = await transport.createBidirectionalStream();
  // stream is a WebTransportBidirectionalStream
  // stream.readable is a ReadableStream
  const readable = stream.readable;
  // stream.writable is a WritableStream
  const writable = stream.writable;

  ...
}

Reading from the ReadableStream can then be done as follows:

async function readData(readable) {
  const reader = readable.getReader();
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array.
    console.log(value);
  }
}

And writing to the WritableStream can be done like this:

async function writeData(writable) {
  const writer = writable.getWriter();
  const data1 = new Uint8Array([65, 66, 67]);
  const data2 = new Uint8Array([68, 69, 70]);
  writer.write(data1);
  writer.write(data2);
}

Specifications

Specification
WebTransport
# dom-webtransport-createbidirectionalstream

Browser compatibility

BCD tables only load in the browser

See also