next.js: React server mismatches: Prop `className` did not match.

Bug report

Describe the bug

After upgrading from Next.js 9.0.5 to 9.2.2 we noticed that we are getting server mismatches for a lot of our components which never errored before. We also tried other versions (e.g. 9.1.x, 9.2.x, 9.3.x) and all of them have the same problem.

To Reproduce

Please use this repository with easy reproducible error - https://github.com/voronianski/nextjs-server-mismatch-bug

The code of the example component is open-source UI library and you can find it here - https://github.com/sumup-oss/circuit-ui/blob/canary/src/components/Hamburger/Hamburger.js

Screenshots

image

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 14
  • Comments: 57 (8 by maintainers)

Commits related to this issue

Most upvoted comments

Closing as it’s a bug in your application and can be better solved in Discussions or on Discord!

I can confirm that with next 10 😢

It was driving me crazy! I spent so many days in this warning and no of the solutions fixed it for me. I finally getting work putting this in the .babelrc file

{
 "presets": [
   "next/babel"
 ],
 "plugins": [
   [
     "babel-plugin-styled-components",
     {
       "ssr": true,
       "minify": true,
       "transpileTemplateLiterals": true,
       "pure": true,
       "displayName": true,
       "preprocess": false
     }
   ]
 ]
}

This has been reported in April and still no fix in November?!

This is not a bug in Next.js. You’re likely using a css-in-js library that is not pre-rendering styles correctly (or not pre-rendering at all) which causes a hydration mismatch given the pre-rendered markup would not match the markup generated client-side.

I’ve ended up here for 3 different projects the past couple of months. This is what has silenced the error all 3 times:

  1. Create the .babelrc file in your root folder
  2. Add this: { "presets": [ "next/babel" ], "plugins": [ [ "styled-components", { "ssr": true } ] ] }

(hello to future me for the 4th project)

Hey folks, in my case it was the reactStrictMode: true flag in next.conf.js that was causing the issue, when I removed it, it’s gone! @Timer there is probably a bug here.

Hi Guys,

I am facing the same issue using NextJS along with Styled Components. Following these steps has worked for me when I am starting the dev server. But once I change any code and refresh the page, again I get the same error.

Has anyone encountered a similar issue?

I’ve ended up here for 3 different projects the past couple of months. This is what has silenced the error all 3 times:

  1. Create the .babelrc file in your root folder
  2. Add this: { "presets": [ "next/babel" ], "plugins": [ [ "styled-components", { "ssr": true } ] ] }

(hello to future me for the 4th project)

That’s works for me. Thanks!

It was driving me crazy! I spent so many days in this warning and no of the solutions fixed it for me. I finally getting work putting this in the .babelrc file

{
 "presets": [
   "next/babel"
 ],
 "plugins": [
   [
     "babel-plugin-styled-components",
     {
       "ssr": true,
       "minify": true,
       "transpileTemplateLiterals": true,
       "pure": true,
       "displayName": true,
       "preprocess": false
     }
   ]
 ]
}

I can also confirm that it works for me as well!

@voronianski

