본문 바로가기

javascript/nextjs

[nextjs13] fetch API

 무작정 fetch 메서드를 써보다가 뭔가 이상해서 공식 문서를 찾아봤다. 


https://nextjs.org/docs/app/api-reference/functions/fetch

 

Functions: fetch | Next.js

Using App Router Features available in /app

nextjs.org

 nextjs 13 버전에서는 getStaticProps, getServersideProps 같은 불편한 표기가 사라졌다. 서버로부터 데이터를 가져오는 방식이 fetch API를 경유하도록 일관된 방식으로 변경되었으며, cache / next 옵션을 통해 기존 함수에 대응되는 기능을 구현할 수 있도록 변했다.

  • force-cache / default: getStaticProps에 대응
  • no-store: getServerSideProps에 대응
  • next.revalidate: getStaticProps의 revalidate 옵션에 대응

위 지시어 중 next.revalidate을 제외한 요소들은 HTTP 요청을 보낼 때 기존에도 설정할 수 있는 요소이다. 

https://developer.mozilla.org/en-US/docs/Web/API/Request/cache

 

Request: cache property - Web APIs | MDN

The cache read-only property of the Request interface contains the cache mode of the request. It controls how the request will interact with the browser's HTTP cache.

developer.mozilla.org

  • default: HTTP 캐시에서 일치하는 요청을 찾되 fresh( Cache-Control: max-age=~ 이 아직 유효 ) 여부에 따라 다른 동작을 수행한다.
    • 캐시가 fresh 하다면 캐시로부터 값을 반환한다.
    • 일치하는 캐시가 존재하지만 오래되었다면(stale) Conditional Request(last-modified, etag 등)을 통해 서버의 데이터를 검사한 후 캐시를 사용하거나 새롭게 값을 가져온다.
  • no-store: 원격 서버에서 리소스를 가져오기만 한다.( 업데이트 X )
  • reload: 원격 서버에서 리소스를 가져와서 캐시를 업데이트한다.
  • no-cache: 캐시에서 일치하는 리소스를 찾되, 유효성을 재확인하고 사용한다.
  • force-cache: 캐시에서 일치하는 리소스를 찾아 사용한다.
  • only-if-cached: 캐시에서 일치하는 요청을 찾는다. 있다면 반환하고, 없으면 504를 반환한다. (mode: same-origin)