-
Notifications
You must be signed in to change notification settings - Fork 483
"Window is not defined" even when isPlatformBrowser used. #1675
Comments
OK - further experimentation. If you have your own module that you are loading into an angular-universal (9) project and that module references a third party angular module, which in turn references a non-angular module that expects browser features, you will get errors about trying to access those features. Here are two example npm modules that cause this issue: It doesn't matter if you even use the contents of those modules - merely importing them into one of your local modules will cause the server to throw errors as soon as your local module is first encountered server side (even if lazily loaded). ...so isPlatformBrowser can't help. So what do we do in these situations? I'm only using browser features in the browser but merely including these modules breaks SSR. |
If you use this:
(note, must appear prior to This will work in some cases but really just kicks the can down the road. For example, with our above modules that reference external 'browser only' modules, this solution will get past that error for ngx-masonry, but will still fail with ng2-pdf-viewer because it will try to find the I guess you could just mock your way to freedom but I'd hope there's some way we can avoid faults for importing modules where the offending code isn't even executed. |
After speaking with the author of So what are we supposed to do in this case? It seems like no matter how you guard against it the error will be thrown for SSR merely by importing the module no matter who's guarding against it. |
I'm inclined to believe one of two things: either it's a change in configuration that @alan-agius4 maybe can speak to, or it's an issue with the Angular CLI since they handle the actual compilation for SSR. I'll leave it to him to follow up. |
@CaerusKaru @jasonburrows hey guys, is there an update on this issue? I have been struggling with it for the past few days |
@alan-agius4 bro... |
Nope. Essentially it breaks multi platform support in angular and makes using ‘isPlatformBrowser’ a waste of time that accomplished nothing. I eventually got past it by literally mocking out every single call that anything I use uses (even had to do it for libs used by libs I use). Amazing waste of time, total hack, and the fact this totally breaking change hasn’t been even really looked at makes my lose confidence in Angular. I won’t be selecting it for future projects. |
@jasonburrows yeah it is a big pain, thanks anyway |
@jasonburrows hey man would you please give me a hint on how you did the mocking of the window object even for third party libs. |
Sure - so since part of the problem is that it triggers the error on module load (rather than on use), just make sure all your modules get loaded - like don’t lazy load or if you do, trigger the load of those modules manually in the browser. This at least means it isn’t that hard to ensure you get all the problems. Next, I use Domino to provide implementations where it provides them. Finally, you will get errors about further missing functions (or whatever is missing). Make note of the name and then look up the proper signature. Implement it, add it to the object that needs it (“window” for example). For functions that return real values, I did my best to return values that wouldn’t cause any problems. On the plus side, it doesn’t seem like these functions actually get executed so I doubt what you return matters (but don’t get me wrong, I’m not really comfortable about this part). Doing all that I’ve had my application up and running with no issues (from what I can tell). If you get stuck let me know - I ran into a few gotchas along the way but don’t remember them all here. It wasn’t actually that time consuming as fortunately there were only a few things that I needed to mock, but I’m still not confident about having to have done it at all. Good luck - let me know how it goes and I’ll try to help if you run into something. ...I’m on my phone right now but if you need it I can post some code to clear it up when I’m back at a workstation. |
@jasonburrows thank you so much. So maybe you could spot something on my server.ts file regarding the usage of domino.
Despite having the above configuration, I still get the error as below: |
@jasonburrows what version is your Angular project? |
@Teebo Angular version is 9.1.5. I don't see anything obvious in your server.ts file although I'm using I'm not saying any of that should make a difference but they are the only obvious differences I see for what we are doing. I'm also not doing anything that is the equivalent of your:
If the error you are getting now is related to instance creation I don't think it is the same problem as, in theory, instance creation can still be guarded with That being said I haven't personally encountered any situation where I could import something that requires it be in a browser at all (without my mock hacks). I may not be fully understanding your situation though - the error you provide is server side - why are you creating an instance of |
@jasonburrows thanks, I am wrapping the editor.js code within the isPlatformBrowser, thank you for the points you have raised |
@jasonburrows It is definitely a very painful thing not to find a simple solution to something so obvious. |
@danielptlr below is how I did it, albeit it does not work, maybe it might work for you.
|
@Teebo This doesn't work for me either, apparently for now the only way to use incompatible third party libraries is by editing the code from the same library, this is obviously bad practice. Since in future updates we will have problems, but to solve it momentarily it is a good option. |
Here's the part of mine that deals with it. In my example I use
This solved the issue. (Nothing after that is any different than any other angular Since you are saying it is a problem not on import but on instantiation (which I have not seen as part of this bug) - can you confirm this by importing the component causing the problem but not using it? My project would throw those same errors even if I only imported and did not use, so Another test would be to but some console logging in your I have found that |
...I'll add to this and say I bet you will experience the problem regardless of if |
@jasonburrows thank you so much, guess what.. I have downgraded my Angular version to Downgrade command:
This gave a linter error saying;
This gave me some hope because, before the downgrade, I did not get this linter error on VS code. Before the downgrade it was Additional changes: Downgraded angular fire to So yeah the downgrade saved me |
@Teebo what version were you on before? I’ll have to avoid it! |
@jasonburrows I was on ~10.0.5 |
@Teebo I believe I am working the same issue and working to resolve... Did you basically go through and clean out all angular 10.x and downgrade to the latest 9.x? I see above that you spec'd |
After an update to Angular 10+
I encountered a regression compared to Angular 9 version
Since the release in angular version 10. ReferenceError: window is not defined I tried to move the redefinition of the global in the server.ts and the main.server.ts but nothing there still makes the same error. Has there been a change in the consideration of the global between the versions It seems that since 10.1.0 all people can't build in SSR anymore because of a potential script with |
I had something similar to this happen to me upgrading to angular 9 and found upon close inspection that I needed to mock something within the window object …
For too long I was convinced it was just on the window object,
In my case it was this:
win.DragEvent = () => {};
good luck!
Sent from Mail for Windows 10
From: Romain Marecat
Sent: Thursday, September 10, 2020 8:55 AM
To: angular/universal
Cc: coanpape; Comment
Subject: Re: [angular/universal] "Window is not defined" even whenisPlatformBrowser used. (#1675)
After an update to Angular 10+
Angular: 10.1.0
... animations, cli, common, compiler, compiler-cli, core
... elements, forms, language-service, platform-browser
... platform-browser-dynamic, platform-server, router
... service-worker
Ivy Workspace: Yes
Package Version
--------------------------------------------------------------------
@angular-devkit/architect 0.1001.0
@angular-devkit/build-angular 0.1001.0
@angular-devkit/build-ng-packagr 0.1001.0
@angular-devkit/build-optimizer 0.1001.0
@angular-devkit/build-webpack 0.1001.0
@angular-devkit/core 10.1.0
@angular-devkit/schematics 10.1.0
@angular/cdk 10.2.0
@angular/flex-layout 10.0.0-beta.32
@angular/material 10.2.0
@angular/material-moment-adapter 10.2.0
@ngtools/webpack 10.1.0
@nguniversal/builders 10.1.0
@nguniversal/common 10.1.0
@nguniversal/express-engine 10.1.0
@nguniversal/module-map-ngfactory-loader 9.0.0-next.9
@schematics/angular 10.1.0
@schematics/update 0.1001.0
ng-packagr 10.1.0
rxjs 6.5.5
typescript 3.9.7
webpack 4.44.1
I encountered a regression compared to Angular 9 version
On the main.server.ts side, I had defined window via domino (everything was functional in ng9):
global['window'] = win;
global['document'] = win.document;
global['CSS'] = null;
global['XMLHttpRequest'] = xmlhttprequest.XMLHttpRequest;
global['Prism'] = null;
global['HTMLAnchorElement'] = win.HTMLAnchorElement;
global['navigator'] = win.navigator;
global['requestAnimationFrame'] = requestAnimationFrame as unknown as (callback: FrameRequestCallback) => number;
global['cancelAnimationFrame'] = cancelAnimationFrame;
global['Element'] = win.Element;
global['Event'] = win.Event;
global['KeyboardEvent'] = win.KeyboardEvent;
Since the release in angular version 10.
The same code no longer works. It seems that global ['window'] is no longer recognized in the main.js suite
ReferenceError: window is not defined
because of node_modules / leaflet / dist / leaflet-src.js from ngx-leaflet which does not work in SSR.
I tried to move the redefinition of the global in the server.ts and the main.server.ts but nothing there still makes the same error.
Has there been a change in the consideration of the global between the versions
@nguniversal/common": "^9.1.0 and @nguniversal/express-engine": "^9.1.0 compare to @nguniversal/common": "^10.1.0" and
"@nguniversal/express-engine": "^10.1.0"
It seems that since 10.1.0 all people can't build in SSR anymore because of a potential script with window.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or unsubscribe.
|
So hey @alan-agius4 - any updates on this? Kinda looks like SSR has been effectively broken for two versions of Angular and its even more broken in 10 than in 9. What's the update? This is a pretty core feature of Angular - how is it not getting any attention? |
@jasonburrows Hi can you try resolving it on Zuck.js? How can I shim it like you did? This is driving my crazy really. I have been at it for a whole 3 days already, I have run into multiple errors and this window is the constant thing up my face. |
@julesmercado what errors are you getting? I literally know nothing about Zuck.js but if I see the errors I might be able to help. |
It has same problem with the window being undefined since Zuck.js is a 3rd party library. I already got it to work by delaying its import inside isPlatformBrowser just like this one (and so I eliminated the need for it to be imported before the constructor). I don't know if it is good practice but it has worked for me. |
Did you try the above example where window is shimmed using domino? If so, what was the problem with that? What version of Angular are you on? What are your I don’t know of any specific problem with how you’ve done it but I don’t think it’s the recommended approach. |
Any Updates? |
I am working with angular 12, and I am still facing this issue with a third library. I tried all the domino solutions but they are not working. |
Same here, I'm having the following errors: |
Angular version 12.0.1 still getting this issue. Followed reference link
Still issue. Not able to fix. |
Updating tsconfig.server.json
Angular version 12.0.1
Again I am stuck with with svg not defined. |
Hello all, any progress on this? Working fine for me in angular versions =< 9, not working for 10+. Content of my server.ts is similar to the one posted by @Santoshah, which working fine in Angular9 but not for more recent versions. Still having |
Hi @mocanapena You will also need to make reference window object. Here is an example
|
Hello @Santoshah I forgot to mention that it happens only for server-side rendering usecase, when doing serve:ssr. I don't think your fix would solve the issue, as I already tried even when I was pretty sure it wouldn't work. |
@mocanapena Let's not assume things on our own. I had the same issue 10 days back. Whenever I try to run I have also open stack explaing my question here . I fixed them by following this website and lastly i updated the "module": "commonjs" inside compilerOptions solve the issue for window not defined. You need to update every window object to the reference. Also make sure you do no have localstorage used or you need to make a reference to window in that case also. I have manage to fixed this issue in my Angular 12.0.1 v project. Its very big and it took 3 days to fixed that issue and making changes all over the site. If you need personal assistant I can help. (its FREE). lets connect via skype: cssmaniaa |
After few days busy I could finally test solution provided by @Santoshah and I can confirm is working fine. |
@mocanapena Glad to help :) |
Solution provided by @Santoshah still doesn't work on Angular 11. |
Hello |
This comment was marked as spam.
This comment was marked as spam.
Is there a concrete solution for this yet? I’m stuck. Thanks. |
Hi I had the same problem. It was caused by a third party lib that I couldn't modify. if (this.winRef.isBrowser()) {
const lib = require('my-lib'); // eslint-disable-line
// then do something with the lib
} make sure add {
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [
"node"
]
},
...
} Hope it helps. |
Got the error from tiny-slider lib :( None of the workarounds helped in my case. |
Wrap that slider function inside the isBrowser condition. it should work.
|
hey, maybe someone will find this useful, works for angular 11 (and leaflet) |
Hello, we reviewed this issue and determined that it doesn't fall into the bug report or feature request category. This issue tracker is not suitable for support requests, please repost your issue on StackOverflow using tag If you are wondering why we don't resolve support issues via the issue tracker, please check out this explanation. |
This issue has been automatically locked due to inactivity. Read more about our automatic conversation locking policy. This action has been performed automatically by a bot. |
🐞 Bug report
What modules are related to this issue?
Is this a regression?
Yes the project worked correctly in all circumstances in Angular 8.1.1
Description
Large Angular 8 application with SSR support. Upgraded to Angular 9. All migration scripts related to my project ran and worked correctly with no errors.
Project works fine with ng serve and builds fine when targeting SSR with the command:
NODE_OPTIONS=--max-old-space-size=8192 ng build --source-map --configuration=development && ng run front:server:development
.When I try to run the resulting server (to host with express / express-engine) it gives the "Window not defined" because of a reference in a third party module. All uses of that module are guarded with an 'isPlatformBrowser' check.
🔬 Minimal Reproduction
Seemingly you just have to include any module that references 3rd party modules that try to access 'window'. Note that this did not cause any problem in Angular 8 as long as you guarded against use of those modules with 'isPlatformBrowser' checks.
Now it seems merely having the module referenced is enough.
Set up a vanilla universal app and then add any angular module that references any non-angular JS module that makes a call to window. Note that this will cause the problem even if the angular module is correctly using
isPlatformBrowser
.https://github.com/jasonburrows/angularUniversal1675.git
🔥 Exception or Error
🌍 Your Environment
The text was updated successfully, but these errors were encountered: