Search code examples
javascriptreactjstypescriptnext.jsnavigator

Navigator is not defined in Next.Js App router


I have this piece of code in my component that is marked with "use client" at the top.

In my return I have a button. I ask if navigator share is available then it will be shown. I do this as the Web Share API is not supported by all browsers yet. It also works perfectly fine. In Chrome I see the share button and it works. In FIrefox for example I do not see it (as there is no support for it). Also in the browser console there are no errors.

But, in my VSCode terminal I get always the ReferenceError: navigator is not defined.
Why? And how can I get rid of it?

The piece of code that I have in my page.tsx, which is marked as "use client":
Nowhere else I use navigator so this is the source for the error in my terminal, but it just works actually.

            {navigator && navigator?.share && (
              <button
                className="absolute top-6 right-16"
                onClick={() => {
                  navigator
                    .share({
                      title: 'Title: ' + article.title,
                      url: 'http://localhost:3000/articles/' + article.id,
                    })
                    .then(() => console.log('Successful share'))
                    .catch(() => console.log('Error sharing'));
                }}
              >
                <Image src={Share} className="w-6 h-6" alt={'Share Icon'} />
              </button>
            )}

Solution

  • The solution for this is you have to check if the code is running in server/client first,

    so you need to do it like below

        {typeof window !== 'undefined' && navigator && navigator?.share && (
                  <button
                    className="absolute top-6 right-16"
                    onClick={() => {
                      navigator
                        .share({
                          title: 'Title: ' + article.title,
                          url: 'http://localhost:3000/articles/' + article.id,
                        })
                        .then(() => console.log('Successful share'))
                        .catch(() => console.log('Error sharing'));
                    }}
                  >
                    <Image src={Share} className="w-6 h-6" alt={'Share Icon'} />
                  </button>
                )}
    

    as for why you need this when you already have 'use client', client components are actually same as next's pages, where the component will get run both on server and client

    that's why its having navigator error in your server logs.