LoginSignup
61
28

More than 3 years have passed since last update.

Next.jsで"document is not defined." "window is not defined."のエラーが出たときの対処法

Last updated at Posted at 2020-07-14

Next.jsで"document is not defined." "window is not defined."のエラーが出たときの対処法

原因

Next.jsのSSRが原因である可能性が高いです。

SSR = Server Side Rendering

本来クライアント(ブラウザ)側でしか動かないJSフレームワークなどによるレンダリングをサーバー側で行うことによって、初期表示時の高速読み込みや検索エンジン最適化(SEO)を向上するもの。

サーバー側でJSの処理を実行しようとしているときに、ブラウザ側にしか存在しないグローバルオブジェクトのwindowdocumentを参照しようとすると、標題のエラーが起こります。

対策

1. componentDidMount()内で処理を行う

componentDidMount()内に書いた処理は、基本的にcomponentがmountされた後にクライアント側のみで起こる処理なので、このエラーは起こらないようです。

ただ、componentDidMount()はクラスコンポーネントのライフサイクルメソッドなので、関数コンポーネントでは使えません。

2. if文で条件分岐

React Hooksが主流の現在、こちらの方が汎用性が高いです。

ssr1.js
if (process.browser) {
  // windowやdocumentを使う処理を記述
}

もしくはシンプルに:

ssr2.js
if (typeof window !== "undefined") {
  // windowを使う処理を記述
}

(コメントでのご指摘・編集リクエストを受けて修正)

参考

Stack Overflow - Window is not defined in Next.js React app
https://nextjs.org/blog/next-9#dead-code-elimination-for-typeof-window-branches
https://github.com/vercel/next.js/issues/5354#issuecomment-520305040

61
28
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
61
28