NextJs에서 SSR(서버 사이드 렌더링)을 가능하게 하는 것이 바로 getInitialProps에 있다.
NextJS에서 모든 스크립트 코드는 NodeJs(서버)와 브라우저(클라이언트) 양쪽 모두에서 수행되지만 getInitialProps
함수는 서버나 클라이언트 중 한군데서만 실행된다.
getInitialProps의 SSR 절차
- getInitialProps의 호출
URL 주소를 이용해 직접 특정 페이지에 접근하면 NodeJs 환경에서 getInitialProps가 호출된다.
브라우저(클라이언트)에서 SPA로 페이지 이동하는 경우 브라우저 환경에서 getInitialProps가 호출된다. - getInitialProps가 plain object를 리턴하면 해당 객체가 그대로 class의 constructor의 props로 전달되거나 함수형일
경우 매개변수로 을 수 있다. - 서버에서 렌더링 된 html이 그대로 브라우저로 내려온다.
- 브라우저에서는 constructor에서 props를 통해 전달받은 데이터를 이용해 추가적인 서버 요청없이 화면을 똑같이 다시
한번 그린다.
ex)class 경우
import React from "react";
export default class extends React.Component {
static async getInitialProps({ req }) {
const userAgent = req ? req.headers["user-agent"] : navigator.userAgent;
return { userAgent };
}
render() {
return <div>Hello World {this.props.userAgent}</div>;
}
}
ex)함수형 경우
const Page = ({ stars }) => <div>Next stars: {stars}</div>;
Page.getInitialProps = async ({ req }) => {
const res = await fetch("https://api.github.com/repos/zeit/next.js");
const json = await res.json();
return { stars: json.stargazers_count };
};
export default Page;
getInitialProps에서 사용할 수 있는 속성
pathname: path section of URL
query: query string section of URL parsed as an object
asPath: String of the actual path shows in the browser
req: HTTP request object(server only)
res: HTTP response object(server only)
jsonPageRes: Fetch Response object(client only)
err: Error object if any error is encountered during the rendering
주의사항
getInitialProps는 pages 폴더 안 파일들에서만 사용할 수 있고 자식 컴포넌트들에서는 사용할 수 없다.
getInitialProps가 서버측에서 수행될 때만 필요한 모듈들을 클라이언트 쪽에서 불필요하게 로드되지 않도록 주의한다.