NodeJs Stream does not stream on front end when using Cloudflare Tunnel

I’m using a Cloudflare tunnel in front of my nodejs api. I am using a react front end.

I have a post endpoint which returns a ReadableStream. On the frontend I read that stream chunk by chunk and display the text as it is read.

Here is an example endpoint which returns a large text in chunks of 5 chars. I hit this endpoint from the front end react client and display the chunks as they come.

const handler = async (req: Request): Promise<Response> => {
  let utf8Encode = new TextEncoder();
  const stream = new ReadableStream({
    start(controller) {
      const text = utf8Encode.encode('Hello World'.repeat(1000));
      const chunkSize = 5;
      let offset = 0;
  
      function enqueueChunk() {
        if (offset >= text.length) {
          controller.close();
          return;
        }
  
        const chunk = text.slice(offset, offset + chunkSize);
        controller.enqueue(chunk);
        offset += chunkSize;
        setTimeout(enqueueChunk, 50);
      }
  
      enqueueChunk();
    }
  });
  return new Response(await stream);
}

Running on local host I can see the stream load in chunks as expected.

Running with a Cloudflare tunnel the stream no longer loads in chunks. Instead it waits till the entire stream is complete before returning on the front end.

Are streams like this a Cloudflare limitation? Is there a work around to this?

1 Like