Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 734
Willem van der Veen Avatar asked Aug 29 '18 18:08

Willem van der Veen


People also ask

What is NextScript?

The default NextScript implementation captures the scripts generated by the Next build process and immediately renders them to <script> tags in its render() function.

Is Next.js spa or MPA?

NextJS by default is not SPA based due to its hybrid nature, because it publishes each page as a separate entry point for everything under /pages . Of course if you only have one page index. js , then technically it's a SPA again.

Is Next.js only for SSR?

The sole purpose of Next is to use SSR, if you don't want it, just drop it entirely and use normal react alone. Next. js pre-renders every page, either at build time when using SSG, or at request time when using SSR. You can't have client-side rendering only, you have to have it along with SSG or SSR.

Does Next.js use client-side routing?

The Next.js router allows you to do client-side route transitions between pages, similar to a single-page application. A React component called Link is provided to do this client-side route transition.


1 Answers

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

like image 155
madhu131313 Avatar answered Sep 17 '22 14:09

madhu131313