본문 바로가기

private

getInitialProps in Next

app.tsx에서 index.tsx를 표시할때 styled를 적용한 컴퍼넌트를 표시할수 없다는

오류가 (getInitialProps오류)가 발생했다.

index.tsx는 styled를 사용하지 않고 내부에 불러온 개별 component에는 styled

가 이미 적용되어 있어 이해할수 없었지만, 붉은 메시지를 없애보려고 @emotion/styled를

import하니 오류는 사라졌다.

 

찜찜한 기분에 vscode를 재시동했는데,  이제는 index.tsx에서 @emotion/styled를 삭제해도

오류가 나타나지 않는다. 이런 설정상의 꼬인 부분은 문제가 무엇인지 파악하기도 어렵고 나타난

오류메시지의 의미도 우회적이라 무엇인가에 대해 기록을 남겨본다. 

 

⊙ Next.js의 getInitialProps와 getServerSideProps

 - 서버측 렌더링을 위한 두가지 기능 

 - 페이지 구성요소에서만 사용가능하며, 초기 페이지 렌더링과 Link의 표시에서 실행위치가 다름 

 

⊙ getInitialProps ( context매개변수 )

- 페이지 구성요소를 서버에서 데이터로 가져오고, SSR하는 비동기 함수 

- Initial Page로드시에 서버에서 실행

- <Link> 구성요소인 경우 브라우저 실행 ( 어플리케이션의 타 영역 탐색 후 router로서 이동할때)

   데이터는 getInitialProps의 객체로서 반환, props 페이지의 구성요소 기본 매개변수를 채움 

- context매개변수의 키

   req, res (요청 및 응답객체의 인스턴스), pathname(현재경로, pages/example.js.pathname/example),

    query(url에 포함된 경우), aspath(브라우저에 표시된 실제경로, 스트링 형식이며 쿼리포함), err(오류개체) 

 

 getServerSideProps ( context매개변수, 반환값, 자동캐싱기능 )

- SSR을 위한 비동기함수, Next9.3에서 도입된 대안함수 ( 항상 서버에서 실행되며 브라우저에서 실행X )

- context매개변수의 키

   req, res (요청 및 응답객체의 인스턴스), params(pages/[id.js]), query(동적경로 매개변수가 포함된

   쿼리 문자열, 페이지에서 쿼리 활용시), preview(Boolean, 미리보기 있을때 true), previewData(미리보기

   활용시 setPreviewData에 의해 설정된 데이터), resolveUrl(클라이언트 전환 _next/data접두사를 제거하

   URL의 해결된 버전), locale(국제화된 locale, 활성화된 경우), locales(지원되는 모든 로케일 정보 포함, 활성화시),

   defaultLocale(기본 로케일정보, 활성화시)

- 반환값 

   props: 페이지 구성요소에 전달된 객체(Key-value)

   notFound : 404상태와 페이지를 반환하는 Boolean 

   redirect : 내외부 소스로 redirection {destination:string, permanent:boolean} 예)가입후

                   사용자를 로그인 페이지로 redirection

- 자동캐싱 적용효과  

   서버응답시간 개선, 외부서비스 요청수 절감 , /_next/static Next에 자바스크립트,CSS,

   정적이미지, 기타 미디어등 정적 자산에 캐싱해더 자동 추가 (개발서버에서는 캐싱 미작동) 

 

 

---------------------------------------------------------------------------------

It's complicated .. the error didn't happen again but I still don't understand why it happened.

Also I don't understand how it was solved. What was the key issue behind this error?

On top of that,  what is the complete solution?

It's real chaos.. 

Regarding the way React renders pages, I could arrange components mechanically or

use hooks or setTimeout functions.. but why do I use them?.. how do they actually work?

Sometimes I feel like a very simple mechanic - someone who just knows input and outputs

but faces a black-box.

 

Relating Pages: 

https://refine.dev/blog/next-js-getinitialprops-and-getserversideprops/#getinitialprops