NextJS API: getServerSideProps

hwisaac·2023년 3월 13일
0

NextJS API(page router)

목록 보기
3/10

getServerSideProps 함수를 페이지에서 내보내면 (서버 측 렌더링), Next.jsgetServerSideProps에서 반환된 데이터를 사용하여 각 요청마다이 페이지를 사전 렌더링합니다. 이것은 자주 변경되는 데이터를 가져 오고 페이지가 가장 최신 데이터를 보여주도록하려는 경우 유용합니다.

export async function getServerSideProps(context) {
  return {
    props: {}, // 페이지 구성 요소로 props를 전달합니다.
  }
}

getServerSideProps에서 상위 수준 범위의 모듈을 가져와 사용할 수 있습니다. 사용 된 가져 오기는 클라이언트 측에 번들되지 않습니다. 이는 데이터베이스에서 데이터를 가져 오는 것을 포함하여 getServerSideProps에서 직접 서버 측 코드를 작성할 수 있음을 의미합니다.

컨텍스트 매개 변수

컨텍스트 매개 변수는 다음 키를 포함하는 객체입니다.

  • params:이 페이지가 동적 경로를 사용하는 경우 params에는 경로 매개 변수가 포함됩니다. 페이지 이름이 [id].js 인 경우 params{id : ...}와 같습니다.
  • req: HTTP IncomingMessage 객체이며 추가적인 쿠키 값인 문자열 키가있는 cookies 속성이 있습니다.
  • res: HTTP 응답 개체입니다.
  • query: 개체는 동적 경로 매개 변수를 포함한 쿼리 문자열을 나타냅니다.
  • preview: 미리보기 모드인 경우 true이고 그렇지 않으면 false입니다.
  • previewData: setPreviewData에 의해 설정된 미리보기 데이터입니다.
  • resolvedUrl: 클라이언트 전환에 대해 _next/data 접두사를 제거하고 원래 쿼리 값을 포함하는 요청 URL의 정규화 된 버전입니다.
  • locale은 활성 로케일 (활성화 된 경우)을 포함합니다.
  • locales는 모든 지원되는 로케일을 포함합니다 (활성화 된 경우).
  • defaultLocale은 구성된 기본 로케일 (활성화 된 경우)을 포함합니다.

getServerSideProps 반환 값

getServerSideProps 함수는 다음 속성 중 하나를 포함하는 객체를 반환해야합니다.

props

props 객체는 각 값을 페이지 구성 요소에서 수신하는 키-값 쌍입니다. 직렬화 가능한 객체 여야하므로 JSON.stringify를 사용하여 직렬화 된 props를 전달 할 수 있습니다.

export async function getServerSideProps(context) {
  return {
    props: { message: `Next.js is awesome` }, // 페이지 구성 요소로 props를 전달합니다.
  }
}

notFound

notFound는 불리언 값으로, 페이지가 404 상태와 404 페이지를 반환할 수 있도록 합니다. 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 }, // 페이지 구성 요소에 프롭스로 전달됩니다.
  }
}

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의 타입은 next의 GetServerSideProps를 사용하여 지정할 수 있습니다.

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,
    },
  }
}

프롭스의 유추 가능한 타입을 얻고 싶다면, InferGetServerSidePropsType<typeof getServerSideProps>를 사용할 수 있습니다.

import { InferGetServerSidePropsType } from 'next'
import { GetServerSideProps } from 'next'

type Data = { ... }

export const getServerSideProps: GetServerSideProps<{ data: Data }> = async () => {
  const res = await fetch('https://.../data')
  const data: Data = await res.json()

  return {
    props: {
      data,
    },
  }
}

function Page({ data }: InferGetServerSidePropsType<typeof getServerSideProps>) {
  // data의 타입은 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 }: InferGetServerSidePropsType<typeof getServerSideProps>) {
  // data 변수의 타입은 Data로 추론됩니다
}

export default Page

이 코드는 InferGetServerSidePropsType을 이용하여 getServerSideProps 함수의 반환 타입을 추론하고, 해당 타입의 data 프로퍼티를 컴포넌트의 props로 받아 사용합니다. 이렇게 함으로써 TypeScript의 타입 추론을 이용하여 개발 효율을 높일 수 있습니다.

0개의 댓글