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 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.
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
This is how I fixed.
We need custom
document.js
and customapp.js
as mentioned in MaterialUI NextJS exampleCopy
_document.js
and_app.js
from here https://github.com/mui-org/material-ui/tree/master/examples/nextjs/pagesto
pages
folderCopy
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.