Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Error:Navigator not defined with nextjs

Tags:

next.js

My code is like this:

import React, { useEffect } from 'react';

    import alanBtn from '@alan-ai/alan-sdk-web';
    
    const alanKey = my key;
    const App = () => {
        useEffect(() => {
            alanBtn({
                key: alanKey,
                onCommand: ({ command }) => {
                        alert('This code was executed');
                }
            })
        }, []);
        return (
            <div><h1>Alan AI News Application</h1></div>);
    }
    export default App;

But I am making the error as:

Reference Error:Navigator not defined..

What is the solution?

like image 331
Chaitra Katoti Avatar asked Mar 22 '26 09:03

Chaitra Katoti


1 Answers

Browser objects like window , navigator etc should be defined in useEffect first before use.

  const [pageURL, setPageURL] = useState("");
  const [isNativeShare, setNativeShare] = useState(false);
  useEffect(() => {
    setPageURL(window.location.href);
    if (navigator.share) {
      setNativeShare(true);
    }
  }, []);

// Now, you can use pageURL, isNativeShare in code
like image 148
GorvGoyl Avatar answered Mar 25 '26 01:03

GorvGoyl