Next - getServerSideProps

Moolbum·2022년 7월 1일
0

Next

목록 보기
2/3
post-thumbnail

getServerSideProps

페이지에서 getServerSideProps 함수를 내보내면 반환된 데이터를 이용해 페이지가 요청 받을때 마다 호출되어 pre-rendering합니다.


pre-render

기본적으로 next는 모든 페이지를 pre-render합니다. 각 페이지에 대해 미리 HTML을 생성합니다. 더 나은 성능과 SEO를 챙길수 있습니다. 두 가지 방식이있습니다.

  • Static Genertion (StaticProps) 권장 : 빌드시 HTML 생성되며 각 요청마다 재사용
  • Server-side-Rendering : 요청마다 HTML 생성

특징

  • 페이지 요청마다 호출합니다
  • 매 요청마다 HTML을 호출하기 때문에 성능저하를 일으킬 수 있다.
  • 꼭 필요할 때 사용하는 것이 좋습니다.

사용방법

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

import { GetServerSideProps } from 'next'

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

  return {
    props: { data },
  }
}


getServerSideProps 반환 값

  • props
  • revalidate
  • notFound
  • redirect

props

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

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

revalidate

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

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

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

notFound

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

export async function getServerSideProps() {
  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 getServerSideProps(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 { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = 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
Next - 공식 홈페이지 pre-render

profile
Junior Front-End Developer 👨‍💻

0개의 댓글