Window is not defined in Next.js React app
Another solution is by using process.browser
to just execute your command during rendering on the client side only.
if (process.browser) { // Client-side-only code}
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 ifyou absolutely need to have access to it in some React component, youshould put that code in componentDidMount. This lifecycle method willonly be executed on the client. You may also want to check if thereisn'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.
If you use React Hooks you can move the code into the Effect Hook:
import * as React from "react";export const MyComp = () => { React.useEffect(() => { // window is accessible here. console.log("window.innerHeight", window.innerHeight); }, []); return (<div></div>)}
The code inside useEffect
is only executed on the client (in the browser), thus it has access to window
.