node.js - ReferenceError: navigator is not defined

Viewed 35308

I'm getting ReferenceError: navigator is not defined running the following code on node.js:

navigator.geolocation.getCurrentPosition((data) => {
  console.log(data);
});

I assume that the problem is that Navigator.geolocation is a Web API and doesn't work on node. Is there a way to mock the browser and use it on node.js?

Many thanks

5 Answers

So I created this because analytics does not support node, so it requires conditional importing

import isNode from 'detect-node'
export async function analyticsLogEvents(event, params) {
  if (!isNode) {
    const firebase = await import('firebase/app')
    await import('firebase/analytics')
    firebase.default.analytics().logEvent(event, params)
  }
}

Is there a way to mock the browser and use it on node.js?

One library that is useful for mocking Web APIs is browser-env.

import browserEnv from 'browser-env';

Then:

browserEnv(['navigator']);

This pollutes the global namespace, though, so be circumspect in its use.

Node.js is a server side technology, which means it can't access the user's geolocation directly.

What you should be asking is how to get geolocation using javascript on the client side, and then simply send that information to your server via Ajax.

More info here: http://www.w3schools.com/html/html5_geolocation.asp .

There are of course libraries that will ease the use of this.

global.navigator worked for me:

global.navigator.geolocation.getCurrentPosition((data) => {
  console.log(data);
});
Related