Skip to content

Instantly share code, notes, and snippets.

@rekomat
Created August 30, 2018 09:37
Show Gist options
  • Save rekomat/5995e83444e7cea907a5f5c6159b80fc to your computer and use it in GitHub Desktop.
Save rekomat/5995e83444e7cea907a5f5c6159b80fc to your computer and use it in GitHub Desktop.
Next.js Cheatsheet

Next.js Cheatsheet

CSS Server-Side

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>
    )
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment