Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window is not defined in Next.js React app

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); } 

Enter image description here

like image 613
Leon Gaban Avatar asked Mar 13 '19 20:03

Leon Gaban


People also ask

Why is window undefined in next JS?

This is because, Next. js is server-side rendered, and it runs the component code in the server, sends the HTML to the browser, and the HTML gets hydrated in the browser.

Can I use window in next JS?

js React app. Bookmark this question.

How do you fix window is not defined?

To solve the "ReferenceError: window is not defined" error, make sure to only use the window global variable on the browser. The variable represents a window containing a DOM document and can't be used on the server side (e.g. in Node. js). If you need to define global variables in Node.

Is window available in React?

The window is the global object in the browser environment. Any property attached to the window object can be accessed from any script on the web page, including the script for the React app. Since window is a global object, the React code can also access its properties, as shown below.


2 Answers

̶A̶n̶o̶t̶h̶e̶r̶ ̶s̶o̶l̶u̶t̶i̶o̶n̶ ̶i̶s̶ ̶b̶y̶ ̶u̶s̶i̶n̶g̶ ̶p̶r̶o̶c̶e̶s̶s̶.̶b̶r̶o̶w̶s̶e̶r ̶ ̶t̶o̶ ̶j̶u̶s̶t̶ ̶e̶x̶e̶c̶u̶t̶e̶ ̶ ̶y̶o̶u̶r̶ ̶c̶o̶m̶m̶a̶n̶d̶ ̶d̶u̶r̶i̶n̶g̶ ̶r̶e̶n̶d̶e̶r̶i̶n̶g̶ ̶o̶n̶ ̶t̶h̶e̶ ̶c̶l̶i̶e̶n̶t̶ ̶s̶i̶d̶e̶ ̶o̶n̶l̶y̶.

But process object has been deprecated in Webpack5 and also NextJS, because it is a NodeJS variable for backend side only.

So we have to use back window object from the browser.

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

Other solution is by using react hook to replace componentDidMount:

useEffect(() => {     // Client-side-only code })
like image 134
Darryl RN Avatar answered Sep 28 '22 04:09

Darryl RN


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.

like image 27
Alexander Staroselsky Avatar answered Sep 28 '22 04:09

Alexander Staroselsky