페이지에서
getServerSideProps
함수를 내보내면 반환된 데이터를 이용해 페이지가 요청 받을때 마다 호출되어 pre-rendering합니다.
기본적으로 next는 모든 페이지를 pre-render합니다. 각 페이지에 대해 미리 HTML을 생성합니다. 더 나은 성능과 SEO를 챙길수 있습니다. 두 가지 방식이있습니다.
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 },
}
}
페이지 구성 요소에서 값을 받습니다. 객체형식입니다.
export async function getServerSideProps(context) { return { props: { message: `Next.js is awesome` }, } }
페이지의 재생성을 발생 시키는 시간(초 단위)입니다. 기본값은 false입니다.
export async function getServerSideProps() { const res = await fetch('https://.../posts') const posts = await res.json() return { props: { posts, }, revalidate: 10, } }
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는 객체 형태로 { 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 }, } }
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