window is not defined angular universal third library

referenceerror: window is not defined angular 6
referenceerror: event is not defined angular universal
angular universal medium
jasmine referenceerror: window is not defined
window, document, 'hammer referenceerror: window is not defined
angular universal cli
window is not defined angularjs
angular universal deployment

I am working with the library ng2-mqtt and I used it im my component like this:

 import 'ng2-mqtt/mqttws31.js';
declare var Paho: any;

Now I am getting following error:

ReferenceError: window is not defined
    at Object.<anonymous> (/Users/Picchu/Documents/em3/node_modules/ng2-mqtt/mqttws31.js:2143:4)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/Picchu/Documents/em3/dist/server.js:18707:18)

How can I fix this issue?

One possible way to avoid server error is not to render the component(if it is an option) that uses window. Something like:

<ng-container *ngIf="isBrowser">
   <!-- mqttws31-component -->
   <mqttws31-component></mqttws31-component> 
</ng-container>

The isBrowser can be imported from(ng2)

import { isBrowser } from 'angular2-universal';

Or if ng4+, you can also define this in your browser module:

// app.browser
@NgModule({
  providers: [
    { provide: 'isBrowser', useValue: true }
  ]
})

then inject from constructor

export class SomeComponent implements OnInit {
  constructor(@Inject('isBrowser') private isBrowser: boolean)
  ngOnInit() { 
    // example usage, this could be anywhere in this Component of course
    if (this.isBrowser) { 
      alert('we're in the browser!');
    }
}

How to fix “ReferenceError: window is not defined” error in angular 6 , And when you use window in your client side (or maybe in a 3rd party library that doesn't support Angular Universal) you get that error. So, first of  "window is not defined" came from 3rd party library which accessing window variable. SSR - Angular Universal - window is not defined #62. Closed

UPDATE

Extending Leon Li's answer, we can avoid loading components that cannot be rendered on server side if it requires Browser APIs like location or window.

This answer explains how to use

import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';

constructor( @Inject(PLATFORM_ID) platformId: Object) {
  this.isBrowser = isPlatformBrowser(platformId);
}

Just inject PLATFORM_ID into your service, and pass it to isPlatformBrowser or isPlatformServerto get a Boolean value. Accordingly you can show/hide the components that cannot be rendered on server if they depend on Browser APIs.

Angular 9: Window is not defined · Issue #1523 · angular/universal , Successfully merging a pull request may close this issue. None yet. 3 participants​. @BruneXX · @yazan-mehrez · @MDzyga. But as this is part of the native DOM api, it does not exist in Node. In Angular >= 6.1.0, Angular Universal uses domino as an implementation of the DOM in Node, and the nativeElement property of ElementRef exposes the domino implementation of HTMLElement.

Angular 6 In server.ts use:

const domino = require('domino');
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync('dist/browser/index.html').toString();
const win = domino.createWindow(template);

global['window'] = win;
global['document'] = win.document;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;

How to use ng-flexmonster with Angular Universal?, Angular Universal is a technology which allows you to create Angular apps globals will throw an error - 'window is not defined', 'document is not defined' etc​… JavaScript within a third party library may throw errors due to  It looks like a third party library causing issues, you'll have to start by going to that line in the server.js bundle and try to investigate which library is causing it. From there you'll have to use Webpack to swap that library out for a blank or mocked version for the server render. Let us know!

window shouldn't be used in universal applications on server side, because Node.js doesn't have window, and having a dummy global.window currently affects the way Angular detects global variable.

If the package uses window, an issue can be opened in its repository and/or it can be forked and changed to not use window.

Since packages that rely on window often rely on things that are specific to client side, they won't work as expected on server side even if this issue is sorted out.

Package description says:

Depends on the library from: https://eclipse.org/paho/clients/js/

While library description says:

The Paho JavaScript Client is an MQTT browser-based client library written in Javascript that uses WebSockets to connect to an MQTT Broker.

Usually third-party Angular module that isn't supposed to work as expected on server side should be stubbed or mocked; dummy module with fake directives and services is imported in app.server.ts instead of real module.

The biggest Angular Universal gotchas, and how to avoid them , Anyone working with angular 5.0-universal with Asp.net MVC 5.0 combination ? by *ngIf=ïsBrowser" but still i got "window is not defined" in 3rd party plugin. Bottom line : when i "import" library which is not universal compatible like  @sokra How do you exclude a library from prerendering?. Update I figured I shouldn’t import the library outside the class definition, but instead require it in the componentDidMount method or a called method thereof.

angular/universal, Angular universal window is not defined It may help to avoid exceptions from thirty party libraries which don't allow using them on server-side. on how to update Node.js. npm ERR! code ELIFECYCLE npm ERR! errno 3. This is a pitfall of using Universal and is well-defined. If you rely extensively on a library that uses globals like document, window, or other APIs without patching it yourself, you will experience errors. This is not something that we will be patching for you, it must be done on the user side.

Angular universal window is not defined, I gave alot of errors like KeyboardEvent is not defined, window is not defined, MouseEvent is not MDBootstrap Angular – Universal server side rendering errors You can fix problem with hammerJS by adding this library to whitelist in your @id90travel In my case it's working properly since I updated to the 5.2.3 version. The issue is basically what the title says, I am using ng-flexmonster v2.7.11 with Angular 7.0.3. Now I am trying to add server-side rendering(SSR) to my application.

MDBootstrap Angular – Universal server side rendering errors , [x] document is not defined and window is not defined - here; [x] Angular Material2 UI components - individual branch; [x] Primeng UI components - [​individual  Hello, I used html2canvas library for create screenshot based on selected area on page for bug tracking project built into CI. It's working well if only one jquery library exists from my application but it's not working while remote proj

Comments
  • You can run this part of the code selectively only in the browser by using isPlatformBrowser available in angular/common
  • With latest Angular version, we can use angular provided injectors instead of manually providing useValues. Provided my solution below.
  • Ok, I didn't really understand. Is there a way to solve this problem? Should I create a globa variable window within my node.js app and how and where should I do this?
  • See the last paragraph. It's applicable to your case. It totally depends on how the module is used in your app, i.e. how this module affects the page that is generated on server side. Also, consider opening an issue. It's vendor's responsibility to provide a module that won't cause an error in universal app.
  • I already opened the issue in the repo. I am using the module as client but the error is occuring on server side. I am not sure how I can solve this. However thanx for your help
  • Do not import ng2-mqtt module in server app. If its import results in Paho global variable (I guess it is), create dummy global.Paho variable in server app that stubs or mocks the behaviour that is expected from this module. And actually, I don't see anything that is specific to Angular in this module, even though it has ng2 prefix. It's just a library that exposes a global (that's why globals are bad).
  • The point is that Paho global shouldn't work, because real ng2-mqtt shouldn't be imported on server side. Instead, Paho global should be replaced with dummy implementation of the module. Because real ng2-mqtt won't work in Node.js.