Next.js window is not defined 해결하기

이지훈·2022년 3월 7일
0

이번 프로젝트에서는 next.js(이하 next) 를 사용하기로 했다.

기능으로 현재 위치를 파악하고 위치에 맞는 날씨 정보를 나타내기 위한 방법을 찾다가
navigator.geolocation 객체를 사용하면 된다는 것을 알게 되었다.

일단 콘솔에 찍어보고자 console.log(navigator.geolocation)을 입력했지만 navigator is not defined가 떴다.
이상하다 생각해서 console.log(window.navigator.geolocation)를 입력하니 window is not defined가 떴다.
(CSR인 리액트에선 정상적으로 출력이 된다.)

이유?

next는 SSR(Server Side Rendering)으로
서버에서 보여질 HTML을 미리 준비해 클라이언트한테 응답해주는 방식이다.

웹 페이지를 렌더링 할때에 초기에는 window나 document 전역객체는 선언되지 않아 해당 변수를 참조할 수 없기 때문에 벌어진 일이다.

해결

생각보다 간단했다

if (typeof window !== 'undefined') 를 사용하거나
export default function weather() {
if (typeof window !== 'undefined') {
    console.log(navigator.geolocation);
  }
} 
//Geolocation {}

useEffect()를 사용하면 해결 가능하다.

import { useEffect } from 'react';
export default function weather() {
  useEffect(() => {
    console.log(navigator.geolocation);
  }, []);
profile
기록

0개의 댓글