Chunks in web streams are fundamental data units that can be of many different types depending on the content, such as String for text or Uint8Array for binary files. While standard Function responses contain full payloads of data processed on the server, streamed responses typically send data in chunks over time.
To do this, you create a ReadableStream and add a data source, then transform the stream's data chunks before they're read by the client. Finally, you write stream the data chunk by chunk as a Function response.
Jump to the full example to see the finished recipe.
Create a ReadableStream and add a data source. In this case, you'll create your own data by encoding text with TextEncoder:
You then need to transform the stream's data chunks before they're read by the client. First, you'll decode the chunks with TextDecoder, then transform the text to uppercase before encoding the text again:
Finally, write stream the data chunk by chunk as a Function response:
The final file will look like this:
If you're not using a framework, you must either add "type": "module" to your package.json or change your JavaScript Functions' file extensions from .js to .mjs
Build your app and visit localhost:3000/api/chunk-example. You should see the text "STREAM ME!" in the browser.
Run your app locally and visit localhost:3000/api/data-chunks. You should see the text "STREAM ME!" in the browser.
See understanding chunks to learn more.