6

I'm trying to do SSR with ReactDOMServer.renderToNodeStream(element) but just wanted to know if there would be any problem with using both ReactDOMServer.renderToString(element) and ReactDOMServer.renderToNodeStream(element) at each request?

What I have in my custom SSR setup is: * React 16 * react-loadable * styled-components v4 * react-helmet-async * Redux * Express JS

Previously with React, I could easily render a HTML document by first rendering the <head></head> tags that contains markup produced by react-helmet and then using ReactDOMServer.renderToString() to render my React elements.

However, by switching to ReactDOMServer.renderToNodeStream() I had to switch react-helmet for react-helmet-async, which supports renderToNodeStream() function. But then when I try to render the <head></head> tags with the markup by react-helmet-async it'll come back as undefined.

To get around this problem, I've had to use renderToString() first without actually writing that out to Express JS response. That way react-helmet-async can then see what meta tags to render and then proceed to use renderToNodeStream and stream that out to the response.

I've simplified my code as much as possible as I want to understand if this would have a negative impact (for performance, or if anyone can think of anything else)?

Before:

let html = ReactDOMServer.renderToString(stylesheet.collectStyles(
    <Loadable.Capture report={moduleName => modules.push(moduleName)}>
        <LocalStoreProvider store={store}>
            <HelmetProvider context={helmetContext}>
                <RouterContext {...renderProps} />
            </HelmetProvider>
        </LocalStoreProvider>
    </Loadable.Capture>
));

const { helmet } = helmetContext; 

response.write(
    renderDocumentHead({
        css: stylesheet.getStyleTags(),
        title: helmet.title.toString(),
        link: helmet.link.toString(),
        meta: helmet.meta.toString()
    })
);

response.write(html);

After:

let html = stylesheet.collectStyles(
    <Loadable.Capture report={moduleName => modules.push(moduleName)}>
        <LocalStoreProvider store={store}>
            <HelmetProvider context={helmetContext}>
                <RouterContext {...renderProps} />
            </HelmetProvider>
        </LocalStoreProvider>
    </Loadable.Capture>
);

// do a first pass render so that react-helmet-async 
// can see what meta tags to render
ReactDOMServer.renderToString(html);

const { helmet } = helmetContext; 

response.write(
    renderDocumentHead({
        css: stylesheet.getStyleTags(),
        title: helmet.title.toString(),
        link: helmet.link.toString(),
        meta: helmet.meta.toString()
    })
);

const stream = stylesheet.interleaveWithNodeStream(
    ReactDOMServer.renderToNodeStream(html)
);

// and then actually stream the react elements out
stream.pipe(response, { end: false });

stream.on('end', () => response.end('</body></html>'));

Unfortunately, the only way I could get react-helmet-async to work correctly, I have to do this two-pass render. My CSS styles, etc. resolves correctly and the client renders/hydrates correctly too. I've seen other examples where react-apollo was used and the getDataFromTree data rehydration method was used which allows react-helmet-async to see what was needed to render the head markup. But hopefully there are no issues with my two-pass rendering approach?

S. Luong
  • 116
  • 5
  • I arrived at the same conclusion. I tried using `react-tree-walker` to have a cheaper option but couldn't get it to work. Tried a number of scenarios – Marc Jan 22 '19 at 16:47
  • Yeah I think I've come to the conclusion that there's no issues with doing this as it's just running a function, not storing it anywhere or outputting via the response. I few other resources also mention a two pass render to make this work. I think if your custom SSR approach allows for this then this is a possible solution. – S. Luong Jan 23 '19 at 22:07
  • @S.Luong Does reach-helmet-async help me to get dynamic meta data in SSR at first hit and not undefined? – Ravi Garg Dec 09 '19 at 17:34
  • Never seen or used reach-helmet-async but react-helmet-async won't help you on first hit as far as I last checked. – S. Luong Dec 11 '19 at 08:24
  • Really interesting solution to this problem. I've recently been trying to migrate over to `renderToNodeStream` myself and have been encountering that my dynamic (i.e. depends on API data) helmet head data was out of sync. I also found this thread of interest over on react-helmet-async issues and the author had this tidbit to say: https://github.com/staylor/react-helmet-async/issues/37#issuecomment-622530358 A suggestion made by the user "diondirza" has gotten me closer to solving this issue. I still have to figure out how to properly transform the data stream. – Jon Eric Escobedo May 31 '20 at 16:32
  • Your scenario is very similar to mine in that case where my dynamic helmet data also depends on API data. My rationale for trying out `renderToNodeStream` was to improve my TTFB time and overall performance. So when you start processing your route matching you would do a `response.write` html fragment right at the beginning. But then comes your async actions of waiting for a response from your API. Is it going to be ~300ms? Because then you're just losing out on some serious time. Probably better to serve a cached HTML response if possible – S. Luong Jun 02 '20 at 07:35
  • Also for my tech stack, I found that from my node server, via a reverse proxy, through to AWS CloudFront I get ~300ms TTFB with ~11ms content download. But with a cached html response I can bring the TTFB down to ~60ms. However, in this yet another experimental solution I haven't figured out the the problem of state management and not just caching the response for one user. – S. Luong Jun 02 '20 at 07:41
  • I thought `renderToNodeStream` exist beacause it can make renderering process to readable stream, so send response without wating all rendering process. If you render your contents with `renderToString`, isn't there no advantage to using `renderToNodeStream`? – godsenal Apr 12 '21 at 06:07
  • Yep ideally it's use one or the other. There are advantages to using `renderToNodeStream` and you certainly should be using that, if possible. In my scenario, I can't use it as I would need another workaround to generate my html meta tags. – S. Luong Apr 13 '21 at 14:40

0 Answers0