Sending React Component styled with MUI5 as HTML string from client to server. Emotion cache data gets lost

539 Views Asked by At

I'm sending a React Component styled with MUI5 as HTML string to the backend to generate a PDF. We have separate repos for React app and Node server. This official MUI5 Server Rendering documentation is the reference I settled on.

Approach:

  1. Convert the component to HTML string, providing redux data as well as emotion cache and other MUI-related style data. Send HTML string and cache object to backend.
export const convertJsxToHtmlCache = (componentWithProps) => {
    const cache = createEmotionCache();
    console.log('cache: ', cache);

    const html = ReactDOMServer.renderToString(
        <Provider store={store}>
            <CacheProvider value={cache}>
                <ThemeProvider theme={theme}>
                    <CssBaseline />
                    {componentWithProps}
                </ThemeProvider>
            </CacheProvider>
        </Provider>,
    );

    return { html, cache };
};
  1. Extract CSS from emotion cache and return a new HTML string that includes the extracted emotion CSS
export const renderFullPage = ({ html, cache }) => {
    console.log('CACHE: ', cache);
    const { extractCriticalToChunks, constructStyleTagsFromChunks } = createEmotionServer(cache);
    const emotionChunks = extractCriticalToChunks(html);
    const emotionCss = constructStyleTagsFromChunks(emotionChunks);
    console.log('emotionCss: ', emotionCss);

    return `
    <!DOCTYPE html>
    <html>
      <head>
        <title>My page</title>
        ${emotionCss}
        <meta name="viewport" content="initial-scale=1, width=device-width" />
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
      </head>
      <body>
        <div id="root">
                    ${html}
                </div>
      </body>
    </html>
  `;
};

In step 2, an error is thrown that Emotion CSS is empty. It seems to be there in the Emotion cache logged in browser console, but not in the backend after transmitted as POST request body. If this is the issue, is there a way to transmit style information elements from app to server?

Any advice / input would be appreciated.

0

There are 0 best solutions below