Here is the Codesandbox example. (https://codesandbox.io/s/next-typescript-app-f2k0y) (PS: The error does not appear every time in console)

index.tsx

import * as React from "react";
import styled from "../lib/styledComponents";

const Wrapper = styled.div`
  min-height: 100vh;
`;

export default function IndexPage() {
  return <Wrapper>WrapperContent2</Wrapper>;
}

lib/styledComponents.tsx

import * as styledComponents from "styled-components";
import { ThemedStyledComponentsModule } from "styled-components";

import { Theme } from "./defaultTheme";

const {
  default: styled,
  css,
  createGlobalStyle,
  ThemeProvider,
  ThemeConsumer,
  keyframes
} = (styledComponents as any) as ThemedStyledComponentsModule<Theme>;

export {
  css,
  createGlobalStyle,
  keyframes,
  ThemeProvider,
  ThemeConsumer,
  Theme
};

export default styled;

lib/defaultTheme.tsx

export const defaultTheme = {
  backgroundColor: "#ffffff",
  borderRadius: "5px",
  breakpoints: ["576px", "768px", "992px"],
  color: "#666666"
};

export type Theme = Readonly<typeof defaultTheme>;
export const Theme = defaultTheme;
export default defaultTheme as Theme;

You can see that the error appear when i use custom theming. I would be really appreciate if someone knows how to solve the problem.

UPDATE What fixed the problem ? Don’t import styled from custom theme!

Create a file styled.d.ts

import {} from 'styled-components'
import { theme } from './utils/theme'

declare module 'styled-components' {
  type Theme = typeof theme
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
  export interface DefaultTheme extends Theme {}
}

and import styled from styled-components in your components

Hi @mulholio,

Thank you for the suggestion. I’ve tried the recommend from styled component’s document in circuit-ui but the mismatch error still shows up.

And I think emotion natures comes with SSR setting. Shouldn’t need more setup to make the hash consistency.

Please correct me if I miss anything here. Thanks!!

.babelrc worked for me too! Thanks!

In case this helps, vercel has an example of wha the .babelrc file needs to look like for this error not to happen.

https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/.babelrc

It was driving me crazy! I spent so many days in this warning and no of the solutions fixed it for me. I finally getting work putting this in the .babelrc file

{
 "presets": [
   "next/babel"
 ],
 "plugins": [
   [
     "babel-plugin-styled-components",
     {
       "ssr": true,
       "minify": true,
       "transpileTemplateLiterals": true,
       "pure": true,
       "displayName": true,
       "preprocess": false
     }
   ]
 ]
}

This works for me as well, after deleting my .next folder.

@sheeraz1022 Yes.

  1. Starting the dev server, there is no error
  2. Change the props to style-components so new class is applied, gives an error about className mismatch on client and server
  3. Further restarting of dev server doesnt solve the issue
  4. And then again once in a while, the cycle repeats from point 1

But I have a monorepo, and am building styled-components using tsdx and providing custom .babelrc

I’m not using style components and still have this issue! I’m using Ant design, anyone else has this problem with ant design?

9.5.2, bug is still present

Same problem here, trying to use styled(ExternalComponent) mismatches classes.

Similar issue and @KyorCode’s comment was my problem. I just had to convert all const StyledComponent = styled(Component) to be const StyledComponent = styled.[html-element-goes-here]... for each “offending” component.

Total speculation, but maybe it’s that the server and client can’t rectify some type of ambiguity with styled(Component), which is made to inherit classes of another styled component.

@barthicus

@kkis Can you provide some codesandbox os smth similar so we can see the problem and try to fix it?

this repo with reproducible setup is available since bug is reported - https://github.com/voronianski/nextjs-server-mismatch-bug

I tried to upgrade to 9.4.0 but it didn’t help.


What helped though is using completely ES5 transpiled version of the component - https://github.com/voronianski/nextjs-server-mismatch-bug/pull/1

Also using plain ESNext component fixes mismatches - https://github.com/voronianski/nextjs-server-mismatch-bug/pull/2

So something seems to be wrong with exported module versions of components - https://unpkg.com/@sumup/circuit-ui@1.8.0/lib/es/components/Hamburger/Hamburger.js

Hello, i still stuck on the problem, that in dev mode i see the error on initial page loading. On prod mode i don’t see

 next": "9.4.0",
"react": "16.13.0",
"babel-plugin-styled-components": "1.10.7",
"styled-components": "4.4.1",
import ...

const AppWrapper: FC = (props) => {
  const { children } = props

  return (
    <ThemeProvider theme={getTheme()}>
      <MessageProvider>
        <Layout cmsContent={appData}>
          <LocationTracker>{children}</LocationTracker>
        </Layout>
      </MessageProvider>
    </ThemeProvider>
  )
}

class App extends NextApp<{
  apolloClients: ApolloClients
  statusCode?: number
}> {
  render() {
    const {
      apolloClients,
      Component,
      pageProps,
      statusCode,
    } = this.props

    return (
      <ApolloClientProvider clients={apolloClients}>
        <Component statusCode={statusCode} {...pageProps} />
      </ApolloClientProvider>
    )
  }
}

  • dynamic import of themprovider doesn’t work
  • babel changes [‘styled-components’, { ssr: true, displayName:true/false, preprocess:true/false }], doesnt work
  • nothing worked 😦

@barthicus Same prob

Bildschirmfoto 2020-05-13 um 12 43 31

Hi @all, same problem on my site. Since 3 days i already stuck on this problem.

Packages

“next”: “9.4.0”, “@types/styled-components”: “4.4.3”, “babel-plugin-styled-components”: “1.10.7”, “styled-components”: “4.4.1”, …

Node 12.14.1

I see that some guys had the same problems before (https://github.com/zeit/next.js/issues/3706) and so i tried to solve my problems with the tips there. Nothing worked for me 😦

Fails

  • Remove  components where class is broken -> other component fails
  • Update/Upgraded styled-components packages
  • Update/Upgraded all packages
  • Change different options in Babel config ( used babel-plugin-styled-components with different settings)
  • try using nextjs dynamic import
  • changed also my _document like described here https://github.com/zeit/next.js/issues/3706#issuecomment-471891636

The errors occurs on dev env (yarn dev) in Chome dev console. If iam start my local prod env ( yarn build && yarn start )i see no error in Chrome dev console or server output log