iTranslated by AI
Building a Chat App with Fetch Upload Streaming
What is Fetch Upload Streaming
Fetch Upload Streaming is a feature that allows HTTP streaming in browser JavaScript POST requests. More specifically, it allows you to pass Streams API objects like ReadableStream or WritableStream to the body of the Fetch API.
const stream = new ReadableStream({})
fetch(`/send?room=${roomId}`, {
method: "POST",
body: stream,
duplex: "half",
});
Previously, while the Fetch API could receive responses as a ReadableStream, it was not possible to pass a ReadableStream to the body during a request. Fetch Upload Streaming is enabled starting from Chrome 105.
Using Fetch Upload Streaming, real-time data exchange similar to WebSockets becomes possible using only the Fetch API. In this article, we will create a real-time chat application using the Fetch API.

Refer to the following for the code details.
Client-side
First, let's look at the client-side code. The client-side code is created under the static folder. First, we use document.querySelector to get DOM elements to capture input values and form submit events. Since it's a chat app, we also need a roomId. The roomId is obtained from the query parameters; if it doesn't exist, an alert is shown and the process terminates.
const input = document.querySelector("#input");
const form = document.querySelector("#form");
const messages = document.querySelector("#messages");
const quit = document.querySelector("#quit");
const roomId = new URLSearchParams(window.location.search).get("roomId");
if (!roomId) {
alert("No roomId given");
return;
}
Uploading a Stream
To upload a stream, create a ReadableStream instance. Use the start method of the ReadableStream() constructor to generate the stream.
const stream = new ReadableStream({
start(controller) {
// When the form is submitted
form.addEventListener("submit", (event) => {
event.preventDefault();
const message = input.value;
input.value = "";
controller.enqueue(message); // Add string to the stream
});
quit.addEventListener("click", () => controller.close());
},
}).pipeThrough(new TextEncoderStream());
When the form is submitted, the input value is obtained. The string is added to the stream using the controller.enqueue method. To stop the generation of the stream, call controller.close(). This is set to be called when the "quit" button is clicked.
The stream is eventually converted into another format using ReadableStream.pipeThrough(). Here, the string stream is converted into bytes using UTF-8 encoding by TextEncoderStream().
The created ReadableStream instance is set as the body parameter for fetch.
fetch(`/send?room=${roomId}`, {
method: "POST",
headers: { "Content-Type": "text/plain" },
body: stream,
duplex: "half",
});
To use streams, you must set duplex: "half". In HTTP features, there is a concept of "whether you can start receiving a response while sending a request". duplex: "half" means the response cannot be received until the request body is fully sent. This is the default pattern for browsers.
However, implementations such as Deno's Fetch default to duplex: "full", where the response becomes available while the request is still completing.
To avoid such compatibility issues, you must always set duplex: "half" on the request.
Reading the Stream
Fetch API obtains res.body as a ReadableStream.
fetch(`/receive?room=${roomId}`).then(async (res) => {
// Attach a reader to read the stream
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
// Get chunks until the stream is closed
while (true) {
const { done, value } = await reader.read();
if (done) return;
const newMessage = document.createElement("li");
messages.appendChild(newMessage);
newMessage.innerText = value
}
});
To read the stream, you need to attach a reader. First, res.body.pipeThrough(new TextDecoderStream()) decodes the byte stream into strings using UTF-8 encoding. A reader is created for the converted data by calling getReader(), which locks the stream. No other reader can read from this stream until this reader is released.
Once the reader is attached, you can read chunks from the stream using the ReadableStreamDefaultReader.read() method. Chunks are obtained from the value property. If done returns true, it means the stream has been closed.
By creating an li element based on the obtained chunk and adding it to the DOM, you can display the received message.
Determining if Fetch Upload Streaming is Enabled
To determine if the browser supports Fetch Upload Streaming, we use a slightly unusual piece of code.
const supportsRequestStreams = (() => {
let duplexAccessed = false;
const hasContentType = new Request('', {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
},
}).headers.has('Content-Type');
return duplexAccessed && !hasContentType;
})();
if (!supportsRequestStreams) {
// …
}
If the browser does not support Fetch Upload Streaming, the toString() method of the ReadableStream instance will be called when it is passed to the body. As a result, the body is assigned the string value '[object ReadableStream]'. When a string type is passed to the body, a Content-Type header of text/plain;charset=UTF-8 is automatically set. In other words, if the Content-Type header is set (headers.has('Content-Type') is true), we can determine that the browser does not support Fetch Upload Streaming.
Safari is a bit tricky; although it supports specifying a stream in the body, it is not permitted for use within the Fetch API. Therefore, we determine support based on whether the duplex option, which Safari currently does not support, is enabled.
HTML
The HTML code is simple, so it shouldn't need much explanation.
<h1>Chat via fetch upload streaming</h1>
<form id="form">
<input type="text" id="input" placeholder="Message">
<button type="submit" id="send">Send</button>
</form>
<ul id="messages"></ul>
<button id="quit">Quit</button>
Server-side
Fetch Upload Streaming has limitations, and attempting to use it over HTTP/1.x will fail with an ERR_H2_OR_QUIC_REQUIRED error. This is because, under HTTP/1.1 rules, request and response bodies must either send a Content-Length header to inform the recipient of the amount of data being sent, or the message format must be changed to use chunked encoding.
In other words, the server-side code must be implemented using HTTP/2 or HTTP/3.
Project Setup
The server-side code will be implemented using Express. spdy is a module for implementing HTTP/2 servers in Node.js.
npm init -y
npm install express spdy
To use spdy, a server certificate is required, so we will create one using the openssl command.
openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
Add a command to start the server to package.json.
{
"scripts": {
"start": "node server.js"
},
}
Implementing the Server Code
Create a server.js file and implement the code as follows.
import express from "express";
import spdy from "spdy";
import fs from "fs";
const app = express();
const receivers = new Map();
app.post("/send", (req, res) => {
const room = req.query.room;
if (!room) {
res.status(400).send("No room given");
return;
}
res.status(200);
req.on("data", (chunk) => {
const set = receivers.get(room);
if (!set) return;
for (const res of set) res.write(chunk);
});
req.on("end", (chunk) => {
if (res.writableEnded) return;
res.send("Ended");
});
});
app.get("/receive", (req, res) => {
const room = req.query.room;
if (!room) {
res.status(400).send("No room given");
return;
}
if (!receivers.has(room)) {
receivers.set(room, new Set());
}
receivers.get(room).add(res);
res.on("close", () => {
const set = receivers.get(room);
set.delete(res);
if (set.size === 0) receivers.delete(room);
});
res.status(200);
res.set("Content-Type", "text/plain");
});
app.use(express.static("static"));
const port = process.env.PORT || 3000;
spdy
.createServer(
{
key: fs.readFileSync("./server.key"),
cert: fs.readFileSync("./server.crt"),
},
app
)
.listen(port, (err) => {
if (err) {
console.error(err);
return;
}
console.log(`Listening on port ${port}`);
});
Sending Requests
First, let's look at the code for the /send path, which sends requests. It retrieves the room ID from the query parameters.
const room = req.query.room;
if (!room) {
res.status(400).send("No room given");
return;
}
res.status(200);
Subscribe to stream data events with req.on("data"). If the connection is closed by the client via controller.close(), the req.on("end") event is called.
When stream data is received, the received chunk data is sent to the res object of the corresponding /receive path using the room ID from the receivers Map object.
req.on("data", (chunk) => {
const set = receivers.get(room);
if (!set) return;
for (const res of set) res.write(chunk);
});
req.on("end", (chunk) => {
if (res.writableEnded) return;
res.send("Ended");
});
Receiving Requests
Connect to the /receive path from the client to receive requests. Similar to the /send path, it retrieves the room ID from the query parameters.
const room = req.query.room;
if (!room) {
res.status(400).send("No room given");
return;
}
Set the res object into the corresponding room ID of the receivers Map object. The res object will be used to send chunk data from the /send path.
if (!receivers.has(room)) {
receivers.set(room, new Set());
}
receivers.get(room).add(res);
Creating an HTTP/2 Server
Finally, create an HTTP/2 server using the spdy module. In the createServer method, set the server certificate created during project setup and the Express app object. Then, specify port 3000 in the listen method.
spdy
.createServer(
{
key: fs.readFileSync("./server.key"),
cert: fs.readFileSync("./server.crt"),
},
app
)
.listen(port, (err) => {
if (err) {
console.error(err);
return;
}
console.log(`Listening on port ${port}`);
});
Final Thoughts
What we are doing here is almost identical to what can be achieved with WebSockets, but it is great that this can be implemented using only HTTP technologies. Setting up a dedicated WebSocket server can be quite a hassle, after all.
References
- Streaming requests with the fetch API
- Is fetch() upload streaming a viable alternative to WebSockets? Sending video from a camera via streaming with Fetch (Japanese)
- HTTP Streaming Upload, which enables unidirectional real-time communication using pure HTTP on web browsers, is finally arriving (Japanese)
- Getting Started with HTTP/2 in Node.js
Discussion