1

I thought checking for if (typeof window === 'undefined') would remove the if clause and its contents in a Next.js production build in the client bundle? Has this been changed somehow in Next.js 11 or 12 or Webpack 5?

The next-code-elimination tool doesn't do it, but perhaps that tool is just not supporting getInitialProps anymore, only getServerSideProps? Or is the actual production build also not supporting dead code elimination in getInitialProps anymore?

Any pointers appreciated... (I found this bug report but it's pretty old and closed, and the 2017 blog post SSR and Server Only Modules, which doesn't mention typeof window checking).

Minimal reproducible example:

export const Content = () => {
  return <h1>hello</h1>
}

Content.getInitialProps = async () => {
  if (typeof window === 'undefined') {
    const article = await 'foo'
    return 'server'
  }
}

The problem seems to be the await keyword! But even if I move the async stuff out to a helper function and don't use await inside getInitialProps, if the helper function contains moderately complex code, webpack seems to inline it and we're back to step one.

mb21
  • 34,845
  • 8
  • 116
  • 142
  • Only `getServerSideProps`/`getStaticProps`'s code is eliminated from the client bundle, as they are fully server-side code. `getInitialProps` code runs both on the client and server, and as such Next.js code elimination isn't applied to it. See slightly related question: [Import a library only on the server side to use in getInitialProps](https://stackoverflow.com/a/71229074/1870780). – juliomalves Mar 10 '22 at 22:53
  • 1
    My experiments showed that some code is actually removed in getInitialProps as well (e.g. non-async code wrapped in `if (typeof window === 'undefined')` for example). I think I managed to solve my issue by using a dynamic import (`const myModule = await import('mymodule')`) inside that `if` block. This causes webpack to break that module out in its own chunk. The chunk is still generated for the client, but never actually loaded. – mb21 Mar 12 '22 at 08:56

0 Answers0