loglevel-plugin-remote icon indicating copy to clipboard operation
loglevel-plugin-remote copied to clipboard

WebpackError: ReferenceError: window is not defined

Open webjay opened this issue 5 years ago • 5 comments

When building with GatsbyJS I get this error:

"window" is not available during server side rendering.

WebpackError: ReferenceError: window is not defined

Here's what Gatsby has to say about it: https://www.gatsbyjs.org/docs/debugging-html-builds/

I'd like to import:

import log from 'loglevel';
import remote from 'loglevel-plugin-remote';

but I need to do it like this:

const log = typeof window !== 'undefined' ? require('loglevel') : null;
const remote = typeof window !== 'undefined' ? require('loglevel-plugin-remote') : null;

webjay avatar Jun 25 '20 15:06 webjay

This has also been reported for loglevel pimterry/loglevel#146

webjay avatar Jun 25 '20 15:06 webjay

I noticed that this is not happening for loglevel so I closed pimterry/loglevel#146, but it is happening for loglevel-plugin-remote.

One way to debug:

Install gatsby-cli globally.

gatsby new gatsby-starter-default https://github.com/gatsbyjs/gatsby-starter-default
cd gatsby-starter-default
yarn add loglevel-plugin-remote

In src/pages/index.js add import 'loglevel-plugin-remote'; gatsby build

webjay avatar Jun 28 '20 12:06 webjay

const win = window;

if (!win) {
  throw new Error('Plugin for browser usage only');
}

https://github.com/kutuluk/loglevel-plugin-remote/blob/master/src/remote.js#L1-L5

Error in error code. But the result is correct - throw an exception in a non-browser environment.

kutuluk avatar Jul 01 '20 13:07 kutuluk

You should not connect the plugin during ssr or connect another plugin that will write logs directly to a file on the server.

kutuluk avatar Jul 01 '20 13:07 kutuluk

const remote = typeof window !== 'undefined' ? require('loglevel-plugin-remote') : null;

Thanks for raising this issue, the above code snippet provided by you helped me hack around the error in my Next.js app.

aman-godara-ria avatar Jun 20 '24 06:06 aman-godara-ria