3
votes

I have made a Angular 6 project with dependency Angularfire2 . I am using firestore and firebase storage. I have converted my app to angular universal and when i run server.js it says listening on localhost:4000 but as soon as i open the browser with localhost:4200 the terminal shows the following error:

ReferenceError: XMLHttpRequest is not defined

here is the snippet of the error

4
Hello, Jayneet! Welcome to StackOverflow! Please consider posting an MCVE (Minimal, Complete and Verifiable Example) so that we could help you, instead of posting images of a console output which in no way helps anyone without the code required to reproduce your case.Edric

4 Answers

9
votes

Install these dependencies:

npm install --save-dev ws xmlhttprequest

Then add this to your server.ts file

(global as any).WebSocket = require('ws');
(global as any).XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

If you run into any other issue with SSR by using Firebase, check if this article already covers it.

Sources:

5
votes

If anyone gets the same problem, the solution for me was to make sure that I did not import the HttpClientModule in my child modules. Once it was already imported in the main AppModule, the error went away.

Here is a link that gave me the solution https://www.thecodecampus.de/blog/angular-universal-xmlhttprequest-not-defined-httpclient/

0
votes

For future reference using xmlhttprequest didn't work me so I had to use xhr2 like so:

  1. npm install ws xhr2 bufferutil utf-8-validate -D
  2. And then adding both ws and xhr2 to server.ts

(global as any).WebSocket = require('ws');
(global as any).XMLHttpRequest = require('xhr2');

-1
votes

You have to install the @angular/platform-server and import the ServerModule. That provides server implementations of the DOM, XMLHttpRequest, and other low-level features that don't rely on a browser.

For more information see the universal guide