How can I use getInitialProps only during the NextJS site build?

When using NextJS to build a static site, I would like the getInitialProps method to fire only during the build step and not on the client.

In the build step, NextJS runs the getInitialProps method before each component’s rendered HTML is used to generate the page’s static HTML. On the client, NextJS also runs this method before the page component is rendered in order to return the necessary props for the component. Thus, large requests can delay the client’s first paint as this is a blocking request.

// example usage of API call in getInitialProps
import fetch from 'isomorphic-unfetch'

function Page({ stars }) {
  return <div>Next stars: {stars}</div>
}

Page.getInitialProps = async ({ req }) => {
  const res = await fetch('https://api.github.com/repos/zeit/next.js')
  const json = await res.json()
  return { stars: json.stargazers_count }
}

export default Page

I’m unwilling to move my slow API request to componentDidMount in order to avoid the blocking request because I want to use the data returned during the build step to populate the static HTML, and this particular request doesn’t need to be dynamic or updated after the build.

Is there a way I can make getInitialProps run only when next export builds and not as the client loads the page?

Is this good practice?

Answer

I found the workaround with NextJs 9.0.3 (other versions may also work, I didn’t test that)

// XXXPage is your page

XXXPage.getInitialProps = async (req) => {
  if (process.browser) {
    return __NEXT_DATA__.props.pageProps;
  }
  // original logic
}

Leave a Reply

Your email address will not be published. Required fields are marked *