Next.js의 데이터 가져오기를 사용하면 앱의 사용 사례에 따라 다양한 방식으로 콘텐츠를 렌더링 할 수 있다. Server-side Rendering이나 Static Generation을 사용한 사전 렌더링과 Incremental Stati Regeneration을 사용한 런타임 시 콘텐츠 업데이트나 생성 등을 할 수 있다. 그중에서도 오늘은 Server-side Rendering를 구현하게 해주는 getServerSideProps 함수를 살펴보고자 한다.
페이지에서 getServerSideProps라는 함수를 내보내면 Next.js는 getServerSideProps에서 반환된 데이터를 사용하여 각 요청에서 이 페이지를 미리 렌더링한다. (Server-side Rendering)
export async function getServerSideProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
렌더링 유형과 관계없이 모두 페이지 컴포넌트로 전달되며 초기 HTML는 클라이언트 측에서도 볼 수 있다.
- context 파라미터
위 함수의 context의 파라미터는 다음과 같은 키들을 포함하는 객체이다.
- params: 이 페이지가 동적 route를 사용하는 경우 pramas는 route 파라미터를 포함한다. 만약 이 페이지의 이름이 [id].js인 경우에는 params는 { id: ... }와 같이 표시된다.
- req: HTTP로 보내지는 메시지 객체. key string과 value string이 매핑된 객체인 쿠키가 props에 더해진다.
- res: HTTP 응답 객체
- query: 동적 route 파라미터를 포함하여 쿼리 문자열을 보여주는 객체.
- preview: preview는 페이지에 미리보기 모드가 있으면 true, 없으면 false.
- previewData: setPreviewDate로 설정된 미리 보기 데이터
- resolveUrl: 클라이언트 전환을 위해 _next/data 접두사를 제거하고 원래 쿼리 값을 포함하는 request URL의 정규화된 버전.
- locale: 활성 로케일을 포함(활성화된 경우)
- locales: 지원되는 모든 로케일을 포함(활성화된 경우)
- defaultLocale: 구성된 기본 로케일을 포함(활성화된 경우)
- getServerSideProps의 반환 값
이 함수는 다음 속성 중 하나를 가진 객체를 반환해야 한다.
1. props
props 객체는 페이지 컴포넌트에서 각 값을 받는 키-값 쌍이다. 전달된 모든 props는 JSON.stringify가 사용 가능한 객체 형태여야 한다.
export async function getServerSideProps(context) {
return {
props: { message: "next.js is awesome },
}
}
2. notFound
noteFound 불리언은 페이지를 404 상태와 404 Page를 반환하는 것을 허용한다. notFound: true를 사용하면 이전에 성공적으로 생성된 페이지가 있더라도 페이지에서 404를 반환한다. 이 것은 작성자가 사용자 생성 콘텐츠를 제거하는 것과 같은 사용 사례를 지원하기 위한 것이다.
export async function getServerSideProps(context) {
const res = await fetch('https://.../data')
const data = await res.json()
if (!data) {
return {
notFound: true,
}
}
return {
props: { data },
}
}
3. redirect
redirect 객체는 내부 및 외부 리소스로의 리디렉션을 허용한다. 이것은 { destination: string, permanent: boolean } 모양과 일치해야 한다. 드문 경우지만 HTTP를 요청하는 클라이언트가 제대로 리디렉션 되도록 사용자 지정 상태 코드를 할당해야 할 수도 있다. 이런 경우 permanent 속성 대신 statusCode 속성을 사용할 수 있지만 둘 다 사용할 수는 없다.
export async function getServerSideProps(context) {
const res = await fetch('https://.../data')
const data = await res.json()
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {},
}
}
- Typescript에서 getServerSideProps 사용하기
getServerSideProps의 타입은 GetServerSideProps from next를 사용하여 정의할 수 있다.
import { GetServerSideProps } from 'next'
type Data = { ... }
export const getServerSideProps: GetServerSideProps<{ data: Data }> = async (context) => {
const res = await fetch('https://.../data')
const data: Data = await res.json()
return {
props: { data },
}
}
만약 props에 유추된 타입선언을 얻으려면 InferGetServerSidePropsType<typeof getServerSideProps>를 사용할 수 있다.
import { InferGetServerSidePropsType } from 'next'
improt { GetServerSideProps } from 'next'
type Data = { ... }
export const getServerSideProps: GetServerSideProps<{ data: Data }> = async () => {
cosnt res = await fetch('https://.../data')
const data: Data = await res.json()
return {
props: { data },
}
}
function Page({ data }): InferGetServerSidePropsType<typeof getServerSideProps>) {
//will resolve data to type Data
}
export default Page
getServerSideProps에 대한 암시적 타입선언도 제대로 작동한다.
import { InferGetServerSidePropsType } from 'next'
type Data = { ... }
export const getServerSideProps = async () => {
const res = await fetch('https://.../data')
const data: Data = await res.json()
return {
props: { data },
}
}
function Page({ data }: InferGetServerSidePrsopType<typeof getServerSideProps>) {
// will resolve data to type Data
}
export default Page
'Next.js' 카테고리의 다른 글
Next.js 4-1. getSaticPaths (0) | 2023.04.24 |
---|---|
Next.js 3-2. getStaticProps (SSG) (0) | 2023.04.21 |
Next.js 3-1. getStaticProps (SSG) (0) | 2023.04.21 |
Next.js 2-2. getServerSideProps(SSR) (0) | 2023.04.19 |
Next.js 1. 왜 Next.js인가? (0) | 2023.04.18 |