device-uuid icon indicating copy to clipboard operation
device-uuid copied to clipboard

ReferenceError: navigator is not defined in angular universal

Open mkhalesi opened this issue 3 years ago • 2 comments

hi when run project in ssr with command : npm run dev:ssr get same error:

return new DeviceUUID(navigator.userAgent);
                        ^
ReferenceError: navigator is not defined

im using a mock browser , in server.ts file :

const MockBrowser = require('mock-browser').mocks.MockBrowser;
const mock = new MockBrowser();
global['navigator'] = mock.getNavigator();
global['window'] = mock.getWindow();
global['document'] = mock.getDocument();

thanks

mkhalesi avatar Aug 24 '21 06:08 mkhalesi

SSR runs on the server, where navigator and other objects (like window) aren't available. When coding for SSR you have to make sure to check the platform before executing code that use these objects.

Parziphal avatar Oct 04 '21 20:10 Parziphal

@Parziphal i worked based on your tips like this:

 if (isPlatformBrowser(this.platformId)) {
        import('device-uuid').then( module => {
             const deviceId = new module.DeviceUUID().get() ; 
         });  
  }

and worked properly thanks :)

mkhalesi avatar Oct 04 '21 20:10 mkhalesi