Search code examples
javascriptreactjsnext.js

NextJS: Main and Nextscript


Exploring NextJS a bit for its server side rendering features. It looks really nice and easy to use. I already explored the _document.js file which we can include to overwrite the default. I found the following code in an example:

import Document, { Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (
      <html>
        <Head>
          <link rel="stylesheet" href="/_next/static/style.css" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

Now I get it that we are overwriting the current HTML template. But I'm a bit confused regarding the functionality of the Main and Nextscript.

Is Main just a page? What is Nextscript (which script)?


Solution

  • NextScript Class is here

    and Main Class is here and I copied the same below. Main renders html/ errorHtml from this.context._documentProps

    export class Main extends Component {
      static contextTypes = {
        _documentProps: PropTypes.any
      }
    
      render () {
        const { html, errorHtml } = this.context._documentProps
        return (
          <Fragment>
            <div id='__next' dangerouslySetInnerHTML={{ __html: html }} />
            <div id='__next-error' dangerouslySetInnerHTML={{ __html: errorHtml }} />
          </Fragment>
        )
      }
    }
    

    you can find actual documentation on Custom Document here