Next.js gives you the best developer experience with all the features you need for production: hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching, and more. No config needed.
pages/ // HTML Document, Application Container, 각종 페이지 등을 작성한다.
_document.js // SPA 시작점이 되는 index.html
_app.js // Application Container. 공통의 레이아웃을 작성한다.
_error.js // Error Page.
index.js // Root Page /로 시작되는 경로를 말한다.
hello.js // Hello Page /hello로 시작되는 경로를 말한다.
static/ // 정적 파일 (이미지, 파일 등)을 업로드 한다.
next.config.js // Next.js의 환경 설정 파일이다. 라우팅 설정, typescript, less 등의 webpack 플러그인을 설정한다.
- Frontend server에서 GET 요청을 받는다
- 요청에 맞는 page를 찾는다
- _app.js의 getinitialProps가 있다면 실행
- Page Component 안에 getinitailProps가 있다면 실행
- _document.js의 getInitalProps가 있다면 실행
- 모든 props를 구성하고 _app.js > Page Component 순으로 렌더링
- 모든 콘텐츠를 구성하고 _document.js를 실행해 html 형태로 출력
웹 페이지는 각 페이지마다 사전에 불러와야할 데이터들이 있다. Data Fectching이라고도 하는 로직은 CSR(Client Side Rendering)에서는 react 로직에 따라 componentDidMount or useEffect로 컴포넌트가 마운트 되고 나서 하는 경우가 많다. 이 과정을 서버에서 미리 처리하도록 도와주는 것이 바로 getInitialProps이다. (사실 Data Fetching에만 getInitialProps를 사용할 수 있는 것은 아니다.)
import axios from 'axios';
const Page = ({ stars }) => {
return <div>Next stars: {stars}</div>;
};
Page.getInitialProps = async ctx => {
const { data } = await axios.get('...url');
return { stars: data };
}
export default Page
📑 reference