WebTransport: createUnidirectionalStream() 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 createUnidirectionalStream() method of the WebTransport interface opens a unidirectional stream; it returns a WritableStream object that can be used to reliably write data 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

createUnidirectionalStream();

Parameters

None.

Return value

A WritableStream object.

Exceptions

InvalidStateError DOMException

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

Examples

Use the createUnidirectionalStream() method to get a reference to a WritableStream. From this you can get a writer to allow data to be written to the stream and sent to the server.

Use the close() method of the resulting WritableStreamDefaultWriter to close the associated HTTP/3 connection. The browser tries to send all pending data before actually closing the associated connection.

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

  try {
    await writer.close();
    console.log("All data has been sent.");
  } catch (error) {
    console.error(`An error occurred: ${error}`);
  }
}

You can also use WritableStreamDefaultWriter.abort() to abruptly terminate the stream. When using abort(), the browser may discard any pending data that hasn't yet been sent.

// ...

const stream = await transport.createUnidirectionalStream();
const writer = ws.getWriter();

// ...

writer.write(...);
writer.write(...);
await writer.abort();
// Not all the data may have been written.

Specifications

Specification
WebTransport
# dom-webtransport-createunidirectionalstream

Browser compatibility

BCD tables only load in the browser

See also