Next.js Discord

Discord Forum

What is the point of getInitialProps?

Unanswered
Oak rough bulletgall wasp posted this in #help-forum
Open in Discord
Avatar
Oak rough bulletgall waspOP
I wanted an easy way to construct an OKTA authentication url, using ENV vars and request headers to construct the various components for it, and figured, it would not hurt to have that url globablly available everywhere... I saw the app I am working on has in every component this duplicate code:

export async function getServerSideProps() {
  const env: EnvironmentVariables = {
    PAGE_TITLE_PREFIX: process.env.PAGE_TITLE_PREFIX,
  }

  return {
    props: {
      env,
    },
  }

I thought-- ok I can put this authentication URL inside here too.. but the fact that this code was duplicated everywhere made me annoyed and thought it's dumb.. So I looked at NextJS' docs and saw getInitialProps and read "it runs on the server as well as the client" ... So I thought-- ok cool, it can get that env variable when it runs on the server, and I can build the okta url there.. So I removed all of those getServerSideProps and added to _app:

MyApp.getInitialProps = async (nextPageContext: NextPageContext) => {
  const req = nextPageContext as unknown as any).req
  return {
    pageProps: {
      oktaURL: req && createOktaUrlFor(req),
      env: {
        PAGE_TITLE_PREFIX: process.env.PAGE_TITLE_PREFIX,
      },
    }
  }
}

2 Replies

Avatar
Oak rough bulletgall waspOP
I thought this was working, but unfortunately it runs one time, does everything correctly, then it re-runs on the client does not have a req property and thus cannot construct the URL, and also does not have access to process.env ... I was assuming this going to run server side, build the object, and then when it re-runs client side it would basically be merging the props from the server with the props with the client.. but, no, it wipes out everything, so when a component actually gets pageProps it's { oktaUrl: null, env: { PAGE_TITLE_PREFIX: null } }

So... Then I am like--- what is the point of this function? Why is this running something on the server AND the client if you can't merge the state between the two? How is this intended to be used?

How am I supposed to accomplish the simple task of having global props available to all components?
Avatar
American Fuzzy Lop
getInitialProps has largely been replaced by new APIs. See here https://nextjs.org/blog/next-9-3#next-gen-static-site-generation-ssg-support