Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To implement Styled-components in Next.js 13 while utilizing SSR, follow these steps:

  1. Install styled-components and babel-plugin-styled-components.
npm install --save styled-components babel-plugin-styled-components
  1. Create a babel.config.js file at the root of your project and add the following code:
module.exports = {
  presets: ["next/babel"],
  plugins: [["styled-components", { ssr: true }]],
};
  1. Create a _document.js file in your pages folder and add the following code:
import Document, { Html, Head, Main, NextScript } 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() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
  1. Create a _app.js file in your pages folder and add the following code:
import { createGlobalStyle, ThemeProvider } from "styled-components";

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
  }
`;

const theme = {
  colors: {
    primary: "#0070f3",
  },
};

function MyApp({ Component, pageProps }) {
  return (
    <>
      <GlobalStyle />
      <ThemeProvider theme={theme}>
        <Component {...pageProps} />
      </ThemeProvider>
    </>
  );
}

export default MyApp;
  1. Finally, you can use styled-components in your components like so:
import styled from "styled-components";

const Button = styled.button`
  background-color: ${(props) => props.theme.colors.primary};
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
`;

export default function Home() {
  return <Button>Hello World!</Button>;
}

Now, when you run your Next.js app, your styled-components will be rendered on the server and hydrated on the client.