Skip to content

React 18 Streaming SSR #3658

Closed as not planned
Closed as not planned

Description

@gshokanov

Hi folks,

React 18 will be rolled out in the near future and currently has an RC release that anyone can try out. I thought I would try the new streaming SSR mode with one of the projects I'm working on that uses styled-components and while working on an implementation I realised that styled-components doesn't have a compatible API yet.

Here's a link to the sandbox with the demonstration of the new streaming API by Dan Abramov. React 18 exposes a new function for rendering on the server called renderToPipeableStream. As part of it's API it exposes a pipe function that expects a target stream (typically a response stream). The existing styled-components API interleaveWithNodeStream expects a stream exposed by React which makes the whole thing incompatible with each other.

I tinkered with the whole thing a bit and the solution seems to be simple - expose a new API that wraps pipe function provided by React, returns a new function with the same API that uses the same internal Transformer stream logic used in interleaveWithNodeStream. The version I came up with looks something like this:

type PipeFn = (destination: streamInternal.Writable) => void;

export default class ServerStyleSheet {
 // existing code here...

  interleaveWithPipe(pipe: PipeFn): PipeFn {
    this._guard();
    this.seal();

    return (destination) => {
      const transformStream = this._getNodeTransformStream();

      transformStream.pipe(destination);
      pipe(transformStream);
    };
  }
}

_getNodeTransformStream creates the same stream as currently seen in interleaveWithNodeStream.

I got the whole thing working together and would be glad to contribute this as a PR, however I run into an interesting issue while working on it.

It seems that there's currently a difference in handling SSR on the main branch and on the legacy-v5 branch which I believe is the latest stable release. The difference pretty much comes down to this particular commit. React seems to be emitting rendered HTML in very small chunks, sometimes even without closing the current tag. Here's what I am talking about:

<div

data-kit
="
progress
"

role
="
progressbar
"
<!-- the rest goes on -->

Every line in the code sample above is a separate chunk emitted by React. Even attributes on tags are split between multiple chunks. Naturally this does not play well with the current implementation in main branch since ServerStyleSheet will insert a style tag after every chunk emitted by React which breaks the HTML and leads to garbage data being rendered to user. Interestingly, the implementation in legacy-v5 works since it does not insert a new style tag if there's no css that needs to be added to stream but this seems like a coincidence rather than something planned.

I wonder if it makes sense instead of copying the current logic from legacy-v5 branch to instead buffer the data emitted by React until it reaches a more reasonable size and then emit it alongside it's style tag if needed.

Would love to discuss it with someone with a deeper understanding of the codebase. I hope I got everything right, I'll happily answer any questions you may have. Any help with this one is much appreciated

