DEV Community

Raúl Sánchez
Raúl Sánchez

Posted on

Next.js and Styled-Components: style loading issue

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.

-__tests__
-components
-pages
   -_document.js
   -index.js
-public

Top comments (31)

Collapse
 
azivkovi profile image
Ante

I had the same problem with a plugin to prerender react app. HTML would load before the styling and for a split second elements would be a mess. Didn't find a solution there.

Now had the same issue with a production version of next.js, but this trick saved the day. Thanks.

Collapse
 
jxshdavis profile image
jxshdavis

This worked, BUT...

I used this and it worked flawlessly. But now how to I add new fonts to my Next JS app with google fonts. This process involves my _document.js file and I don't know what to do: nextjs.org/docs/basic-features/fon....

Collapse
 
emmanuel001 profile image
Idoko Emmanuel

This was really helpful, thanks

Collapse
 
praiseisaac profile image
praise

Works great thanks.

Collapse
 
zomeru profile image
Zomer Gregorio

Thank you so much bro!

Collapse
 
ehceyn profile image
Chimeruzee

Merci beaucoup mon ami. This solved the issue that cost me hours. I am grateful

Collapse
 
giayychan profile image
Gia Chan

Thanks!

Collapse
 
hardikpedia profile image
HARDIK GUPTA

Thank you so much it worked like magic

Collapse
 
bradwray profile image
Brad Wray

Thank you so much for pointing this out!!! Totally mindboggling style problems have been unboggled.

Collapse
 
kiehlb profile image
kiehlB

thank you so much! it worked very well!

Collapse
 
horpey profile image
Tha_UI_Guy

Thank you

Collapse
 
hastacs profile image
Hasta

nice thanks,, you saved the first render FLICK with materialui & nextjs too

Collapse
 
kwadoskii profile image
Austin Ofor • Edited

Thank you so much, you saved my deployed app on Heroku. I also added the .babelrc config below to enable my app to work well.

{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]],
}

Collapse
 
buabaj_ profile image
Jerry Buaba

wow this saved me, thanks!

Collapse
 
gabehercules profile image
Gabriel Hercules

A Hero whitout a cape