Willem van der Veen
Willem van der Veen

Reputation: 36660

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

Upvotes: 23

Views: 29603

Answers (2)

Никитос
Никитос

Reputation: 390

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}
/>

Upvotes: 11

madhu131313
madhu131313

Reputation: 7396

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

Upvotes: 15

Related Questions