#How to use RenderToReadableStream with the bun init React project?

1 messages · Page 1 of 1 (latest)

violet pelican
#

I am trying to transform the basic bun react template (with Wouter as an addition) to use renderToReadableStream.

So far I managed to get just rendering the <App> component working:

"/*": async (req) => {
      const url = new URL(req.url);
      const stream= await renderToReadableStream(
        <Router ssrPath={url.pathname} ssrSearch={url.search}>
          <App />
        </Router>
      );
      
      return new Response(stream, {
        headers: { "Content-Type": "text/html" }
      });
    },```

But I don't really know how to place it inside Index.html, which has the frontend.tsx and should receive the imported .css file from <App> and still have it be transpiled by bun?

I guess I could just add the raw html to the Response (which would mean I would need to build first) and add the stream in, but I'd ideally keep buns automatic bundling/transpilation magic
old token
#

if your doing the new Response manually, then you can't take advantage of the full stack server right now

#

so that means you'll have to do the css bundling as a separate task and then make a route

violet pelican
#

@old token is there a way to not do it manually? :3 noob here. this sort of works, except that the chunks are not loaded in the browser.

      const baseHtml = await Bun.file("./out/index.html").text();
      const [htmlStart, htmlEnd] = baseHtml.split('<div id="root"></div>');
      console.log(baseHtml);
      const url = new URL(req.url);   
      const reactStream = await renderToReadableStream(
        <Router ssrPath={url.pathname} ssrSearch={url.search}>
          <App />
        </Router>
      );
            // Manually construct the full HTML response
      const { readable, writable } = new TransformStream();
      const writer = writable.getWriter();
      const encoder = new TextEncoder();

      (async () => {
        // 1. Write HTML start
        await writer.write(encoder.encode(htmlStart));
        await writer.write(encoder.encode('<div id="root">'));

        // 2. Stream React content
        const reader = reactStream.getReader();
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          await writer.write(value);
        }

        // 3. Write HTML end
        await writer.write(encoder.encode('</div>'));
        await writer.write(encoder.encode(htmlEnd));
        await writer.close();
      })().catch(err => {
        console.error("Stream error:", err);
        writer.abort(err);
      });

      return new Response(readable, {
        headers: { }
      });
    },"```
old token