Amplitude-JavaScript: ReferenceError: window is not defined

Trying to use amplitude-js on node 8.8.1

I got this error when I run: const amplitude = require('amplitude-js');

ReferenceError: window is not defined
    at /root/app/node_modules/amplitude-js/amplitude.js:2427:8
    at commonjsGlobal (/root/app/node_modules/amplitude-js/amplitude.js:2:82)
    at Object.<anonymous> (/root/app/node_modules/amplitude-js/amplitude.js:5:2)
    at Module._compile (module.js:612:30)
    at Object.Module._extensions..js (module.js:623:10)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)
    at Function.Module._load (module.js:486:3)
    at Module.require (module.js:556:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/root/app/src/helpers/amplitude.js:3:19)
    at Module._compile (module.js:612:30)
    at Object.Module._extensions..js (module.js:623:10)
    at Module.load (module.js:531:32)
    at tryModuleLoad (module.js:494:12)
    at Function.Module._load (module.js:486:3)
    at Module.require (module.js:556:17)
    at require (internal/module.js:11:18)
...

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 12
  • Comments: 19 (4 by maintainers)

Most upvoted comments

I have server side rendering and I simply require only when not in node. In node I mock it. isServer is my custom global variable

import config from "config";

const Amplitude = !global.isServer ? require("amplitude-js") : null;

const instance = Amplitude ? Amplitude.getInstance() : {
  init: () => {},
  logEvent: () => {},
  setUserId: () => {},
  setUserProperties: () => {}
};

instance.init(config.amplitude.apiKey);

export default instance;

I have a case that I don’t need amplitude to work, but I need to require it, can you make a way that it just doesn’t do anything on the node case, instead of blowing up?

On this answer, you can use process.browser instead of !global.isServer

I have server side rendering and I simply require only when not in node. In node I mock it. isServer is my custom global variable

import config from "config";

const Amplitude = !global.isServer ? require("amplitude-js") : null;

const instance = Amplitude ? Amplitude.getInstance() : {
  init: () => {},
  logEvent: () => {},
  setUserId: () => {},
  setUserProperties: () => {}
};

instance.init(config.amplitude.apiKey);

export default instance;

I’m having this problem still with my node express server. Some events cannot be logged on the client. Any chance this will be fixed?