1. getServerSideProps (Docs)
getServerSideProps 라는 함수를 한 페이지 내부에서 export 할 경우,
Next.js는 getServerSidePrpos에 의해 반환되는 각 페이지 별 요청에 따른 데이터를 pre-rendering 할 것이다.(자동적으로)
export async function getServerSideProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
Note that irrespective of rendering type, any props will be passed to the page component and can be viewed on the client-side in the initial HTML. This is to allow the page to be hydrated correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client in props. |
렌더링 타입을 무시하는 것은 페이지 컴포넌트를 pass 될것이고, 초기 HTML에서 client-side 위에 보여질 것이다. 이것은 패이지를 정확하게 hydrated 될 것이다. 확실히 해라 민감한 정보(props 안에는 클라이언트가 이용가능하지 않아야 할)는 pass 하지 않아야 한다고 |
- When does getServerSideProps run?
- getServerSideProps는 오로지 server-side에서 run한다. (절대 broswer에서 run X)
- 만약 페이지에서 getServerSideProps를 사용한다면
- 네가 이 페이지를 직접적으로 request 했을때, getServerSideProps는 request time을 실행하고, 이 페이지는 props을 리턴함과 동시에 pre-rendering 할 것이다.
- 네가 next/link || next/router를 통해 client-side페이지를 request 했을때, Next.js는 gerServerSideProps를 실행시키는 API request를 서버에 보낸다.
- getServerSidePrpos 은 JSON 데이터를 반환하며 이 데이터는 각 페이지에 렌더링 되기 위해 사용된다. 이 모든 작업들은 Next.js에 의해 자동적으로 핸등링되기 때문에, getServerSidePrpos에 대해 정의하려고 추가적인 시간 가지지 않아도 됨.
- When Should I use getServerSidePrpos
- 매 요청마다 data가 반드시 fetch 되어야 하는 페이지를 렌더링 할때 필요로 할때만 getServerSidePrpos 사용
- 이것은 data의 특성 or request의 속성 때문에 이렇게 됨
- getServerSidePrpos를 사용하는 페이지는 매 요청마다 server-side에서 렌더링 될것이고, cache-control 헤더가 조작될때만 캐시화 된다.
- 만약 request하는 동안 data를 fetch 할 필요가 없다면, client-side 또는 getStaticProps에서 데이터를 fetch하도록 고민
- 매 요청마다 data가 반드시 fetch 되어야 하는 페이지를 렌더링 할때 필요로 할때만 getServerSidePrpos 사용
- getServerSidePrpos 또는 API Routes
- 서버로부터 data를 fetch하기 원할때 API Route를 통해 시도할 수 있는데, 이건 getServerSidePrpos로부터 APIT Route를 call 할 수 있다. 이것은 비효율적인 접근이고 필수적이지않다. (extra request를 야기 할 수 있기 때문에)
- getServerSideProps 사용하기
const Page = ({data}) =>{
//
}
export async function getServerSidePrpos(){
const res = await(`https://.../data`)
const data = await res.json()
return {
props:{data}
}
}
export default Page
- server-side rendering로 캐싱하기
export async function getServerSideProps({req,res}){
res.setHeader(
'Cache-Contirol',
'public, s-maxage=10, stale-while-revalidate=59'
)
return {
props:{},
}
}
'FrontEnd > Next.js' 카테고리의 다른 글
[Next.js] OAuth(2.0)를 통한 로그인 인증 (0) | 2023.01.10 |
---|---|
페이지 렌더링 비교 (SSR vs CSR vs SSG (0) | 2023.01.04 |
[Next.js] Middleware에 대해 알아보자 (0) | 2022.12.22 |
[Next.js] Image 컴포넌트에 대해 (feat. local & remote) (0) | 2022.12.22 |
[Next.js] SWR을 통해 캐시 데이터 가져오기 (0) | 2022.12.12 |