reaviz / reagraph

🕸 WebGL Graph Visualizations for React. Maintained by @goodcodeus.

Home Page:https://reagraph.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ReferenceError: window is not defined - NextJS

iAMkVIN-S opened this issue · comments

Describe the bug

When attempting to use reagraph with nextjs 14.1.0 I am getting error window is not defined

I understand this normally suggests that a client element is trying to load on a server component.
For this reason, I thought I added enough checks, but to no avail. Is this package inherently incompatible with NextJS?

'use client'

// modules
import { GraphCanvas } from 'reagraph'

const isClient = typeof window !== 'undefined';

export default function ServersContent() {

const nodes = [
  {
      id: '1',
      label: '1'
    },
    {
      id: '2',
      label: '2'
    }
  ];
  
  const edges = [
    {
      source: '1',
      target: '2',
      id: '1-2',
      label: '1-2'
    },
    {
      source: '2',
      target: '1',
      id: '2-1',
      label: '2-1'
    }
  ];
  
  return (
    <div>
      {isClient && GraphCanvas && <GraphCanvas nodes={nodes} edges={edges} />}
    </div>
  );
}

Steps to Reproduce the Bug or Issue

  1. Using a use client NextJS client component
  2. Integrate the reagraph Basic Getting Started
  3. npm run dev
  4. Get error ReferenceError: window is not defined - NextJS
image

Expected behavior

Expecting the Getting Started Graph
image

Platform

  • Reagraph Version: 4.15.6
  • OS: macOS
  • Browser: Chrome
  • NodeJS version: v18.19.0

I had a lot of trouble figuring it out. Along with "use client" on top what worked for me was:

on pages/index.tsx

const Graph = dynamic(
  import("@/components/Graph/Graph").then((mod) => mod.Graph),
  { ssr: false }
);

on graph.tsx

 const [isBrowser, setIsBrowser] = useState(false);
useEffect(() => {
    if (typeof window !== "undefined") {
      setIsBrowser(true);
    }
  }, []);

if (!isBrowser) {
    return <></>;
  }

return (
     <div
        style={{
          position: "relative",
          width: "99vw",
          height: "90vh",
          borderWidth: 1,
        }}
        id="graph-canvas-container"
        className="border-black border-1"
      >
        <GraphCanvas
            ref={graphContext.graphRef}
    .......

    </div>

@thobhanifreddy I appreciate the reply very much.

Can you provide the full pages/index.tsx and graph.tsx ? I can't seem to make it work.

Additionnally, I'm using the App Router of NextJS, you seem to be on the Page Router. I wonder how that could be impactful. Are you also on nextjs 14.1.0 ?

Cheers

Hey Austin @amcdnl 👋

Thank you so much for attempting to add further support for NextJS!

I noticed you pushed a commit yesterday. If it helps, I noticed that I'm able to make it work when scaling back down to NextJS 13.5.x but get the undefined window errors on 14.x (the current LTS)

The last bit to get this working is update reakeys off mouse trap - ref reaviz/reakeys#29

The last bit to get this working is update reakeys off mouse trap - ref reaviz/reakeys#29

Very cool!

I don't believe I saw anything in the documentation, but is there a temporary workaround prop where we could already disable the keyboard shortcuts?

@iAMkVIN-S - Unfortantly not since this is a compile time issue.

I have just started a fresh NextJS 14 project and I am having the same issue above, and I'm unable to solve it using the soln provided above probably because of the different NextJS versions. From what I am getting from this thread, NextJS 14 is currently not supported by this library, but it will be updated soon in the meantime there is currently no workaround other than downgrading the NextJS version correct? This library looks so good I will definitely wait for the time when version 14 is supported. Could you provide a time estimate in which this will be done?

@stephen-ip - Planning to have solved in the next week to two. If you need this faster, we have proffesional support options or we are happy to accept a PR for the fix.

This should be solved now. Please try again on latest.

@amcdnl I'm running nextjs 14.1.0 with "reagraph": "^4.17.0" and I'm getting: Error in worker registerModule call: window is not defined

This is my code (when uncommenting dynamic import errors are gone but nothing shows on the screen - canvas is missing):

'use client'
import { GraphCanvas } from 'reagraph'

// const GraphCanvas = dynamic(
//   import('reagraph').then((mod) => mod.GraphCanvas),
//   { ssr: false },
// )

const nodes = [
  {
    id: '1',
    label: '1',
  },
  {
    id: '2',
    label: '2',
  },
]

const edges = [
  {
    source: '1',
    target: '2',
    id: '1-2',
    label: '1-2',
  },
  {
    source: '2',
    target: '1',
    id: '2-1',
    label: '2-1',
  },
]

function ComputeGraphCanvas() {
  return <GraphCanvas nodes={nodes} edges={edges} />
}

export default ComputeGraphCanvas

@avalanche-tm did you find a workaround?

@gkorland unfortunately no. I decided to move on with cytoscape.js

@avalanche-tm - Is this still an issue? Can you try latest because I thought we fixed this.

@amcdnl I didn't get any notification there was a bugfix. Anyway, there were other bugs (performance issues) with this library and I had to move fast so I decided to use other library. Sorry :/

@avalanche-tm - Is this still an issue? Can you try latest because I thought we fixed this.

@avalanche-tm yes it's still happening.
@Anchel123 can you please post the error you got?

@avalanche-tm - Is this still an issue? Can you try latest because I thought we fixed this.

@avalanche-tm yes it's still happening. @Anchel123 can you please post the error you got?

ReferenceError: document is not defined
at webpack_require (/home/anchel/Desktop/falkordb/falkordb-browser/.next/server/webpack-runtime.js:33:43)
at eval (./app/graph/GraphView.tsx:13:66)
at (ssr)/./app/graph/GraphView.tsx (/home/anchel/Desktop/falkordb/falkordb-browser/.next/server/app/graph/page.js:217:1)
at webpack_require (/home/anchel/Desktop/falkordb/falkordb-browser/.next/server/webpack-runtime.js:33:43)

Seeing similar issues here too on Next 14.2.3.

Reakeys

Based on my investigation, one of the issues stems from reakeys using client only global objects without checking for their existence. This makes sense pre SSR era.

It seems this is the culprit for the SSR issue on the reakeys side: https://github.com/search?q=repo%3Areaviz%2Freakeys%20navigator&type=code

Strangely enough though, in the built package for reakeys, there is an if block around the usage of navigator. Though this still seems to fail?

Reagraph

I believe that Reagraph itself has a similar issue but with document.

Any use of this function outside of a React Lifecycle hook will cause an error also.

Lazy Importing

A temporary solution should be dynamic imports in Next. Ref: https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading - Turning off SSR for these imported modules. This will allow for builds to complete and the runtime to work, but you will still receive error logs about these global client side variables.

ran into this issue with next.js as well. i can get it working most of the way, but it fails when i try to set it to darkmode.

const GraphCanvas = dynamic(
  () => import("reagraph").then((mod) => mod.GraphCanvas),
  { ssr: false }
);
...
return(
        <div className="fixed w-1/2 h-3/4">
          <GraphCanvas
            nodes={data.nodes}
            edges={data.links}
            onNodeClick={nodeClicked}
            labelType="all"
            draggable
            // theme={darkTheme}
          />
        </div>
);
...

the code above works until i uncomment the darkmode.

Edit: by the way, it works on dev but fails at build time with a ReferenceError: document is not defined