storybookjs / react-inspector

🔍 Power of Browser DevTools inspectors right inside your React app
https://5d8cb665bc622e0020296079-dippbxxgcq.chromatic.com/
MIT License
769 stars 95 forks source link

[Bug] window is not defined on startup, when using NextJS #149

Closed tinybitsofcode closed 2 years ago

tinybitsofcode commented 2 years ago

Describe the bug

Trying to integrate the Inspector with the latest NextJS, will prompt the ReferenceError: window is not defined error, with minimal configuration of react-inspector.

Steps to reproduce the behavior

  1. Go to https://nextjs.org/docs, create a new NextJS app (using npx create-next-app@latest)
  2. In the new project, install the latest react-inspector (using npm install react-inspector)
  3. Open the pages/index.js file, type the <Inspector data={[]} /> somewhere in the body of the file (in the React component > render function)
  4. Run the NextJS project (npm run dev)
  5. Open the browser, go to http://localhost:3000 and the error should be prompted

Expected behavior

The Inspector should correctly show the data passed through, and allow the application to start.

Screenshots and/or logs

image

Environment

Additional context

Below is the full stacktrace of the error.

1 of 1 unhandled error
Server Error
ReferenceError: window is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
Object.isNode [as default]
file:///C:/Dev/my-app/node_modules/is-dom/index.js (5:35)
Inspector
file:///C:/Dev/my-app/node_modules/react-inspector/dist/cjs/react-inspector.js (2241:32)
processChild
file:///C:/Dev/my-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (3353:14)
resolve
file:///C:/Dev/my-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (3270:5)
ReactDOMServerRenderer.render
file:///C:/Dev/my-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (3753:22)
ReactDOMServerRenderer.read
file:///C:/Dev/my-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (3690:29)
Object.renderToString
file:///C:/Dev/my-app/node_modules/react-dom/cjs/react-dom-server.node.development.js (4298:27)
Object.renderPage
file:///C:/Dev/my-app/node_modules/next/dist/server/render.js (751:45)
Object.defaultGetInitialProps
file:///C:/Dev/my-app/node_modules/next/dist/server/render.js (389:51)
Function.getInitialProps
node_modules\next\dist\pages\_document.js (145:19)
luminaxster commented 2 years ago

Yep, been there. Next automatically supports SSR, and isDOM ( used here import {isNode as isDOM} from './utils/typeUtils';) breaks SSR for React Inspector, try code splitting to avoid the SSR phase:

let ReactInspector = null;
//inside a useEffect, or useSWR hook, or via next/dynamic
ReactInspector = import('react-inspector');