Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReferenceError: window is not defined #121

Open
hnhatr opened this issue Sep 28, 2017 · 58 comments
Open

ReferenceError: window is not defined #121

hnhatr opened this issue Sep 28, 2017 · 58 comments

Comments

@hnhatr
Copy link

hnhatr commented Sep 28, 2017

From the latest version, server-side rendering produces following issue

ReferenceError: window is not defined
at C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:150552
at C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:150507
at e.exports (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:151009)
at Object. (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:146201)
at t (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:377)
at Object.defineProperty.value (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:41330)
at t (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:377)
at Object.defineProperty.value (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:39991)
at t (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:377)
at t.exports (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:734)
at C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:744
at n (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:81)
at Object. (C:\Users\hnhatr\Downloads\reactGo-master\node_modules\react-json-view\dist\main.js:1:253)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Object. (C:\Users\hnhatr\Downloads\reactGo-master\compiled\webpack:\external "react-json-view":1:1)
at webpack_require (C:\Users\hnhatr\Downloads\reactGo-master\compiled\webpack:\webpack\bootstrap deda87cb735796675547:19:1)

help me please !!!

@mac-s-g
Copy link
Owner

mac-s-g commented Sep 29, 2017

i haven't tested ssr. i'll take a look as soon as i get a chance.

@mac-s-g
Copy link
Owner

mac-s-g commented Oct 1, 2017

@hnhatr i'm having trouble reproducing the error. The error output you posted comes from the uglified and minified build, so it's tough to see where window is being referenced.

I know the issue is coming from a dependency, because window is not referenced in my src/ directory. I could try to track down what dependency is causing the issue.

can you tell me more about what tools & config you're using for server-side rendering?

is there a github link that will give me some more info about your build?

@mac-s-g
Copy link
Owner

mac-s-g commented Oct 1, 2017

also, @hnhatr , it looks like you're not the only one running into "window is not defined" issues when using server-side rendering.

a google search shows quite a bit of people running into the same issue.

there should be tools to emulate the window global on the server. here is an example of someone solving the problem by faking a window variable. I also believe there are plugins for ssr that initialize a global window object.

@Rid
Copy link

Rid commented Oct 19, 2017

I'm having the same issue, none of the hacks seem to work as the plugin is loaded using webpack before the global can be set.

I believe the included lib with is causing the issue is:
https://github.com/zenorocha/clipboard.js/blob/a55c9ac513da6e6d01dfd6ceed9a930c596cf7e4/src/clipboard-action.js#L141

@indolent-developer
Copy link

This is due to style loader. module of webpack. webpack-contrib/style-loader#272 (comment).

I guess we have to use different style loader if you want to support server side rendering. Do you support server side rendering ?

@rajoriav
Copy link

I am seeing this as well, any leads anyone?

@indolent-developer
Copy link

@Alchemist-V are you using server side rendering? if yes can you disable it if not then you should use different style loader.
something similar to https://github.com/kriasoft/isomorphic-style-loader

@Rid
Copy link

Rid commented Dec 15, 2017

@indolent-developer have you got this working with SSR? If so could you point me to a working fork/pull req?

@indolent-developer
Copy link

@Rid I was able to work this via disabling server side rendering of this component. No fork or pull.

@rajoriav
Copy link

rajoriav commented Dec 18, 2017

@indolent-developer I got it working by trying to load the component lazily. Something like this:

