---
title: "WebSocketStream API"
description: "A modern WebSocket API that supports backpressure and streams. Practical notes and code examples on WebSocketStream API by."
url: "https://h3manth.com/scribe/websocketstream-api/"
canonical_url: "https://h3manth.com/scribe/websocketstream-api/"
markdown_url: "https://h3manth.com/scribe/blog/websocketstream-api.md"
publishDate: "2020-03-05T00:00:00.000Z"
author: "Hemanth HM"
category: "web"
tags: ["javascript","web-api","websocket","streams"]
word_count: 129
reading_time_minutes: 1
x_markdown_tokens: 329
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# WebSocketStream API

> A modern WebSocket API that supports backpressure and streams. Practical notes and code examples on WebSocketStream API by.

WebSocketStream API came into play to make things easier with WebSocket API, which has the below limitations:

- Ergonomics isn't great
- The important feature of `backpressure` is missing
- The `onmessage` event will keep firing until the page becomes completely unresponsive
- To find out when it is safe to start sending messages again, it is necessary to poll bufferedAmount

## Goals of WebSocketStream API

- Provide a WebSocket API that supports backpressure
- Provide a modern, ergonomic, easy-to-use WebSocket API
- Allow for future extension

*From the [explainer](https://github.com/ricea/websocketstream-explainer).*

## Sample Code

```javascript
(async () => {
  const wss = new WebSocketStream("wss://echo.websocket.org/");
  const { readable, writable } = await wss.connection;
  const reader = readable.getReader();
  
  await writable.getWriter().write("echo");
  const { value, done } = await reader.read();
  console.log(value, done);
})();
```
