Does fetch automatically read stream data only after all chunks have been received and not immediately upon receiving each chunk?

When handling a stream response with a content-type of text/event-stream using fetch, reader, and decoder, it seems that the reader only returns after all chunks are received. I expected the reader to return as soon as each chunk is received. Am I approaching the stream response handling incorrectly?

const sseController = new AbortController();
fetch(url, {
    method: 'POST',
    mode: 'cors',
    credentials: 'include',
    headers: {
        Accept: 'text/event-stream,application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        ...params,
    }),
    signal: sseController.signal,
}).then(async (response) => {
    console.log('sselog::: open', new Date());
    if (!response.ok || !response.body) {
        // TODO onerror
        return;
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');

    while (true) {
        const { done, value } = await reader?.read();
        console.log('sselog::: while', value);
        const str = new TextDecoder().decode(value);
        // TODO onmessage
        if (done) {
            return;
        }
    }
});

The sselog::: while output shows only one iteration, but in reality, the backend received two messages with types major and message. https://i.sstatic.net/n6jZD.png

https://i.sstatic.net/0R8J8.jpg

Answer №1

It seems like the issue lies not in your fetch code, but rather with the backend system. Your HTTP server should avoid buffering and send data promptly.

Check out this test using chunked fetch:
Showing text from stream XHR response bit by bit

Answer №2

I have finally found the solution. Disable server compression.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular - Enhance ngFor index while filtering

I am currently working with a list that utilizes an *ngFor loop in the template: <li *ngFor="let product of products | filterProducts: selectedFilter; index as productId"> <a [routerLink]="['/product', productId]"> {{produc ...

Switch out the icons within a return statement in JavaScript

Help! I have 5 empty star icons (<StarBorderIcon/>) displayed for a product on the material-ui website. I need to replace them with filled star icons (<StarIcon/>) based on the rating entered into a function. I attempted to use replace(), but i ...

What is the process for setting up nested routes using React router?

I have multiple layouts that need to display different screens. Each layout has its own header, footer, and other shared elements similar pages should have. Below is the code I have created: <BrowserRouter> <Route path={['/index', &ap ...

Version 1 of Vue.js is not compatible with Ajax-loaded HTML files

Currently, I am encountering a minor issue with loading content through ajax requests. I am in the process of developing a web application where everything is located on one page without any reloading. To achieve this, I have split the content into separa ...

Using Javascript to create a new regular expression, we can now read patterns in from

I am currently working on developing a bbcode filtering solution that is compatible with both PHP and JavaScript. Primarily focusing on the JavaScript aspect at the moment, I have encountered an issue with the new RegExp constructor not recognizing pattern ...

Live notification application using node.js

I am looking to create a recipe maker webapp for practice purposes. This webapp will consist of 2 main pages: the index page and the recipes page. On the "index" page, users can create their own recipes. On the "recipes" page, users can view a table ...

Working with Vue.js: Binding to dynamically generated form elements

I am facing an issue where form elements are not available in the html document until an inline script runs on page load. In Vue.js, how can I bind to these form elements after the page loads? While with jQuery I could use a $('.element').each(), ...

Tips for optimizing images for mobile screens and ensuring responsiveness

I'm trying to ensure that my image only loads on mobile screens and remains responsive so it doesn't stretch. However, the code I've written isn't working as expected. Currently, the image takes up the whole browser window and appears o ...

Guide to dynamically resizing the Monaco editor component using react-monaco-editor

Currently, I am integrating the react-monaco-editor library into a react application for viewing documents. The code snippet below showcases how I have set specific dimensions for height and width: import MonacoEditor from 'react-monaco-editor'; ...

Accessing elements within a gridview

My gridview is connected to an objectdatasource and contains a bound textbox for input in each row. Next to the textbox, there is a button that triggers a javascript popup for unit conversion. I am wondering: how can I specify to the unit converter (Ja ...

The fetch function consistently executes the then() block, regardless of any errors, resulting in an undefined response

I'm encountering an issue where the catch block doesn't seem to be firing in my code, even though I am throwing a new error. However, the then block with an undefined response always fires. Can anyone help me understand why this is happening? Ca ...

Which is better: specifying a name in window.open() or using replace?

If the current window is www.myparent.com and a button labeled "a" is clicked, it triggers the following function window.open('children','same','',??). Subsequently, a new page will open as www.myparent.com/children. On the o ...

A pause of 5 seconds between every request in Node.js

Need Help with Delays in Node.js Request Queue I am facing an issue with my code that involves looping through more than 500,000 records in a database and requesting information from another server. I have managed to write all the necessary functions, but ...

How does Sizzle JS function?

While investigating the sizzle.js source code for a project, I stumbled upon an interesting discovery. Towards the end of the code, there is a line that reads: window.Sizzle = Sizzle; However, there doesn't seem to be any declaration of a variable n ...

When using React Router, redirect to a new page by pushing into the browser's history

Is it feasible to utilize <link> for the purpose of <Link to="route" target="_blank"> in order to open links in a new tab? However, can we also employ browserHistory.push to achieve the same outcome? ...

React.js Component Composition Problem

I am attempting to replicate the following straightforward HTML code within a React environment: Traditional HTML <div> Hello <div>child</div> <div>child</div> <div>child</div> </div> React(working ...

The database powered by Postgresql performs flawlessly when it comes to updating data with accurate code execution. However, there seems to be an

Imagine a zoo with a postgresql database. To enable web access to this database, I am using php and javascript. Most of the web pages are working fine, but I am currently working on a page where clients can add or remove animals from existing exhibits. T ...

React Material-UI Table - Universal and Group-Wide Application

I want to implement the functionality of "Apply To All" and "Apply to GroupBy" for the rows I'm working with using Material UI. I need to create a button for "Apply to All". This button will update all the columns on a row when the user makes chang ...

When a table row is selected, set the OnClick attribute of an input to the value of the TD cell in that row based on

I'm really struggling with this. So, here's the issue - I have a table where rows get assigned a class (selected) when clicked on. Now, there's an input inside a form that needs to redirect to another page when clicked, and it also needs t ...

Testing for expressjs 4 using Mocha revealed unexpected behavior when attempting to spy on a function called within a promise. Despite setting up the

I have encountered a situation with some test cases structured like this: it('does stuff', function(done) { somePromise.then(function () { expect(someSpy).to.have.been.called done() }) }) When the assertion in a test case fails, it ...