Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andremalveira/3e9ef7fdef90d2fce2fc054b662f8a37 to your computer and use it in GitHub Desktop.
Save andremalveira/3e9ef7fdef90d2fce2fc054b662f8a37 to your computer and use it in GitHub Desktop.
Problem fixed in css when javascript is disabled in Next.js!

✅ Problem fixed in css when javascript is disabled in Next.js!

Server side rendering Styled-Components with NextJS

  • Make sure you have these packages in package.json:
  {
  "dependencies": {
    "next": "latest",
    "react": "^16.8.0",
    "react-dom": "^16.8.0",
    "styled-components": "latest"
  },
  "devDependencies": {
    "babel-plugin-styled-components": "latest",
  }
  • And in .babelrc
  {
    "presets": ["next/babel"],
    "plugins": [["styled-components", { "ssr": true }]]
  }
  • Finally, let’s take a look at _document.js: this is where the magic happens. Styled-components creates an instance of ServerStyleSheet This stylesheet retrieves any styles found in all the components inside our <App />. This then gets passed into our Html template later on.
import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    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();
    }
  }

   render() {
     //render here!
   }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment