728x90
반응형
getServerSideProps
만약 getServerSideProps 라 불리는 async 함수를 export한다면 Next.js는 getServerSideProps에 의해 리턴된 data를 사용하면서 이 페이지를 매 요청시마다 pre-rendering 할 것이다.
export async function getServerSideProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
context 파라미터는 다음 속성들을 포함하는 객체이다.
params | 만약 동적 라우트를 사용하는 페이지라면 params는 라우트 파라미터들을 포함한다. 만약 페이지명이 [id].js라면 params는 {id : ...}와 같은 형태가 될 것이다. |
req | HTTP IncommingMessage object |
res | HTTP response object |
query | An object representing the query string |
preview | preview가 true라면 이 페이지는 preview모드, false면 아닌 것이다. |
previewData | setPreviewData에 의해 세팅된 preview data이다 |
resolvedUrl | client transition을 위해 _next/data 접두어가 생략된 요청 url의 정규화 버전 |
locale | active locale을 포함 |
locales | 모든 지원 locales를 포함 |
defaultLocale | 디폴트로 설정된 locale |
getServerSideProps가 리턴하는 객체는 아래항목들이 포함한다.
- props - 페이지 컴포넌트에 의해 리턴되는 props는 필수객체이다.
- notFound - 페이지가 404 상태와 404 페이지로 리턴되도록 허용하는 옵셔널한 boolean 값이다.
- redirect: 옵셔널한 값으로 내외부 자원으로 redirecting 해주는 값이다. 반드시 {destination: string, permanent: boolean} 형태여야 한다.
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: {}, // will be passed to the page component as props
}
}
언제 getServerSideProps를 써야할까?
getServerSideProps는 pre-render되는 페이지의 필요한 데이터가 요청시에 가져와야하는 경우에만 사용해라. 서버가 반드시 모든 요청에 대한 결과를 계산해야만 하기 때문에 getStaticProps보단 느리다.
만약 데이터가 pre-render 될 필요가 없다면, client-side에서 데이터를 가져오는 것을 고려해봐라.
- 동적 라우트에서 정적인 데이터를 필요로 할 때 : getStaticProps
- 동적 라우트에서 정적인 데이터를 필요로 하며, 정적인 페이지를 생성할 때 : getStaticPaths with getStaticProps
- pre-render되는 페이지에 필요한 데이터를 요청시에 가져와야 하는경우 : getServerSideProps
- pre-render가 필요없고 데이터를 가져와야하는 경우 : Axios
TypeScript : Use GerServerSideProps
타입스크립트를 사용할 때에는 next에서 GetServerSideProps를 사용할 수 있다.
import { GetServerSideProps } from 'next'
export const getServerSideProps: GetServerSideProps = async (context) => {
// ...
}
Technical details
Only runs on server-side
getServerSideProps는 서버에서만 동작하고 브라우저에서 동작하지 않는다. 사용할 때
- getServerSideProps는 요청시에만 실행된다.
- 만약 이 페이지가 next/Link나 next/router를 통해 요청된다면 Next.js는 API요청을 서버에 보낸다. 그리고 getServerSideProps를 실행한다. 그리고 getServerSideProps의 실행결과로 만들어진 JSON을 리턴한다.
또한 getServerSIdeProps는 pages에서만 요청된다.
SWR
리액트에서 쓰이는 useAsync같은 Hook이다. 클라이언트사이드에서 데이터를 가져올 때 이것이 매우 유용하다.
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then((res) => res.json())
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
728x90
반응형
'Front-End > Next.js' 카테고리의 다른 글
Next.js | 라우터 | 소개 (0) | 2021.10.13 |
---|---|
Next.js | 기본기능 | Built-In CSS Support (0) | 2021.10.13 |
Next.js | 기본기능 | Data fetching(3) | getStaticPaths (0) | 2021.10.13 |
Next.js | 기본기능 | Data fetching(2) | Incremental Static Regeneration (0) | 2021.10.13 |
Next.js | 기본기능 | Data fetching(1) (0) | 2021.10.08 |