1

I was trying to make Server Side Rendering using Node,Express and React18 feature. The method I used was with renderToPipeableStream and not with renderToString.

Link for the CODE -

  1. GITHUB : https://github.com/ranjanrnj44/react-ssr/tree/master
  2. CODESANDBX : https://codesandbox.io/s/react-ssr-9x9ohn

NOTE :

  1. Please Download the code and run from the local machine. I have provided package.json file to install all the dependencies
  2. for now, on any code changes in server side I'm generating a build file (please look package.json under scripts line 25 and 28)
  3. after changes on server.js please try running npm run bild followed by npm run ssr(now you will notice app is running on localhost:3001/one)

ISSUE :

  • I get message like Hydration failed because the initial UI does not match what was rendered on the server.
  • The server generated HTML file is not with whole part that includes (html,head,meta,body tags).
  • In renderToString method we can use replace method to inject the data but here, I'm streaming html(stream- nodejs part)
  • I couldn't inject the chunk of data between the root file (i.e ideally <div id="root"> <!-received chunk data should inject here-></div> )

WHAT I TRIED :

  1. I tried sending hard-coded split method and inject the response (Unfortunately I got [object][Object] error).
  2. Also tried serving whole raw content with response to stream.pipe(). It doesn't work.

Please provide me the solution to match the Server generated HTML and Client side HTML so that I can hydrate the UI.

user9151444
  • 31
  • 1
  • 9
  • When you dive into the error stack in the browser you can find the reason for that. 1st problem ist the import of const UserListFetch = lazy(() => import("./components/UserListFetch")); where only a UserFetch file exists in your example. 2nd problem is, that in UserListSSR the fetchedData ist not filled and you map over undefined object. I hope you can go on with that. All in all the hydration mismatch seems to be a consequential error. PS: Your call to download the code to the local system seems a bit like a junk mail ;) – Marcel Hinderlich Sep 22 '22 at 10:32
  • Thank you Marcel, I tried this, and also went with concatenate method to bind the structure. It worked, unfortunately hydration has not happening. – user9151444 Sep 23 '22 at 14:22

1 Answers1

0

The thing is, when you're working with react streaming, there's no real way to inject something in it.

The solution would be to provide your own Document component like in Next.js.

const Document = ({ title, js, css, children }) => {
  return (
    <html>
      <head>
        <meta charSet="utf-8" />
        <title>{title}</title>
        {js.map((src, i) => (
          <script key={i} src={src} defer />
        ))}
        {css.map((src, i) => (
          <link key={i} href={src} rel="stylesheet" />
        ))}
      </head>
      <body>
        <div id="root">{children}</div>
      </body>
    </html>
  );
};