var ReactJson = null; class JsonEditor extends React.Component{ constructor() { super(); } componentDidMount() { require.ensure(['react-json-view'], function() { try { ReactJson = require('react-json-view').default; } catch(err) { console.log('react-json-view:', err); } }) } render () { return ( { ReactJson == null ? "Unable to load content": <ReactJson src={context} onEdit={this.onEdit.bind(this)} /> } ) }
Any concerns or feedback?

@indolent-developer
Copy link

@Alchemist-V looks fine to be.

We do need a longterm solution for this though. A PR from some one. What does author have to say ? I am currently tied up :(

@Rid
Copy link

Rid commented Dec 20, 2017

@Alchemist-V I can confirm it's working, thanks! I think a fork/pull req using isomorphic-style-loader is better but I don't have time to test right now

@mac-s-g
Copy link
Owner

mac-s-g commented Dec 20, 2017

I'm totally cool with swapping out the loaders if that fixes the issue. anyone want to post a PR? I'm happy to test, merge, and publish.

@indolent-developer
Copy link

i can try in few weeks currently tied up.

@rajoriav
Copy link

Thanks @Rid ! Let me see if i can file a PR for this. Hope the above hack works for all in the mean time.

@mansdahlstrom1
Copy link

Is there any updates on this ?

@charlieprynn
Copy link

I'm also interested in this.

@janouser11
Copy link

Same^

@janouser11
Copy link

janouser11 commented Jun 12, 2018

Last week I had this working perfectly fine, after restarting project I only get a window is not defined error. Any suggestions?

Thanks

P.S. The hack above worked, but not ideal

@gptguy
Copy link

gptguy commented Jun 30, 2018

Checkout:
NextJs Loading Components Dynamically

@xuchen81
Copy link

Same error.

@tomkiss
Copy link

tomkiss commented Nov 5, 2018

Same error here.

@johnking
Copy link

johnking commented Nov 7, 2018

I am using it with Gatsby, and get the same error.

@johnking
Copy link

johnking commented Nov 7, 2018

one note: the hack code does not work for my case.

@johnking
Copy link

johnking commented Nov 7, 2018

My workaround has two parts:

  1. use conditional rendering in your component like the code snippet below
<div>
  { typeof window !== 'undefined' && ReactJsonViewt &&  <ReactJsonView  />}
</div>
  1. Modify your webpack config to avoid loading the react-json-view during stage build-html, something like below:
  // workaround for using react-json-view
  if (stage === 'build-html') {
    // console.log('inside build-html ...');
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /react-json-view/,
            use: loaders.null(),
          },
        ],
      },
    });
  }

@chetanism
Copy link

Here's my solution using dynamic import (inspired by @alexandre-lelain ), just leaving it here if it helps:

function useReactJsonView() {
  const [ReactJson, setReactJsonView] = React.useState('div');
  if (typeof window !== 'undefined') {
    import('react-json-view').then((jsonView) => {
      setReactJsonView(jsonView);
    });
  }
  return ReactJson;
}

// Then in you component
function SomeComponent() {
  const ReactJson = useReactJsonView();
  return (
    <ReactJson.default src={jsonData} />
  );
}

@panyamred
Copy link

For users using nextjs, you can use next/dynamic for this case
const DynamicReactJson = dynamic(import('react-json-view'), { ssr: false });

return your json view with data like
<DynamicReactJson src={yourData}

import dynamic from "next/dynamic";

const DynamicReactJson = dynamic(import('react-json-view'), { ssr: false });

This solved the issue.

@arifszn
Copy link

arifszn commented Sep 28, 2020

Confirming this issue while production building in Docusaurus v2. Not recommending with Docusaurus.

@slorber
Copy link

slorber commented Sep 28, 2020

@arifszn I'm the current lead maintainer of Docusaurus and you should just do something similar to what I did here: #121 (comment)

I wouldn't say this lib is not recommended for Docusaurus, but as any lib without proper SSR support, we have to work around the lack of SSR support.

@arifszn
Copy link

arifszn commented Sep 28, 2020

@slorber I tried using react-json-inspector as an alternative but same error occurred. Then switched to react-json-tree and it is running perfectly without any hack. I would recommend react-json-tree for Docusaurus.

Running Example is here: https://arifszn.github.io/reddit-image-fetcher/docs/#example

@slorber
Copy link

slorber commented Sep 28, 2020

This is not really a "hack", it's just rendering it only on the client, which is a technique you should have in your bag as a React developer. I mean, you shouldn't dismiss a lib just for lack of SSR support, particularly for things like json trees for which SEO does not matter much.

Here's also a working version of this lib in Docusaurus: https://v2.docusaurus.io/__docusaurus/debug/

I agree that react-json-tree looks nice and is probably easier to integrate with Docusaurus (or Gatsby or NextJS), but that should not be the only thing to consider when making a choice.

@correiamp
Copy link

@thomasjm and @justinmchase, first of all, thank you for your amazing work!
Just wondering, relative to this #298, do you guys have an ETA to go live?

@thomasjm
Copy link
Contributor

thomasjm commented Oct 6, 2020

@correiamp I think it just needs some review. If people could try it out and chime in that it works and doesn't mess anything up visually, hopefully we can get it merged. (Last I checked this project was only semi-maintained.)

