The WebTransport interface of the WebTransport API provides functionality to enable a user agent to connect to an HTTP/3 server, initiate reliable and unreliable transport in either or both directions, and close the connection once it is no longer needed.
The example code below shows how you'd connect to an HTTP/3 server by passing its URL to the WebTransport() constructor. Note that the scheme needs to be HTTPS, and the port number needs to be explicitly specified. Once the WebTransport.ready promise fulfills, you can start using the connection.
async function initTransport(url) {
const transport = new WebTransport(url);
await transport.ready;
return transport;
}
You can respond to the connection closing by waiting for the WebTransport.closed promise to fulfill. Errors returned by WebTransport operations are of type WebTransportError, and contain additional data on top of the standard DOMException set.
The closeTransport() method below shows a possible implementation. Within a try...catch block it uses await to wait for the closed promise to fulfill or reject, and then reports whether or not the connection closed intentionally or due to error.
async function closeTransport(transport) {
try {
await transport.closed;
console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
} catch (error) {
console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
}
}
We might call the asynchronous functions above in their own asynchronous function, as shown below.
async function useTransport(url) {
const transport = await initTransport(url);
await closeTransport(transport);
}
const url = "https://example.com:4999/wt";
useTransport(url);
For other example code, see the individual property and method pages.