'Import NPM package only for server side rendering(SSR) in Next.js App

I am trying to use one private NPM module only when the page is loading for the first time and rendering is happening on the server. I am using the following piece of code but I am still able to see my package in chunks in client.html using the build analyzer.

  if (typeof window === 'undefined') {
    const content = await import('@abc/my-npm-package');
    return conent(payload);
  } else {
    return null;
  }


Solution 1:[1]

Excellent question, I've poked around the Next.js's code and found out that in order to code that will be exists only on the server you need to use some variable which is passed to webpack.DefinePlugin (which at build time will replace the usage with the value, this what allows the tree-shake to work).

From this line, there is a special variable process.browser which will be true only in the browser.

Change your code to

if (!process.browser) {
  const content = await import('@abc/my-npm-package');
  return conent(payload);
} else {
  return null;
}

Update 16.03.2022

Next.js will deprecate process.browser soon, the new recommended way to distinguish between client & server is by checking type of window === 'undefined' // means that it's server side.

 if (typeof window === 'undefined') { // server side
    const content = await import('@abc/my-npm-package');
    return content(payload);
  } else { // client side
    return null;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1