Why can't I access the window in Next.js app '_app.js'?

0

Issue

I have a Next.js app where I want to load the application and then check for Network access with a custom modal dialog that displays if the user disconnects to the internet. I set up an _app.js file for my application to set up the Context Provider but unable to check network access on it using the window.navigator. It results to an error: "ReferenceError: window is not defined". Is there any way I can load the application first so I can use the custom modal dialog I created?

_app.js

function MyApp({ Component, pageProps }) {
  console.log(window)
  return <Component {...pageProps} />
}

export default MyApp

Error upon page reload:
Approach #1
Error

Solution

You can access window when component mounted by using useEffect:

function MyApp({ Component, pageProps }) {
 useEffect(() => {
        console.log(window)
 },[])
 return <Component {...pageProps} />

}

export default MyApp

Answered By – Paiman Rasoli

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More