DEV Community

Next.js and Styled-Components: style loading issue

Raúl Sánchez on February 09, 2020

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 d...
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
 
praiseisaac profile image
praise •

Works great thanks.

Collapse
 
kiehlb profile image
kiehlB •

thank you so much! it worked very well!

Collapse
 
emmanuel001 profile image
Idoko Emmanuel •

This was really helpful, thanks

Collapse
 
giayychan profile image
Gia Chan •

Thanks!

Collapse
 
ehceyn profile image
Chimeruzee •

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

Collapse
 
zomeru profile image
Zomer Gregorio •

Thank you so much bro!

Collapse
 
horpey profile image
Tha_UI_Guy •

Thank you

Collapse
 
bradwray profile image
Brad Wray •

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

Collapse
 
hardikpedia profile image
HARDIK GUPTA •

Thank you so much it worked like magic

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
 
gabehercules profile image
Gabriel Hercules •

A Hero whitout a cape

Collapse
 
buabaj_ profile image
Jerry Buaba •

wow this saved me, thanks!

Collapse
 
hastacs profile image
Hasta •

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

Collapse
 
sagarkhadkaa profile image
Sagar Khadka • • Edited

For typescript project,
in _document.tsx
Use the following code.

import Document, { DocumentContext } from "next/document";
import { ServerStyleSheet } from "styled-components";

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

or
Follow this link

Collapse
 
denniscodes profile image
Dennis Mwangi •

for those using typescript nextjs template

import Document, { DocumentContext, DocumentInitialProps } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;
    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
        });
      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
denniscodes profile image
Dennis Mwangi •

this worked so well you can also create a .babelrc at the root folder of your project and add the following code.
if you are using style-components

{
    "presets": ["next/babel"],
    "plugins": [["styled-components", { "ssr": true }]]
}
Enter fullscreen mode Exit fullscreen mode
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
 
developergp profile image
GPWebDeveloper •

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

Collapse
 
jawadahmed profile image
Jawad Ahmed •

Thank you so much!
Works Great