Search code examples
angularangular-cliangular-universalngx-bootstrap

Can't get Angular Universal to work with existing CLI project?


I have put in 17 hours trying to get this to work. I have tried just about every tutorial I could find.

I have an existing Angular 4 project that can be build and run perfectly without Universal. The existing project can even run through AOT fine (which was another pain to get running).

The current error I encounter when trying to run the server-side rendering is:

ERROR { ReferenceError: document is not defined

It took a while to even get to this point. There were tons of @types/node errors, but now that I got it to compile, the page won't load.

After doing some research on the error, it may be possible that ngx-bootstrap has something to do with it, but I am not 100% sure.

I am using this tutorial in combination with the webpack version of universal because without webpack my project would not compile due to ngx-bootstrap.


Solution

  • Somewhere in your code (or in a library), there is a reference to the document object. While this object is defined in every browser, it is not available on the server.

    According to https://github.com/angular/universal#universal-gotchas

    window, document, navigator, and other browser types - do not exist on the server - so using them, or any library that uses them (jQuery for example) will not work.

    As far as I can tell, there is no easy solution to this issue other than rewriting the code to avoid those objects.