disabling next.js server side rendering to prevent window is undefined errors

Viewed 3180

I have a private NPM package that I maintain, which I use in a Next.js project. Both projects are React, Typescript projects.

I've recently added a graph into the NPM project and have now run into the problem of; all the calls to window within that NPM package throw an error window is undefined within the Next.js project

As I'm using a library, that I don't have control over, to build my graph, I don't have the luxury of wrapping the calls to window in some sort of if (typeof window !== "undefined") statement.

I get these errors on build of my Next.js project, before I've even made a call to a component that makes use of the graphing library. Simply including my NPM package in my main project results in these errors arising.

Would it be possible to stop server-side rendering just for that particular graphing library or perhaps my entire NPM package?

Alternatively any other solution would be welcome, however wild.

2 Answers

Given the constrain you mentioned. I don't think there are much options. You simply don't have window object in node environment.

You can render other parts of the page where SSR is possible. and you can dynamically render with ssr: false for the portion where you cannot SSR due to window object.

import dynamic from 'next/dynamic'

// wrap your component that uses the graph lib.
const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/myGraphComponent'),
  { ssr: false }
)

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  )
}

Reference:

https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr

Maybe you can try dynamic import your graph import

Related