0

I am trying to use geolocation API in my app. Luckily I found one that I'd like to use at the MDN website, but when I tried testing for the geolocation object (if it exists in the browser) I got this error:

Server Error
ReferenceError: navigator is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source pages/index.js (24:20) @ eval

  22 | }
  23 | 
> 24 | if('geolocation' in navigator) {
     |                    ^
  25 |   console.log('It does exist')
  26 | } else {
  27 |   console.log('doesn't exist')

This is the code I tried implementing (from the MDN docs website) :

if('geolocation' in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}

Can you let me know what I'm doing wrong, and how to fix it?

showdev
  • 28,454
  • 37
  • 55
  • 73
  • Are you using React? – showdev Apr 17 '21 at 08:40
  • Is this executed on a server (`Server Error`, _" Any console logs will be displayed in the terminal window"_)? – Andreas Apr 17 '21 at 08:42
  • @showdev Yes sir. Next JS to be precise. Would that be the problem? –  Apr 17 '21 at 08:45
  • @ChrisBBB Are you testing from local? (like localhost:port} As it won't work in `HTTP` connection, only works in `HTTPS` protocol. `This feature is available only in secure contexts (HTTPS).` – sidverma Apr 17 '21 at 08:51
  • These and similar posts seem relevant: [How can I use geolocation in my node.js to get user device lat/long](https://stackoverflow.com/questions/61696252/how-can-i-use-geolocation-in-my-node-js-to-get-user-device-lat-long) and [Navigator not Found](https://stackoverflow.com/questions/34910623/requireprocessing-js-throws-reference-error-navigator-not-found) and [navigator is not defined](https://stackoverflow.com/questions/41194264/mocha-react-navigator-is-not-defined) – showdev Apr 17 '21 at 08:51
  • @sidverma - Yes, I am testing from local. –  Apr 17 '21 at 08:57
  • @ChrisBBB Then what I have told you is correct, you should either deploy on some secure HTTPS connection.[try ngrok]. Read here: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/geolocation – sidverma Apr 17 '21 at 10:00

1 Answers1

0

There is no window object on the server. When you want to work with the window object you need to do it on the client side. So in your react component, you need to use useEffect as this function only runs in the browser.

useEffect(()=>{
  if('geolocation' in navigator) {
    /* geolocation is available */
  } else {
    /* geolocation IS NOT available */
  }
},[])

The function inside useEffect will run when the component is mounted in the browser.

Ivan V.
  • 7,593
  • 2
  • 36
  • 53