본문 바로가기
개발 프레임워크/Next.js

[Next.js] window is not defined, document is not defined

by minhyeok.lee 2023. 3. 29.
반응형

1. Next.js에서 window is not defined, document is not defined가 출력되는 이유

1. Next.js는 서버측에서 움직이는 SSR(Server Side Rendering)과 클라이언트 측에서 움직이는 CSR(Client Side Rendering)을 수행하는 프레임워크이다.

 

2. document, window 두 객체는 클라이언트 측에서만 정의되는 전역 변수이다.  

 

3. 서버측에서 Redeing을 할 때, 코드를 읽으면서 document와 window 두 객체를 읽을 수 없기 때문에 window is not defined, document is not defined 두 error가 출력된다.

 

4. 따라서 document, window를 쓴다면 서버쪽에서 document, window를 정의하고 사용하려고 시도하는 것을 예외처리를 해주고 클라이언트 측에서 랜더링이 된 후에 사용해야 한다.

 

5. 왜냐하면 Next.js는 서버 측에서 랜더링 된 다음에 클라이언트로 전송되는 SSR구조이기 때문이다.

 

 


 

2. window is not defined, document is not defined 해결 방법

1. if문을 사용하여 document, window가 있는지 판단하는 방법

let location, windowLocation;

if (typeof document !== "undefined") {
  location = document.location;
}
  
if (typeof window !== "undefined") {
  windowLocation = window.location;
}

위 코드와 같이 if문으로 document, window가 undefined인지 아닌지 판단하여 undefined가 아닐때 실행하는 방법이다.

 

 

2. 클라이언트 측에서만 체크할 수 있게 판단하는 방법 ( process.browser 사용 )

let location, windowLocation;

if (process.browser) {
  location = document.location;
  windowLocation = window.location;
}

process.browser을 사용하면 브라우저 환경만 실행하여 서버 환경에서의 실행을 무시해 클라이언트 환경에서만 잘 동작한다.

 

3. useEffect 사용하는 방법 

useEffect(() => {
  console.log(document.location);
  console.log(window.location);
}, []);

useEffect(() => {}) HOOK은 client 측에서 rendering 이후에 실행되기 때문에 코드가 잘 출력된다.

 

출력값

#document
Location{ , ... , }

 

 

반응형

댓글