[Nuxt3] $fetch 실패 시 왜 자동으로 refetch 될까?
Nuxt3에서 $fetch를 사용하다보면 요청이 실패했을 때 자동으로 다시 요청되는(refetch) 경우가 있습니다. 이번 포스팅에서는 그 이유에 대해 알아보겠습니다
해당 현상이 발생한 원인을 파악하기위해서, Nuxt3의 $fetch가 어떻게 동작하는지 알아보겠습니다.
Nuxt3는 $fetch라는 내장 HTTP 클라이언트를 제공하며, 이는 내부적으로 ohmyfetch(ofetch) 라이브러리를 활용해 구현되어 있습니다.
여기서 중요한 포인트는 ofetch를 사용하다는 것입니다.
https://github.com/unjs/ofetch
ofetch Github를 들어가면 아래와 같은 설명을 확인 하실 수 있습니다.
ofetch Automatically retries the request if an error happens and if the response status code is included in retryStatusCodes list:
Retry status codes:
- 408 - Request Timeout
- 409 - Conflict
- 425 - Too Early (Experimental)
- 429 - Too Many Requests
- 500 - Internal Server Error
- 502 - Bad Gateway
- 503 - Service Unavailable
- 504 - Gateway Timeout
You can specify the amount of retry and delay between them using retry and retryDelay options and also pass a custom array of codes using retryStatusCodes option.
The default for retry is 1 retry, except for POST, PUT, PATCH, and DELETE methods where ofetch does not retry by default to avoid introducing side effects. If you set a custom value for retry it will always retry for all requests.
The default for retryDelay is 0 ms.
await ofetch("http://google.com/404", {
retry: 3,
retryDelay: 500, // ms
retryStatusCodes: [ 404, 500 ], // response status codes to retry
});
중요한 부분은 기본적으로 아래 Retry status codes에 있는 status라면 한 번 재시도 하도록 되어있다는것입니다.
이렇게 원인을 찾았으니 이제 Nuxt3에서 retry 설정을 어떻게 제어할 수 있는지 살펴보겠습니다.
1. useFetch에서 각 요청마다 직접 retry 설정
const { data, pending, error, refresh } = useFetch('/pages', {
retry: 1,
retryStatusCodes: [401],
retryDelay: 500,
})
각 요청에 대해 개별적으로 retry 설정을 지정하면 요청의 특성과 중요도에 맞춰 유연하게 제어할 수 있다는 장점이 있지만
매 요청마다 옵션을 반복해서 작성해야 하므로 코드 복잡도가 올라갈 수 있다는 단점이 있습니다.
2. $fetch.create로 $fetch의 인스턴스를 생성하여 설정
const instance = $fetch.create({
retry: 1,
retryStatusCodes: [401],
retryDelay: 0,
})
전역 인스턴스를 생성하면 공통 설정을 한곳에서 관리할 수 있어 코드가 간결해지고 일관성을 유지할 수 있는 장점이 있지만
모든 요청에 동일한 retry 정책이 적용되므로 세밀한 제어가 필요한 경우에는 적절한 예외 처리가 필요하다는 단점이 있습니다.
마무리
Nuxt에서 $fetch 실패 시 왜 자동으로 refetch 가 되는지에 대해서 알아 보았습니다.
refetch 기능은 일시적인 네트워크 문제나 서버 오류에 효과적인 해결책이 될 수 있지만, 이로 인해 발생할 수 있는 문제들도 존재합니다. 이러한 상황들을 충분히 고려한 뒤 사용한다면, refetch를 매우 효과적으로 활용하실 수 있을 것입니다.