본문 바로가기
Next

[Next] ReferenceError: window is not defined

by lvd-hy 2024. 2. 14.
반응형

 

목차

    1. 원인

    Next는 SSR로 서버에서 렌더링 된다.

    window 객체는 브라우저 환경에서만 정의되고 서버 환경에서는 window 객체가 존재하지 않기 때문에 이러한 오류가 발생함.

    2. 해결

    2-1. AS-IS

    const currentURL = window.location.href;
      
      const handleCopyClipBoard = async () => {
        try {
          alert("복사되었습니다.");
        } catch (error) {
          alert("다시 시도해주세요.");
        }
      };
    
      return (
        <section className={styles.greeting}>
          <div className={styles.greetingContainer}>
            <CopyToClipboard text={currentURL} onCopy={handleCopyClipBoard}>
              <div className={styles.clipboardIcon}></div>
            </CopyToClipboard>
            <div className={styles.kakaoIcon} />
          </div>
        </section>
      );

     

    2-2. TO-BE

    window 객체가 존재하는지 판단하는 코드를 추가해준다.

    const currentURL = typeof window !== 'undefined' ? window.location.href : "";
      
      const handleCopyClipBoard = async () => {
        try {
          alert("복사되었습니다.");
        } catch (error) {
          alert("다시 시도해주세요.");
        }
      };
    
      return (
        <section className={styles.greeting}>
          <div className={styles.greetingContainer}>
            <CopyToClipboard text={currentURL} onCopy={handleCopyClipBoard}>
              <div className={styles.clipboardIcon}></div>
            </CopyToClipboard>
            <div className={styles.kakaoIcon} />
          </div>
        </section>
      );

    Reference

    https://github.com/vercel/next.js/issues/26055

     

    Window is not defined · Issue #26055 · vercel/next.js

    What version of Next.js are you using? 10.2.3 What version of Node.js are you using? 14.17.0 What browser are you using? Chrome What operating system are you using? Windows How are you deploying yo...

    github.com

     

    반응형

    댓글