Go back

Next.js supports styled-components now?

Eons ago, I wrote about an issue — fixing styled-components server mismatch error in Next.js — I had with styled-components. Today, I tried updating meje.dev to a newer version (13.5.6) of Next.js (Not 14, please.) and I got this in my terminal

nextjs CLI interface with details about the current dev server instance running on port 3000

Although, the image above shows my current version as 14.0.1, I ran into an error that I can't even describe. So, I'm just going to place the screenshot below:

errors on caleb's netlify dashboard due to an upgrade of the Next.js version to 14

I had to switch between pnpm, yarn and now npm, multiple times. It was that bad. But, that's not for this post.

The styled-compponent issue was more of a compatibility issue with Next.js' rendering patterns. So the ideal way to bypass this was to use a custom babel plugin — "babel-plugin-styled-components" — for transpiling (compiling).

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

As of then Next's compiler, SWC doesn't do that. I am still trying to understand why. Apparently, this support was already being worked on by the team, since 2021.

update next.config

In the image of my terminal that i shared. The info in my terminal suggests that I remove the babel configuration since its compiler takes care of tthat now.

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

In my next.config.js file, all I had to do was include the compiler rule and include styledComponents, with ssr enabled. I think this is even supported by default. So without explicitly setting this, it works just fine.

But, if you want to include more customizations. You can check the props they allow, here

So what now?

I think this is a good thing that I do not have to worry about manually configuring a transpiler for my styles. Instead, I can just rely on SWC's capabilities. Another good thing about this support is improved performance and build times.