CSS must be server-side rendered or you'll end up with a flash of unstyled content (FOUC).
styled-jsx Docs: Server-Side Rendering
// next.config.js
module.exports = {
webpack: (config, { defaultLoaders }) => {
config.module.rules.push({
test: /\.css$/,
use: [
defaultLoaders.babel,
{
loader: require('styled-jsx/webpack').loader,
options: {
type: 'scoped'
}
}
]
})
return config
}
}
GitHub, nextjs Issue: styled-jsx does not render server side with custom _document.js
// pages/_document.js
// _document is only rendered on the server side and not on the client side
// Event handlers like onClick can't be added to this file
// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'
import flush from 'styled-jsx/server'
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const { html, head, errorHtml, chunks } = renderPage()
const styles = flush()
return { html, head, errorHtml, chunks, styles }
}
render() {
return (
<html>
<Head>
{this.props.styles}
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}