Search code examples
reactjsserver-side-renderingstyled-componentsisomorphic-javascript

SSR with styled-components - when app.js loads site missing few styles


I have SSR implemented with styled-components.

When the page loads with SSR, everything looks good. However, when the app.js is loaded and hydrated together with SSR version, page is missing some styles and few elements breaks.

Whats more - when I turn app locally, with npm start or basically just remove my SSR, everything works fine and styles are being applied correctly.

Important: when I enter the page and app.js loads and styles are broken, if I change route - the new route appears with applied styles correctly and the problem is... gone.

  • SSR loads - styles are fine
  • then after few secs app.js loads (hydration process) - styles are broken

running app locally - no problems with styles

running app without SSR - no problems with styles


So in a brief - if I use SSR im missing some styles, the SSR itself returns proper styles, but after hydration with app.js few components are broken.

I bet it's probably an issue with styled-components. The SSR works fine and everything else, except that one component which is missing styles.


Im aware that it's rather uncomplete information about my case, but to show every part which could be responsible for this error, I should publish whole project, however maybe you experienced similar case and you would help me somehow. Thanks.

Edit: My babel-styled-component-plugin config:

['babel-plugin-styled-components', {
    ssr: true,
    displayName: false,
    fileName: false,
    transpileTemplateLiterals: false,
    minify: false,
}],

Solution

  • Two things...

    1) Make sure you're using the babel plugin; without it there's no guarantee the generated class names will be the same between server and client.

    2) In your bundling setup, make sure you're using mostly the same babel config for both client and server. If there's a major discrepancy and the files are being transformed in very different ways, that can affect the generated class name output.