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

Oldest comments (31)

Collapse
 
vrtech profile image
VrTech

It works like a charm!

Collapse
 
sergeytyan profile image
Sergey Tyan

thanks! worked for me too!

Collapse
 
pedrobertao profile image
Pedro Bertao

Thanks

Collapse
 
ridakejji profile image
ridakejji

God bless your soul

Collapse
 
rajnandigalla profile image
Raj Nandigalla

Life saver

Collapse
 
ciberus profile image
Ciberus

Thanx a lot. I forgot this after adding _app, and lost 9hours to debug why in production styles broken🙃

Collapse
 
peppermint_juli profile image
Juliana Jaime 🎃

YOU RE AMAZING! Thank you so so so much!! I've been struggling with this for 2 days, I was about to give up using styled components.
Thank you!

Collapse
 
qqpann profile image
qpan

You saved my day. 🙏

Collapse
 
mahdizaabi profile image
crxs14

Hello!
Where i can find the _document.js please ?
I can't find it on the next js github repo !

Collapse
 
rsanchezp profile image
Raúl Sánchez
Collapse
 
nicolaas0 profile image
Nicolaas Lerrick

Thank you so much!!

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
 
developergp profile image
GPWebDeveloper

Thank you. It helped-me a lot. God bless your soul.

Collapse
 
zomeru profile image
Zomer Gregorio

Thank you so much bro!

Collapse
 
buabaj_ profile image
Jerry Buaba

wow this saved me, thanks!

Collapse
 
horpey profile image
Tha_UI_Guy

Thank you