Home >Web Front-end >JS Tutorial >How to Fix the 'window is not defined' Error in Next.js?

How to Fix the 'window is not defined' Error in Next.js?

Susan Sarandon
Susan SarandonOriginal
2024-12-08 06:07:16902browse

How to Fix the

Window is not defined in Next.js React App: A Comprehensive Resolution

In Next.js applications, you may encounter the error "window is not defined" when attempting to access the global 'window' object. This can occur because the window object is only available during client-side rendering. Here's how you can resolve this issue:

To use the 'window' object, you can surround your code with an 'if' statement that checks whether 'window' is defined:

if (typeof window !== "undefined") {
  // Client-side-only code
  console.log('window.innerHeight', window.innerHeight);
}

This approach ensures that the code within the 'if' block is only executed on the client-side, where the 'window' object is accessible.

Using the suggestion of accessing 'window' via 'process.browser' is no longer recommended as it has been deprecated in both Webpack5 and Next.js. The 'process' object is primarily used for server-side rendering, and using it for client-side operations is not appropriate.

Therefore, the recommended solution is to check for the presence of the 'window' object before accessing it. This ensures that your code is portable between client-side and server-side rendering environments.

The above is the detailed content of How to Fix the 'window is not defined' Error in Next.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn