HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

Window is not defined in Next.js React app

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
nextdefinedwindowappreactnot

Problem

In my Next.js app I can't seem to access window:

Unhandled Rejection (ReferenceError): window is not defined

componentWillMount() {
    console.log('window.innerHeight', window.innerHeight);
}

Solution

Move the code from componentWillMount() to componentDidMount():

componentDidMount() {
  console.log('window.innerHeight', window.innerHeight);
}


In Next.js, componentDidMount() is executed only on the client where window and other browser specific APIs will be available. From the Next.js wiki:

Next.js is universal, which means it executes code first server-side,
then client-side. The window object is only present client-side, so if
you absolutely need to have access to it in some React component, you
should put that code in componentDidMount. This lifecycle method will
only be executed on the client. You may also want to check if there
isn't some alternative universal library which may suit your needs.

Along the same lines, componentWillMount() will be deprecated in v17 of React, so it effectively will be potentially unsafe to use in the very near future.

Code Snippets

componentDidMount() {
  console.log('window.innerHeight', window.innerHeight);
}

Context

Stack Overflow Q#55151041, score: 103

Revisions (0)

No revisions yet.