kutuluk / loglevel-plugin-remote

A loglevel plugin for sending browser logs to a server
MIT License
102 stars 36 forks source link

WebpackError: ReferenceError: window is not defined #28

Open webjay opened 4 years ago

webjay commented 4 years ago

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 commented 4 years ago

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

webjay commented 4 years ago

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

kutuluk commented 4 years ago
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 commented 4 years ago

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

aman-godara-ria commented 2 months ago

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.