Next.js: how to access browser "window" object

lucasm

Lucas Menezes

Posted on August 6, 2021

Next.js: how to access browser "window" object

If you are trying to access "window" object from HTML DOM in your Next.js app and have this error message:

Unhandled Rejection (ReferenceError): window is not defined

Just keep you code as the example:

componentDidMount() {
   console.log('window.innerHeight', window.innerHeight);
}
Enter fullscreen mode Exit fullscreen mode

Another solution to just execute your code during rendering on the client side only, is:

if (typeof window !== "undefined") {
   var width = window.innerWidth;     
}
Enter fullscreen mode Exit fullscreen mode

I hope you enjoy it!

Follow me on Twitter
Sponsor my open source projects on GitHub

💖 💪 🙅 🚩
lucasm
Lucas Menezes

Posted on August 6, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related