Next.js and Styled-Components: style loading issue

rsanchezp profile image Raúl Sánchez ・1 min read

Have you tried using Styled-Components with your Next.js app but can't get the styles to load properly? This is because the server-side rendering does not fetch the styles before rendering the page. The Styled-Components documentation mentions this very briefly and it is easy to miss. What we actually have to do is inject server-side rendered styles to the head so it can render the page and its styles correctly. Next.js has the exact file you'll need to make this possible. Within the Next.js Github repo you can find _document.js. Within your Next.js project inside the pages folder create a file called _document.js and copy and paste all the code from the _document.js from the Next.js Github repo. This should fix your problem. Remember to restart the server to apply all changes.



markdown guide