DEV Community

Lucas Menezes
Lucas Menezes

Posted on • Updated on

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

Top comments (3)

Collapse
 
rafde profile image
Rafael De Leon

I think you can also do
globalThis?.window?.innerWidth
or
window?.innerWidth

I usually do the first one to be formal

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

do you do

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

or

if (globalThis?.window?.innerWidth) {
   var width = window.innerWidth;     
}
Enter fullscreen mode Exit fullscreen mode


?

Collapse
 
ekkis profile image
Erick Calder

when I try it I get:

Unhandled Runtime Error
TypeError: Cannot read properties of null (reading 'suppressHydrationWarning')

Call Stack
didNotFindHydratableInstance
node_modules/react-dom/cjs/react-dom.development.js (10511:0)
insertNonHydratedInstance
node_modules/react-dom/cjs/react-dom.development.js (14509:0)