react-native-webrtc / react-native-webrtc-web-shim

Web Shim for React Native WebRTC
MIT License
22 stars 11 forks source link

SSR rendering in NextJS causes build error #14

Open gavrilikhin-d opened 6 months ago

gavrilikhin-d commented 6 months ago

Describe the bug

react-native-webrtc-web-shim uses window, which is undefined on Server. This is causing error in NextJS:

ReferenceError: window is not defined

In this minified code snipet

window.MediaStream.prototype.release=function(){this.getTracks().forEach(function(e){return e.stop()})}

Versions:

React Native Version: 0.73.2 React Native Web Version: 0.19.10 React Native WebRTC Version: 118.0.0

gavrilikhin-d commented 6 months ago

Should be quite easy to fix by using:

if (typeof window !== "undefined") {

}
8BallBomBom commented 6 months ago

Easy fix indeed but this module wasn't intended to be used with NextJS as such. But it does use React as a foundation so it does make sense to have at least "some" support. Will be included in the next release.

gavrilikhin-d commented 2 months ago

Patch that fixes it:

diff --git a/node_modules/react-native-webrtc-web-shim/src/react-native-webrtc-web-shim.web.js b/node_modules/react-native-webrtc-web-shim/src/react-native-webrtc-web-shim.web.js
index 7d10049..5b823e6 100644
--- a/node_modules/react-native-webrtc-web-shim/src/react-native-webrtc-web-shim.web.js
+++ b/node_modules/react-native-webrtc-web-shim/src/react-native-webrtc-web-shim.web.js
@@ -1,5 +1,7 @@
 import RTCView from './RTCView';

+if (typeof window !== "undefined") {
+
 window.MediaStream.prototype.release = function release() {
   this.getTracks().forEach((track) => track.stop());
 };
@@ -8,6 +10,8 @@ window.MediaStreamTrack.prototype._switchCamera = function _switchCamera() {
   console.warn('_switchCamera is not implemented on web.');
 };

+}
+
 const {
   RTCPeerConnection,
   RTCIceCandidate,
@@ -18,13 +22,15 @@ const {
   RTCErrorEvent,
   MediaStream,
   MediaStreamTrack,
-} = window;
+} = typeof window !== "undefined" ? window : {};

-const { mediaDevices, permissions } = navigator;
+const { mediaDevices, permissions } = typeof window !== "undefined" ? navigator : {};

 function registerGlobals() {
-  window.mediaDevices = navigator.mediaDevices;
-  window.permissions = navigator.permissions;
+  if (typeof window !== "undefined") {
+    window.mediaDevices = navigator.mediaDevices;
+    window.permissions = navigator.permissions;
+  }
 }

 export {