styled-components: styled-components are not working with Next.js SSR

Hello,

I’ve recently come to know about the babel-plugin-styled-components and added the following code snippet into .babelrc.

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

but when I explicitly refresh my browser, the styled components are not working as defined. like styled-components don’t get loaded as required.

I tried to change the "ssr": true as well but not working.

please anyone can help me to solve the issue I am facing?

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 4
  • Comments: 17 (2 by maintainers)

Most upvoted comments

For newcomers to this issue, or if your app is running the new SWC compiler(default from v12), simply add the following to next.config.js:

compiler: {
    styledComponents: true,
  }

https://nextjs.org/docs/advanced-features/compiler#styled-components

For newcomers to this issue, or if your app is running the new SWC compiler(default from v12), simply add the following to next.config.js:

compiler: {
    styledComponents: true,
  }

https://nextjs.org/docs/advanced-features/compiler#styled-components

for some reason even tho I added it still having same issue… 😦

Actually, I’ve looked into this issue and my conclusion is that there is not really a way to make styled-components to be rendered on the server side, at least not with Next.js 13 and app router… But it is possible to make styled-components work with Next.js 13 without any “delay bugs” using client-side rendering and a few workarounds.

Step 1: add the following to your next.config.js file

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  compiler: {
    styledComponents: true,
  },
}

module.exports = nextConfig

Step 2: create the registry.tsx file with the following code:

'use client'
 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
 
export default function StyledComponentsRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())
 
  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement()
    styledComponentsStyleSheet.instance.clearTag()
    return styles
  })
 
  if (typeof window !== 'undefined') return <>{children}</>
 
  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  )
}

Step 3: add the ‘use client’ directive to your layout.tsx file and wrap all the children components on your layout with the StyledComponentsRegistry component.

I’ve made a tutorial if anyone needs further help: https://www.youtube.com/watch?v=3tgrPm2aKog

Hey! I’ve not been working anymore with NextJS or styled components… Is this still a problem with most recent versions of both NextJS and Styled Components? I’d suggest to anyone who wants to work with NextJS to use Tailwind instead of styled components, or if you want to use Styled Components, then go for plain and simple React. Otherwise it will be a constant struggle.

@dhavalveera You can put them in the same file. Here’s an example: https://github.com/agriffis/agcom/blob/4783dcb9eeae67de8765a551f4336e7068eed335/pages/_document.tsx

Be aware that this is probably not the source of the problem you’re experiencing. Rendering styles in SSR is an optimization, not a requirement. When you say:

the styled components are not working as defined. like styled-components don’t get loaded as required.

That means that you have some other issues in your code that are probably not going to be solved by enabling SSR rendering of styles.

Did you update your _document.js file accordingly? You will need to create a stylesheet server-side.

Check out this example of an _document.js.

@dhavalveera I believe it should be:

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

(notice it’s just styled-components instead of babel-plugin-styled-components). Also remember to npm install babel-plugin-styled-components). At least it’s like so in the project I just took over and it works fine 😄

The registry.tsx solution does not work for me. I can still se, for a fraction of a second, the server side rendered page, then styles are applied.

Thank you! You saved me from mental breakdown 😃

Actually, I’ve looked into this issue and my conclusion is that there is not really a way to make styled-components to be rendered on the server side, at least not with Next.js 13 and app router… But it is possible to make styled-components work with Next.js 13 without any “delay bugs” using client-side rendering and a few workarounds.

Step 1: add the following to your next.config.js file

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  compiler: {
    styledComponents: true,
  },
}

module.exports = nextConfig

Step 2: create the registry.tsx file with the following code:

'use client'
 
import React, { useState } from 'react'
import { useServerInsertedHTML } from 'next/navigation'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
 
export default function StyledComponentsRegistry({
  children,
}: {
  children: React.ReactNode
}) {
  // Only create stylesheet once with lazy initial state
  // x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
  const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet())
 
  useServerInsertedHTML(() => {
    const styles = styledComponentsStyleSheet.getStyleElement()
    styledComponentsStyleSheet.instance.clearTag()
    return styles
  })
 
  if (typeof window !== 'undefined') return <>{children}</>
 
  return (
    <StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
      {children}
    </StyleSheetManager>
  )
}

Step 3: add the ‘use client’ directive to your layout.tsx file and wrap all the children components on your layout with the StyledComponentsRegistry component.

I’ve made a tutorial if anyone needs further help: https://www.youtube.com/watch?v=3tgrPm2aKog

Thank you! You saved me from a mental breakdown 😃