I'm trying to integrate amplitude-js with React and Gatsby. Everything looks good when doing gatsby developer since it's happening inside the browser, but when I try gatsby build I get the following error because Gatsby build is happening on the server where we don't have window object:
WebpackError: window is not defined
amplitude.js:2428 ~/amplitude-js/amplitude.js:2428:2
Here is my amplitude module:
import amplitude from 'amplitude-js';
amplitude.getInstance().init('API-KEY', null, {
// optional configuration options
saveEvents: true,
includeUtm: true,
includeReferrer: true,
});
Gatsby build is not working: window is not defined.
If if I'm not using this part anywhere in a project error is pointing to this part:
if (windowLocalStorageAvailable()) {
localStorage = window.localStorage;
} else if (window.globalStorage) { // <- here
// Firefox 2-3 use globalStorage
// See https://developer.mozilla.org/en/dom/storage#globalStorage
try {
This error happens because Amplitude JS SDK expects to be inside browser window object and have access to window context to collect properties like IP address, OS, Browser, device_id from the cookie, etc from it.
Does your app any type of backend you could sent events from?
To send data to Amplitude you are not required to use Amplitude SDK you have REST endpoint as well. https://help.amplitude.com/hc/en-us/articles/360032842391-HTTP-API-V2
HTTP API also has 3rd party maintained nodejs wrapper https://github.com/crookedneighbor/amplitude