You can stick the following in your package.json:

"react-json-view": "git+https://github.com/thomasjm/react-json-view.git#e9baddc761536929f436e93baa5cebc5be519417"

@justinmchase
Copy link

@correiamp I'm not a developer on this project but I would recommend everyone go to the PR (#298) and vote there because the developers appear to be simply unaware of the PR completely. If they were to see enough votes they may be inclined to merge it.

@correiamp
Copy link

@thomasjm and @justinmchase sorry the late reply.
I've tested as you suggested and worked smoothly :)

Going to add this feedback to the PR

@vongohren
Copy link

@correiamp I think it just needs some review. If people could try it out and chime in that it works and doesn't mess anything up visually, hopefully we can get it merged. (Last I checked this project was only semi-maintained.)

You can stick the following in your package.json:

"react-json-view": "git+https://github.com/thomasjm/react-json-view.git#e9baddc761536929f436e93baa5cebc5be519417"

@thomasjm Im using your package version on SSR side. But when using it as the simples demo example showcase, I get an empty object back, and it fails my render. I wonder why as I cannot find anything in the docs pointing to renderJson should return an empty object.

@thomasjm
Copy link
Contributor

@vongohren I'm not sure, but there's been a bunch of commits on master branch since my PR was merged--I'd recommend trying the latest first.

@vongohren
Copy link

Nothing helped, so skipping this lib

@jjoker0110
Copy link

I'm also getting a similar error, it works right after restarting the develop local server but any time after it fails with this message:

Failed to Server Render (SSR)
Error message:
document is not defined

File:
node_modules/react-json-view/dist/main.js:1:81149

I'm using this with Gatsby.js

@marlonguimaraes
Copy link

I got around using this:

export const BrowserOnlyReactJson = (props) => {
  if (typeof window === 'undefined') {
    return null;
  }
  const ReactJson = require('react-json-view').default;
  return <ReactJson {...props} />;
};

@marlonguimaraes
Copy link

marlonguimaraes commented Aug 23, 2021

If you're using Next.js, you can use Dynamic Imports:

import dynamic from 'next/dynamic';

const BrowserReactJsonView = dynamic(() => import('react-json-view'), {
  ssr: false,
});

function Page() {
  const obj = {
    obj: 'example'
  }
  
  return (
    <div>
      <BrowserReactJsonView src={obj} />
    </div>
  );
}

@jjoker0110
Copy link

jjoker0110 commented Aug 25, 2021

export const BrowserOnlyReactJson = (props) => {
  if (typeof window === 'undefined') {
    return null;
  }
  const ReactJson = require('react-json-view').default;
  return <ReactJson {...props} />;
};

This worked for me using Gatsby.js, thank you @marlonguimaraes !

rahulsivalenka added a commit to rahulsivalenka/ui-meetup-mui-styling that referenced this issue Oct 20, 2021
Problem was with SSR during gatsby build

Solution was to check if it is browser before importing and rendering react-json-view

Refs:
mac-s-g/react-json-view#121 (comment)

https://stackoverflow.com/a/32598826
@himself65
Copy link

see https://github.com/TexteaInc/json-viewer

@slorber
Copy link

slorber commented Oct 26, 2022

export const BrowserOnlyReactJson = (props) => {
  if (typeof window === 'undefined') {
    return null;
  }
  const ReactJson = require('react-json-view').default;
  return <ReactJson {...props} />;
};

This worked for me using Gatsby.js, thank you @marlonguimaraes !

This can cause hydration issues because the JSX rendered on the server/client is not exactly the same. React 18 will likely emit an hydration error BTW.

@cube-dan
Copy link

cube-dan commented Apr 6, 2023

Thanks for the hot tip @himself65! Works perfect with Next.js SSR.

@janwirth
Copy link

I like to wrap it in this component:

import { useEffect, useState } from "react";

interface Props {
  fallback?: JSX.Element; // JSX.Element
}

export const NoSSR = ({
  children,
  fallback,
}: React.PropsWithChildren<Props>): JSX.Element => {
  const [mounted, setMounted] = useState(false);

  useEffect(() => setMounted(true), []);

  if (!mounted) {
    return fallback || <></>;
  }

  return children as JSX.Element;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.