Reactjs – Page refresh break styles on Nextjs production app

antdnext.jsreactjs

I have a website built with Nextjs that break styles on page refresh or when a user visits the website directly to a specific route and not the root route. Eg https://vinnieography.web.app/contacts (The site link if it looks ok, try to refresh and see)

The website is hosted on Firebase Functions and uses Nextjs and Ant design components.

Screenshot of the site before a refresh

Screenshot of the site before a refresh

Screenshot of the site after a refresh (Notice the missing Nav)

The Nav is not completely missing but it became a mobile nav whose icon is not shown but you get a dropdown with Nav links when hovering around the Nav area.

Screenshot of the site after a refresh

My next.config.js

const withCss = require('@zeit/next-css')

module.exports = withCss({
  webpack: (config, { isServer }) => {
    if (isServer) {
      const antStyles = /antd\/.*?\/style\/css.*?/
      const origExternals = [...config.externals]
      config.externals = [
        (context, request, callback) => {
          if (request.match(antStyles)) return callback()
          if (typeof origExternals[0] === 'function') {
            origExternals[0](context, request, callback)
          } else {
            callback()
          }
        },
        ...(typeof origExternals[0] === 'function' ? [] : origExternals),
      ]

      config.module.rules.unshift({
        test: antStyles,
        use: 'null-loader',
      })
    }

    // Fixes npm packages that depend on `fs` module
    config.node = {
      fs: 'empty'
    }

    return config
  },
  distDir: "../../dist/client"
})

Versions of Nextjs, React & Antd.

"antd": "^3.24.2",
"next": "^9.0.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"@zeit/next-css": "^1.0.1",

Best Answer

I got this issue when working with NextJS 9.4 with MaterialUI.

I got this warning in console whenever styles are broken

Warning: Prop className did not match. Server: "MuiBox-root MuiBox-root-5" Client: "MuiBox-root MuiBox-root-1" in span (created by Styled(MuiBox))

enter image description here

This is how I fixed.

We need custom document.js and custom app.js as mentioned in MaterialUI NextJS example

Copy _document.js and _app.js from here https://github.com/mui-org/material-ui/tree/master/examples/nextjs/pages

enter image description here

to pages folder

enter image description here

Copy theme.js from https://github.com/mui-org/material-ui/tree/master/examples/nextjs/src and place it somewhere and update the import links in _document.js and _app.js

The styles should work now.

Related Topic