Home > OS >  getInitialProps function in document.js run on server or client?
getInitialProps function in document.js run on server or client?

Time:07-13

getInitialProps function run just in servser or client or both ?


class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx);

    console.log("document.js");

    return { ...initialProps };
  }

  render = () => (
    <Html>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

CodePudding user response:

https://github.com/vercel/next.js/discussions/11211#discussioncomment-1692

If I use getInitialProps will the list of books be outdated to what was the list at the time I ran npm run build?

No, it'll be server-rendered on-demand.

If I use getServerProps what happens from a user perspective? Is that a more up to date list?

getServerSideProps has slightly different semantics than getInitialProps. On client-side transitions getInitialProps will execute it's code in the browser, whereas with getServerSideProps it will call an API endpoint of sorts that will run getServerSideProps and return the results.

The code in getServerSideProps is not sent to the browser, which makes bundle sizes smaller.

Also you can check https://nextjs.org/docs/api-reference/data-fetching/get-initial-props https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props

  • Related