NextJS: Main and Nextscript

11,536

Solution 1

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

Solution 2

For those who will look for an answer to this question in the future...

Component NextScript from 'next/document' takes a list of files from context._documentProps and returns each of them as a element like this:

<script
        key={file}
        src={`${assetPrefix}/_next/${file}`}
        nonce={this.props.nonce}
        async
      />

It also takes dynamic imports from context._documentProps and returns them in a similar way:

<script
        async
        key={bundle.file}
        src={`${assetPrefix}/_next/${bundle.file}`}
        nonce={this.props.nonce}
      />
Share:
11,536

Related videos on Youtube

Willem van der Veen
Author by

Willem van der Veen

Started programming since 2014 in Java because of interest. Since then I developed a passion with a variety of languages and technologies. I am currently making web applications professionally.

Updated on June 04, 2022

Comments

  • Willem van der Veen
    Willem van der Veen almost 2 years

    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)?