biggora / device-uuid

Fast browser device uuid generation library. Written in pure JavaScript, no dependencies.
MIT License
183 stars 96 forks source link

ReferenceError: navigator is not defined in angular universal #13

Open mkhalesi opened 3 years ago

mkhalesi commented 3 years ago

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

Parziphal commented 2 years ago

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.

mkhalesi commented 2 years ago

@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 :)