Next - getStaticProps

Moolbum·2022년 7월 1일
0

Next

목록 보기
1/3
post-thumbnail

getStaticProps

페이지에서 getStaticProps 함수를 내보내는 경우 Next 빌드 시에 반환된 props를 사용하여 페이지를 미리 렌더링합니다.


특징

  • 빌드시에 한 번 호출됩니다.
  • 고정된 내용의 page에 사용하는것이 좋습니다.
  • 매번 data fetch를 하지않아 ServerSideProps보다 성능면에서 좋습니다.
  • revalidate 지정한 시간뒤에 다른 사람이 온다면 그 사람은 업데이트된 데이터를 볼 수 있게 할 수 있습니다.


사용방법

getStaticProps 를 사용할 page폴더내 파일에 아래 함수를 추가합니다.
타입스크립트의 경우 next에서 타입을 import를 합니다.

import { GetStaticProps } from 'next'

export const getStaticProps: GetStaticProps = async () => {
  const res = await fetch(`https://...`)
  const data = await res.json()

  return {
    props: { data },
  }
}


getStaticProps 반환 값

  • props
  • revalidate
  • notFound
  • redirect

props

페이지 구성 요소에서 값을 받습니다. 객체형식입니다.

export async function getStaticProps(context) {
  return {
    props: { message: `Next.js is awesome` }, 
  }
}

revalidate

페이지의 재생성을 발생 시키는 시간(초 단위)입니다. 기본값은 false입니다.

export async function getStaticProps() {
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  return {
    props: {
      posts,
    },
    revalidate: 10, 
  }
}

notFound

notFound의 boolean 값을 이용하면 404페이지를 반환할 수 있습니다.

export async function getStaticProps() {
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  if (!data) {
    return {
      notFound: true, // 404 페이지 이동
    }
  }

  return {
    props: { data },
  }
}

redirect

redirect를 이용해 외부 페이지로 이동할 수 있습니다.
redirect는 객체 형태로 { destination: string, permanent: boolean }

export async function getStaticProps(context) {
  const res = await fetch(`https://...`)
  const data = await res.json()

  if (!data) {
    return {
      redirect: {
        destination: '/', // 페이지 이동
        permanent: false, // 영구적으로 캐시를 할지 true/false
      },
    }
  }

  return {
    props: { data },
  }
}


try, catch문 활용

import { GetStaticProps } from 'next'

export const getStaticProps: GetStaticProps = async () => {
  const REVALIDATE = 10; // revalidate 상수
  
  try {
  const res = await fetch(`https://.../data`)
  const data = await res.json()
    });

    return {
      props: {data},
      revalidate: REVALIDATE, // 10초 뒤에 업데이트 된 데이터 출력
    };
  } catch (err) {
    return {
      notFound: true, // 404페이지 이동
    };
  }
};

Next - 공식 홈페이지 getStaticProps
Next - 공식 홈페이지 getStaticProps API

profile
Junior Front-End Developer 👨‍💻

0개의 댓글