Search code examples
angulartypescriptwebrtcserver-side-rendering

RTCPeerConnection is not defined


I have an Angular application with server side rendering. I have created a WebRTC service that works fine in unit tests. However, when I run the application I get the following error:

RTCPeerConnection is not defined

On this code:

this.localConnection = new RTCPeerConnection({
      iceServers: [
        ...
      ],
});

The browser I'm using definitely knows the RTCPeerConnection class because I've tested it in the console. Visual Studio Code also thinks the class is available but the serving process believes otherwise.

I would like to know how to ensure that RTCPeerConnection is available for my server rendered Angular web application.


Solution

  • The answer, with thanks to Philipp Hanke for pointing me in the right direction, was to wrap the code in a check for the window object type definition, as per this Stack Overflow answer: Angular 17 window not defined.

    The fixed code is:

    if (typeof window !== 'undefined') {
        this.localConnection = new RTCPeerConnection({
              iceServers: [
                ...
              ],
        });
        ...
    }
    

    The code now executes as intended and throws no server error. I presume that the code is being checked for correctness when rendered on the server, but only actually run within the browser. However, if anyone wants to comment with a better explanation I'd be very interested to find out why the code acts like this, presuming it wouldn't have executed twice.