Fix the Window is not defined error

Fix the Window is not defined error

Next.js is very useful in many aspects, but nothing is perfect. One difficult point is the use of the window object. It is used in many libraries and tools such as analytics and, because Next.js uses pre-rendering, the window may be undefined and may therefore break our site.

Wait for window to be ready

This is the usual fix we find for this issue. Somehow it was never the fitting solution in my projects, but I still try it every time.

if (typeof window !== "undefined") {
  // Client-side-only code
}

With useEffect

The other solution requires a better knowledge of React, using the useEffect hook. It is working because this hook will wait for the mounting of the page. Pay attention to the empty array, which is needed to work.

useEffect(() => {
    // Client-side-only code
}, [])

For a working example, check this article on dark mode.

Enjoy coding with Next.js!

Please open this website with a recent browser for the best experience. Avoid Internet Explorer at all costs.