
Next.js는 정적 사이트 생성(SSG)과 서버 사이드 렌더링(SSR) pre-rendering 웹사이트 생성을 도와주는 리액트 프레임워크이다.
SSG를 구현하기 위한 함수로는 getStaticProps와 getStaticPaths를 제공하고 있고,
SSR를 구현하기 위한 함수는 getServerSideProps를 제공하고 있다.
Next.js에서 제공하는 함수 중 하나로, 정적 사이트 생성을 위해 사용된다. 페이지가 빌드될 때 getStaticProps에서 반환된 props를 사용하여 페이지를 미리 렌더링할 수 있다. (공식문서)
import type { InferGetStaticPropsType, GetStaticProps } from 'next';
type Repo = {
name: string;
stargazers_count: number;
};
export const getStaticProps: GetStaticProps<{
repo: Repo;
}> = async () => {
const res = await fetch('https://api.github.com/repos/vercel/next.js');
const repo = await res.json();
return { props: { repo } };
};
export default function Page({
repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return repo.stargazers_count;
}
getStaticProps는 항상 서버에서 실행되며 클라이언트에서는 실행되지 않는다.
동적 라우팅 (Dynamic routing) + getStaticProps 를 사용하는 경우 반드시 사용해야한다.
getStaticPaths를 사용하면 Next.js는 getStaticPaths에서 지정된 모든 경로를 정적으로 사전 렌더링한다.
여기서 정의하지 않은 하위 경로는 접근해도 렌더링이 되지 않기 때문에, path와 fallback을 return 해줘야 한다. (공식문서)
import type {
InferGetStaticPropsType,
GetStaticProps,
GetStaticPaths,
} from 'next';
type Repo = {
name: string;
stargazers_count: number;
};
export const getStaticPaths: GetStaticPaths = async () => {
return {
paths: [
{
params: {
name: 'next.js',
},
}, // See the "paths" section below
],
fallback: true, // false or "blocking"
};
};
export const getStaticProps: GetStaticProps<{
repo: Repo;
}> = async () => {
const res = await fetch('https://api.github.com/repos/vercel/next.js');
const repo = await res.json();
return { props: { repo } };
};
export default function Page({
repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return repo.stargazers_count;
}
서버에서 렌더링 될 때마다 실행되며 페이지를 렌더링하기 전에 데이터를 가져온다.
getServerSideProps는 데이터가 매 요청마다 변경되는 경우에 사용된다. 페이지 컴포넌트에서 내보내야 한다. (공식문서)
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next';
type Repo = {
name: string;
stargazers_count: number;
};
export const getServerSideProps: GetServerSideProps<{
repo: Repo;
}> = async () => {
const res = await fetch('https://api.github.com/repos/vercel/next.js');
const repo = await res.json();
return { props: { repo } };
};
export default function Page({
repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return repo.stargazers_count;
}
getServerSideProps는 서버에서만 실행되며 클라이언트에서는 실행되지 않는다.
페이지가 getServerSideProps를 사용하는 경우
getServerSideProps는 페이지를 렌더링하는 데 사용될 JSON을 반환한다. Next.js가 모든 작업을 자동으로 처리하므로 getServerSideProps가 정의되어 있다면 추가 작업이 필요하지 않다.
getServerSideProps는 페이지에서만 내보낼 수 있다. 페이지 파일이 아닌 파일에서 내보낼 수 없다.
getServerSideProps를 페이지 컴포넌트의 속성으로 추가하면 작동하지 않으므로 getServerSideProps를 독립적인 함수로 내보내야 한다.