next.js: Styled Components fail to SSR on first render
I’m am using styled-components in Next.js. When I deploy the app, the first time the UI is rendered, it is unstyled. Only after a refresh does the SSR styles come through and persist.
Implementation based on: https://github.com/zeit/next.js/tree/canary/examples/with-styled-components
Anyone have ideas? I’m stumped atm 😦 https://github.com/stephencorwin/nextjs-hello-world/tree/styled-components-ssr-error
- I have searched the issues of this repository and believe that this is not a duplicate.
Expected Behavior
When I deploy the app, any SSR styles should be rendered the first refresh.
Current Behavior
When I deploy the app, the first time the UI is rendered, it is unstyled. Only after a refresh does the SSR styles come through and persist.
First Render:
Second Render:
Steps to Reproduce (for bugs)
- Wait 2 mins for it to finish. Don’t view the interstitial website with the progress status first.
- Go to the website generated by Now – fantastic feature btw!!!
- My
<Header />,<Footer />, andglobalStyles()in the_document.jsare not coming through. - Refresh the page and you will notice the styling has been fixed.
Context
When I deploy the app, I should NOT have to visit the website once to ensure that the SSR styles are generated.
Your Environment
| Tech | Version |
|---|---|
| node | 8.7.0 |
| next | 4.2.3 |
| styled-components | 3.1.6 |
| babel-plugin-styled-components | 1.5.0 |
| OS | Windows 10 |
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 5
- Comments: 15 (8 by maintainers)
+1. have the same problem at v8.0.1
I just came here with the same problem. I copied the styled components example from the examples folder.
@timneutkens I wound up here tonight with the same issues. With PR #4129 close to completion, does this mean we can / should do styled-components
injectGlobalin the soon to be exposedapp.jsinstead of_document.jsand have it behave as expected?same problem
“I have the same problem” on a closed issue while not providing a reproduction is not really helpful. Can you open a new issue with a clear and concise reproduction following the issue template. Thanks 🙏
this is just a guess based on how the example (and my own project) is configured, but have you tried moving the global style injections out of
_document?I inject all of my global styles in a template component that i import into each page, and my
getInitialPropsin_documentmore or less just mirrors the example.It’s also worth noting that I always call
injectGlobaloutside ofgetInitialProps, but I’m not smart enough on the SSR pipeline to speculate on if that matters or not.So, in your case, try editing your
Home.jsto something like thisI use this pattern a lot in my
nextapp to inject third-party css on-demand, so I’m certain it works. Whether or not it addresses your specific problem is to be determinbed, though.