
Next.js는 모든 페이지를 pre-render 한다.
pre-render은 모든 페이지를 위한 html을 클라이언트 사이드에서
자바스크립트로 처리하기 전 사전에 생성한다는 걸 의미한다.
Next.js에서 데이터를 가져오는 방법은 여러가지가 있다.
Static Generation으로 빌드할 때 데이터를 불러온다.
export async fuction getStaticProps(context) {
const res = await fetch('https://...');
const posts = await res.json();
return {
props : {
posts,
}
}
}
위 코드와 같이 getStaticProps 함수를 async로 export 한 후,
function Board({posts}) => {
return (
<ul>
{posts.map((post) => (<li>{post.content}</li>))}
</ul>
)
}
getStaticProps에서 리턴되는 props를 가지고 페이지를 빌드 시간에 프리렌더링 한다.
Static Generation으로 데이터에 기반하여 pre-render시 특정한 동적 라우팅 구현한다.
경로 리스트를 정의하고, HTML에 build 시간에 렌더링 된다.
export async fuction getStaticPaths() {
const res = await fetch('https://....');
const posts = await res.json();
const paths = posts.map((post) => ({
params : {id : post.id }
})
return { paths, fallback : false }
}
위 코드와 같이 getStaticProps 함수를 async로 export 한 후, path와 fallback을 리턴해준다.
function Board({posts}) => {
return (
<ul>
{posts.map((post) => (<li>{post.content}</li>))}
</ul>
)
}
return {
paths : [{params : {id : '1'}, {params : {id, '2'}],
fallback : ...
}
return {
paths : [{params : {id : '1'}, {params : {id, '2'}],
fallback : ...
}
server side Rendering으로 요청이 있을 때 데이터를 불러온다.
function Board({data}) {
}
export async function getServerSideProps() {
const res = await fetch('https://....');
const posts = await res.json();
return {props : {data}}
}
export default Board
getServerSideProps 함수를 async로 export하면, Next는 각 요청마다 리턴되는 데이터를 getServerSideProps로 pre-render 한다.