본문 바로가기
개발/Next.js

Next.js "Reference Error: document is not defined"

by 안뇽! 2022. 3. 2.
반응형

next.js 썸네일

Reference Error: document is not defined

document is not defined 를 해결하려면 next.js의 작동방식을 먼저 알아야 한다.

CSR(Client side rendering)인 리액트와 달리, Next는 첫 렌더링에서 SSR(Server side rendering)방식을 취한다. 서버에서는 document를 찾을 수 없다.

 

이를 간과하고 document같은 브라우저에서만 작동하는 기능을 SSR이 작동하는 시점에 이용하면 Reference Error : document is not defined 에러가 발생한다.

 

Next.js에서 ReferenceError : document is not defined 가 뜰 때 해결책은 총 3가지이다.

 

1. window 객체가 존재할때만 렌더링되도록 하기

다음과 같은 패턴으로 window 객체가 작성할때만 렌더링 되도록 할 수 있다. 가장 심플하다.

if(type window === 'undefined'){
	return null
}
.. 나머지 코드 작성

 

 

 

 

2. useEffect 사용

컴포넌트가 갱신되거나, 마운트 된 후에 작동하는 useEffect를 사용한다.

만약 document가 로딩 되었을때만 체크하고 싶다면 의존성배열에 빈배열을 넣어주면 된다.

import {useEffect} from "react";

useEffect(() => {
    alert('Finished loading');
  }, []);

 

3. dynamic import 사용

dynamic import과  { ssr:false } 를 이용해서 특정 컴포넌트를 CSR 시킬 수 있다.

 

브라우저에서만 작동하는 라이브러리를 사용할때 좋은 방법이라고 공식문서에서 소개한다.

You may not always want to include a module on server-side. For example, when the module includes a library that only works in the browser.
//next 공식문서
// https://nextjs.org/docs/advanced-features/dynamic-import

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/hello3'),
  { ssr: false }
)

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  )
}

export default Home

참고 문서

https://dev.to/typicoul/fixing-next-js-referenceerror-document-is-not-defined-2jgi

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

반응형