nextjs에서 window 객체 찾을 수 없는 에러

soo's·2023년 8월 12일
0

에러  정리

목록 보기
9/10

Server Error
ReferenceError: window is not defined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
util/video/player.ts (4:19) @ window
2 |
3 | export const getVideoJsOptions = (videoUrl: string, thumbnailUrl: string, isIOS: boolean) => {
4 | const isMobile = window.matchMedia("(max-width: 520px)").matches;
| ^
5 | return {
6 | autoplay: true,
7 | controls: true,

window 객체를 찾을 수 없는 에러 발생
window는 브라우저의 전역 객체로, 서버에서는 사용할 수 없습니다. Next.js와 같은 프레임워크에서는 기본적으로 서버 사이드 렌더링이나 정적 생성을 수행하기 때문에 이런 문제가 발생할 수 있습니다.

해결 방법은
1. 조건부 사용해서 윈도우 객체 있는지
2. useEffect로 컴포넌트 마운트 후에 window 접근하기 => 이거는 상황에 따라 불가능하기도 함, 함수안에서 useEffect 호출 못하니까

나는 함수 안에서 사용해야 하기 때문에 1번으로 해결함

const isMobile = typeof window !== "undefined" && window.matchMedia("(max-width: 520px)").matches;

0개의 댓글