Activity

  1. romeovs commented on Apr 11, 2022

    @romeovs

    Is there any plan to support this? React 18 has been released this month and I would like to be able to switch to it.

  2. karthage-spartacus commented on May 22, 2022

    @karthage-spartacus

    any news regarding react 18 ssr support ?

  3. keeganstreet commented on Jun 1, 2022

    @keeganstreet
    Contributor

    Hey @gshokanov, I'm curious to know whether your spike included using Styled Components in a delayed content block that is wrapped in Suspense? I was assuming that sheet.collectStyles would run synchronously and not be able to collect the styles for the asynchronous SSR components.

  4. adbutterfield commented on Jun 2, 2022

    @adbutterfield

    I came up with a pretty simple workaround, pipe renderToPipeableStream into a duplex stream, which you can then pass to interleaveWithNodeStream. You can see here: https://github.com/adbutterfield/fast-refresh-express/blob/react-18/server/renderToStream.ts

    Of course you don't get true streaming render though.

    Currently you get a hydration mismatch error, which I think is the same as this issue: react/react#24430

  5. switz commented on Jul 1, 2022

    @switz

    Next.js has now rolled out streaming SSR support so this is now a big blocker for folks to opt-in to that.

    https://nextjs.org/docs/advanced-features/react-18/streaming

    Here's the style upgrade guide for library authors

  6. adbutterfield commented on Jul 6, 2022

    @adbutterfield

    Maybe not ideal, but I got something working now. Might be a way to go if you want to upgrade to React 18 now, and then hopefully get all the benefits of streaming rendering sometime in the future.
    You can see this repo here: https://github.com/adbutterfield/fast-refresh-express

  7. freese commented on Sep 6, 2022

    @freese

    This is a pretty big blocker for many. In our team, we are working to upgrade to React18 and one of our main bets, to solve some remaining TTFB Issues, would be to use HTML Streaming or however you wish to call it.
    We are prevented right now, due to the lack of support by styled-components.

    Is this on the pipeline at all or not? I see the team is working actively on the beta v6, but I see no mentions at all.
    A simple yes/no answer would suffice, so we can start searching for replacement or another solution.
    Thank you for your work!

  8. beefchimi commented on Sep 13, 2022

    @beefchimi

    @freese the best that I can determine is that useInsertionPoint was added to the codebase in the v6-beta.0 release:
    https://github.com/styled-components/styled-components/releases/tag/v6.0.0-beta.0

    This hook (as I understand it) is specifically for authors of css-in-js libraries for inserting global DOM nodes (like <style />)
    https://reactjs.org/docs/hooks-reference.html#useinsertioneffect

    I take this as a sign the authors are working towards a solution. Might not be fully realized until a v7 however. I'm only guessing.

    Worth noting that React's official stance on this is:

    Our preferred solution is to use <link rel="stylesheet"> for statically extracted styles and plain inline styles for dynamic values. E.g. <div style={{...}}>. You could however build a CSS-in-JS library that extracts static rules into external files using a compiler. That's what we use at Facebook (stylex).

  9. wmertens commented on Sep 29, 2022

    @wmertens
    Contributor

    Curious how this will be solved. How about keeping a buffer of styles while components are rendering and every time there's a chance to emit a <style> tag, empty the buffer into it?

  10. gaojude commented on Oct 17, 2022

    @gaojude

    I managed to emit a style tag for each boundary component, but it was only possible by changing the ReactDOMServer code to expose a hook. Since React has made it clear in reactwg/react-18#110 that they would not support anything new upstream to accommodate this kind of CSS-in-JS problem, my solution would be a hack at this point and maybe a risky thing to be used in production.

    Based on the same doc, it speculates that there will be performance implications from the concurrent mode of React 18, even if you could solve this streaming issue.

  11. kayakyakr commented on Nov 30, 2022

    @kayakyakr

    Curious how this will be solved. How about keeping a buffer of styles while components are rendering and every time there's a chance to emit a <style> tag, empty the buffer into it?

    Looks like this PR is doing something similar to this suggestion: #3821

    Wondering if this gets us any closer to React18 SSR support. Huge blocker for us, so I'm interested to hear any contributor feedback on potential solutions.

  12. ericselkpc commented on Dec 8, 2022

    @ericselkpc

    Emotion does React 18 streaming by inserting styles in the stream https://github.com/emotion-js/emotion/blob/92be52d894c7d81d013285e9dfe90820e6b178f8/packages/react/src/emotion-element.js#L149-L153

    But it seems like Emotion doesn't support renderToPipeableStream either, otherwise it seems like emotion/styles might be a pretty simple drop-in replacement, the syntax looks identical to Styled Components.

    emotion-js/emotion#2800

    Hopefully one of these libraries is able to add support soon -- my massive React app is 50% CSS (most components have an equal amount of CSS vs JS/JSX), so the thought of migrating to something like CSS modules is keeping me up at night.

  13. wmertens commented on Dec 8, 2022

    @wmertens
    Contributor
  14. ericselkpc commented on Dec 8, 2022

    @ericselkpc

    @ericselkpc take a look at https://github.com/wmertens/styled-vanilla-extract - it's for qwik right now but adding react would not be hard.

    Thanks. We use a lot of props in our styled components that would be difficult to migrate to inline styles or other methods. Very nice work though. I love the zero runtime idea, just maybe not practical in our case where content comes from CMS and would require a new build on each change to have full SSG instead of SSR.

  15. 28 remaining items

  16. Andarist commented on May 18, 2023

    @Andarist
    Contributor

    I had a wrapper Writable that could be used with the writable response. One of the main reasons I went with this is that I wanted to support flush forwarding (the React team suggested this as being the best solution in the working group thread):

    class WritableWithStyles extends Writable {
      constructor(writable) {
        super();
        this._writable = writable;
        this._buffered = "";
        this._pendingFlush = null;
        this._inserted = false;
        this._freezing = false;
      }
      _flushBufferSync() {
        const flushed = this._buffered;
        this._buffered = "";
        this._pendingFlush = null;
    
        if (flushed) {
          this._insertInto(flushed);
        }
      }
      _flushBuffer() {
        if (!this._pendingFlush) {
          this._pendingFlush = new Promise((resolve) => {
            setTimeout(async () => {
              this._flushBufferSync();
              resolve();
            }, 0);
          });
        }
      }
      _insertInto(content) {
        // While react is flushing chunks, we don't apply insertions
        if (this._freezing) {
          this._writable.write(content);
          return;
        }
    
        const insertion = sheet.getStyleTags();
        sheet.instance.clearTag();
    
        if (this._inserted) {
          this._writable.write(insertion);
          this._writable.write(content);
          this._freezing = true;
        } else {
          const index = content.indexOf("</head>");
          if (index !== -1) {
            const insertedHeadContent =
              content.slice(0, index) + insertion + content.slice(index);
            this._writable.write(insertedHeadContent);
            this._freezing = true;
            this._inserted = true;
          }
          if (
            process.env.NODE_ENV !== "production" &&
            insertion &&
            !this._inserted
          ) {
            console.error(
              `server inserted HTML couldn't be inserted into the stream. You are missing '<head/>' element in your layout - please add it.`
            );
          }
        }
    
        if (!this._inserted) {
          this._writable.write(content);
        } else {
          queueTask(() => {
            this._freezing = false;
          });
        }
      }
      _write(chunk, encoding, callback) {
        const strChunk = chunk.toString();
        this._buffered += strChunk;
        this._flushBuffer();
        callback();
      }
      flush() {
        this._pendingFlush = null;
        this._flushBufferSync();
        if (typeof this._writable.flush === "function") {
          this._writable.flush();
        }
      }
      _final() {
        if (this._pendingFlush) {
          return this._pendingFlush.then(() => {
            this._writable.end();
          });
        }
        this._writable.end();
      }
    }

    I can't find the slightly improved version right now but:

    1. this should use TextDecoder over chunk.toString()
    2. this should handle/propagate errors from the wrapped _writable
    3. _final should use callbacks and not promises, promises were only briefly supported by node 16 or smth like that
    4. it should accept sheet in the constructor or something, this version relies on the sheet created in the closure
  17. prohabibi commented on Jun 5, 2023

    @prohabibi

    Hi @Andarist !
    Can't make it work your solution. I have this error. 😢

    Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.

    thanks!

  18. Andarist commented on Jun 5, 2023

    @Andarist
    Contributor

    This error is thrown only if you .seal() the ServerStyleSheet instance somehow (could be through interleaveWithNodeStream call). My code doesn't do any of that.

  19. LorenDorez commented on Jun 28, 2023

    @LorenDorez

    @Andarist did you ever managed to find your updated version? I wanted to give this a try in a project while we wait for React to release those 'new' APIs to make this all easier

  20. thomasjm commented on Sep 21, 2023

    @thomasjm

    Is there perhaps a place where one could follow along with the development of the new React APIs? I'd love to get some visibility into what they will look like and when they might be ready.

  21. Andarist commented on Sep 21, 2023

    @Andarist
    Contributor
  22. rurquia commented on Oct 16, 2024

    @rurquia

    I'm quite new to SSR and NodeStreams but using Node docs and styled code i finally got to this:

    const sheet: ServerStyleSheet = new ServerStyleSheet();			
    const readerWriter = new Duplex({
                          		writableObjectMode: true,
                          		readableObjectMode: true,
                          		read() {},
                          		write(chunk, encoding, callback) {
                          			this.push(chunk, encoding);
                          			callback();
                          		},
                          		final() {
                          			this.push(null);
                          		},
                          	});
    const { pipe, abort } = renderToPipeableStream(
    				<StyleSheetManager sheet={sheet.instance}>
    					<RootComponent {...rootProps} />
    				</StyleSheetManager>,
    				{
    					bootstrapModules: [getEntryURL(manifest, mapLayoutToPage(rootProps?.root?.name || ''))],
    					onShellReady() {
    						readerWriter.write(html[0]);//Document start
    						pipe(readerWriter);
    					},
    					onAllReady() {
    						readerWriter.write(html[1]);//Document end
    						readerWriter.push(null);
    					},
    					onError(x) {
    						console.error(x);
    						throw x;
    					},
    				}
    			);
    setTimeout(() => abort(), 10000);
    

    To get the styles i used a part of styled-components' interleaveWithNodeStream method's code, as the entry param is a Readable i thought that it would work well cause i have a Duplex that extends Readable, so i took the Transform and piped my Duplex:

    const transfrmStream = new Transform({
    				objectMode: true,
    				transform(
    					chunk,
    					/* encoding */
    					_: string,
    					callback: Function
    				) {
    					// Get the chunk and retrieve the sheet's CSS as an HTML chunk,
    					// then reset its rules so we get only new ones for the next chunk
    					const renderedHtml = chunk instanceof Uint8Array ? Buffer.from(chunk).toString() : chunk.toString();
    					const html = sheet._emitSheetCSS();
    					const CLOSING_TAG_R = /^\s*<\/[a-z]/i;
    
    					sheet.instance.clearTag();
    
    					// prepend style html to chunk, unless the start of the chunk is a
    					// closing tag in which case append right after that
    					if (CLOSING_TAG_R.test(renderedHtml)) {
    						const endOfClosingTag = renderedHtml.indexOf('>') + 1;
    						const before = renderedHtml.slice(0, endOfClosingTag);
    						const after = renderedHtml.slice(endOfClosingTag);
    
    						this.push(before + html + after);
    					} else {
    						this.push(html + renderedHtml);
    					}
    
    					callback();
    				},
    			});
    readerWriter.pipe(transfrmStream).pipe(response);
    

    As my dev environment uses vite.ssrLoadModule in that use case chunk's type is Uint8Array instead of string or buffer so i had tu add the objectMode config values to my Duplex and Tranform and protect the transform renderedHtml with const renderedHtml = chunk instanceof Uint8Array ? Buffer.from(chunk).toString() : chunk.toString();

    UPDATE
    As Transform is a Duplex implementation you can use the transform stream directly. There is no need of this anymore:

    const readerWriter = new Duplex({
                          		writableObjectMode: true,
                          		readableObjectMode: true,
                          		read() {},
                          		write(chunk, encoding, callback) {
                          			this.push(chunk, encoding);
                          			callback();
                          		},
                          		final() {
                          			this.push(null);
                          		},
                          	});
    

    The react API method onAllReady it's a bit tricky. If you have suspense inside your rendered component it will be executed outside the main execution thread and after onAllReady is executed. So if you want to recive that last chunks with the result of the suspense execution you will have to erase this line:

    readerWriter.push(null);
    
  23. dovigod commented on Nov 10, 2024

    @dovigod

    @rurquia can you pls share working demo??

  24. rurquia commented on Nov 16, 2024

    @rurquia

    Based in Dan Abramov's demostration shared by @gshokanov i made this:
    styled-components-ssr-3658
    there are stills some console warnings but its enough for you to get the general idea.
    My job's project works just fine.

  25. dovigod commented on Nov 17, 2024

    @dovigod

    @rurquia Thanks for sharing :)

  26. damassi commented on Nov 23, 2024

    @damassi

    Thank you for this!

    Got a chance to adapt @rurquia's example to our app and as far as I can tell it seems to work great. Suspense boundaries work on the server, styled-component styles are correctly streamed down chunk by chunk, and errors thrown in components propagate through to React's renderToPipeableStream handlers.

    The only problem I've encountered (which seems minor) is a text encoding issue.

    I keep wondering if there's some kind of catch! Is there a catch @rurquia? Nice work figuring this out.

  27. damassi commented on Nov 26, 2024

    @damassi

    For those interested, I was able to make the above example work with the very nice react-streaming lib like so (using express and a PassThrough stream):

    import { PassThrough, Transform } from "stream"
    import { renderToStream } from 'react-streaming/server'
    
    const decoder = new TextDecoder("utf-8")
    
    // Intercept stream in order to inject styled-components CSS on the fly
    const transform = new Transform({
      objectMode: true,
      flush(callback) {
        callback()
      },
      transform(chunk, encoding, callback) {
        const renderedHtml =
          chunk instanceof Uint8Array
            ? decoder.decode(chunk, { stream: true })
            : chunk.toString(encoding || "utf8")
    
        const styledCSS = sheet._emitSheetCSS()
        const CLOSING_TAG_R = /<\/[a-z]*>/i
    
        sheet.instance.clearTag()
    
        // Inject CSS into HTML
        if (/<\/head>/.test(renderedHtml)) {
          const replacedHtml = renderedHtml.replace(
            "</head>",
            `${styledCSS}</head>`
          )
          this.push(replacedHtml)
        } else if (CLOSING_TAG_R.test(renderedHtml)) {
          const execResult = CLOSING_TAG_R.exec(renderedHtml) as RegExpExecArray
          const endOfClosingTag = execResult.index + execResult[0].length
          const before = renderedHtml.slice(0, endOfClosingTag)
          const after = renderedHtml.slice(endOfClosingTag)
    
          this.push(before + styledCSS + after)
        } else {
          this.push(styledCSS + renderedHtml)
        }
    
        callback()
      },
    })
    
    const { pipe } = await renderToStream(jsx, {
      userAgent: "<some-ua>", 
    })
    
    const passThrough = new PassThrough()
    pipe(passThrough)
    
    const passThroughStream = passThrough.pipe(transform)
    passThroughStream.pipe(res) // express response
    
    transform.on("close", () => {
      res.end()
    })
  28. cesarbrie commented on Jan 4, 2026

    @cesarbrie

    Looking at Dan Abramov's example I wrote an implementation for React Router's new handleRequest function and made some improvements to it:

    • Supports streaming of the whole tag. (Won't emit styles inside head tags like <title>, where they don't work.)
    • Uses more solid regex for matching tags.
    • Will flush all styles if it encounters </html>.
    • Uses a TextDecoder instead of toString.

    It works like a charm here:

    function handleRequest(
      request: Request,
      responseStatusCode: number,
      responseHeaders: Headers,
      routerContext: EntryContext,
      loadContext: AppLoadContext,
    ) {
      // https://httpwg.org/specs/rfc9110.html#HEAD
      if (request.method.toUpperCase() === 'HEAD') {
        return new Response(null, {
          status: responseStatusCode,
          headers: responseHeaders,
        })
      }
    
      return new Promise((resolve, reject) => {
        let shellRendered = false
        let userAgent = request.headers.get('user-agent')
    
        // Ensure requests from bots and SPA Mode renders wait for all content to load before responding
        // https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation
        let readyOption: keyof RenderToPipeableStreamOptions =
          (userAgent && isbot(userAgent)) || routerContext.isSpaMode ? 'onAllReady' : 'onShellReady'
    
        // Abort the rendering stream after the `streamTimeout` so it has time to
        // flush down the rejected boundaries
        let timeoutId: ReturnType<typeof setTimeout> | undefined = setTimeout(() => abort(), streamTimeout + 1000)
    
        // styled-components support for SSR + streaming
        const sheet = new ServerStyleSheet()
        let closingHeadTagReached = false
        let pendingStyleTags: string[] = []
        const textDecoder = new TextDecoder()
        const insertStylesTransform = new Transform({
          objectMode: true,
          transform(chunk, encoding, callback) {
            const styleTag = sheet._emitSheetCSS()
            if (styleTag) pendingStyleTags.push(styleTag)
            sheet.instance.clearTag()
    
            const renderedHtml: string = chunk instanceof Uint8Array ? textDecoder.decode(chunk, { stream: true }) : chunk
    
            const HEAD_CLOSE_REGEX = /<\/\s*head\s*>/i
            if (HEAD_CLOSE_REGEX.test(renderedHtml)) closingHeadTagReached = true
    
            if (!closingHeadTagReached) {
              callback(null, chunk)
              return
            }
    
            if (!pendingStyleTags.length) {
              callback(null, chunk)
              return
            }
    
            const CLOSING_TAG_REGEX = /<\/\s*[a-z][a-z0-9\-_.]*\s*>/i
            const getConcatenatedTags = () => {
              const concatenatedTags = pendingStyleTags.join('')
              pendingStyleTags = []
              return concatenatedTags
            }
    
            // If closing head tag found, prepend styles tag
            if (HEAD_CLOSE_REGEX.test(renderedHtml)) {
              const replacedHtml = renderedHtml.replace(HEAD_CLOSE_REGEX, `${getConcatenatedTags()}</head>`)
              this.push(replacedHtml)
              callback()
              return
            }
    
            // If closing HTML tag found, flush it all before tag
            const HTML_CLOSE_REGEX = /<\/\s*html\s*>/i
            if (HTML_CLOSE_REGEX.test(renderedHtml)) {
              const replacedHtml = renderedHtml.replace(HTML_CLOSE_REGEX, `${getConcatenatedTags()}</html>`)
              this.push(replacedHtml)
              callback()
              return
            }
    
            // If any other closing tag found, append after closing tag
            if (CLOSING_TAG_REGEX.test(renderedHtml)) {
              const execResult = CLOSING_TAG_REGEX.exec(renderedHtml)
              const endOfClosingTag = execResult!.index + execResult!.flat().length - 1
              const before = renderedHtml.slice(0, endOfClosingTag)
              const after = renderedHtml.slice(endOfClosingTag)
              this.push(before + getConcatenatedTags() + after)
              callback()
              return
            }
    
            // Otherwise, emit chunk
            callback(null, chunk)
          },
        })
    
        const { pipe, abort } = renderToPipeableStream(
          <StyleSheetManager sheet={sheet.instance}>
            <ServerRouter context={routerContext} url={request.url} />
          </StyleSheetManager>,
          {
            [readyOption]() {
              shellRendered = true
              const body = new PassThrough({
                final(callback) {
                  // Clear the timeout to prevent retaining the closure and memory leak
                  clearTimeout(timeoutId)
                  timeoutId = undefined
                  sheet.seal()
                  pendingStyleTags = []
                  callback()
                },
              })
              const stream = createReadableStreamFromReadable(body)
    
              responseHeaders.set('Content-Type', 'text/html')
    
              insertStylesTransform.pipe(body)
              pipe(insertStylesTransform)
    
              resolve(
                new Response(stream, {
                  headers: responseHeaders,
                  status: responseStatusCode,
                }),
              )
            },
            onShellError(error: unknown) {
              reject(error)
              sheet.seal()
            },
            onError(error: unknown) {
              responseStatusCode = 500
              // Log streaming rendering errors from inside the shell.  Don't log
              // errors encountered during initial shell rendering since they'll
              // reject and get logged in handleDocumentRequest.
              if (shellRendered) {
                console.error(error)
              }
              sheet.seal()
            },
          },
        )
      })
    }

    Hopefully this will save someone some time!

  29. quantizor commented on Mar 19, 2026

    @quantizor
    Contributor

    Closing — this issue is stale (2+ years without resolution) and relates to an older version or has been superseded by v6.x changes. If this is still reproducible on the latest v6.x release, please open a new issue with a minimal reproduction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    6.0help wanted 🆘

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions