Timeout and Retry Timeout and retry are two options that can be used to control the request timeout and retry behavior.
You can set the timeout in milliseconds.
const res = await $fetch ( "/api/users" , {
timeout : 10000 ,
});
You can set the retry count and interval in milliseconds.
const res = await $fetch ( "/api/users" , {
retry : 3
});
Better fetch provides flexible retry mechanisms with both linear and exponential backoff strategies. You can customize the retry behavior to suit your specific needs.
Basic retry with number of attempts:
const res = await $fetch ( "https://jsonplaceholder.typicode.com/todos/1" , {
retry : 3
});
Linear retry strategy:
const res = await $fetch ( "https://jsonplaceholder.typicode.com/todos/1" , {
retry : {
type : "linear" ,
attempts : 3 ,
delay : 1000 // 1 second delay between each attempt
}
});
Exponential backoff strategy:
const res = await $fetch ( "https://jsonplaceholder.typicode.com/todos/1" , {
retry : {
count : 3 ,
interval : 1000 , //optional
type : "exponential" ,
attempts : 5 ,
baseDelay : 1000 , // Start with 1 second delay
maxDelay : 10000 // Cap the delay at 10 seconds, so requests would go out after 1s then 2s, 4s, 8s, 10s
}
});
Custom retry condition:
const res = await $fetch ( "https://jsonplaceholder.typicode.com/todos/1" , {
retry : {
type : "linear" ,
attempts : 3 ,
delay : 1000 ,
shouldRetry : ( response ) => {
if ( response === null ) return true ;
if ( response . status === 429 ) return true ;
if ( response . status !== 200 ) return true ;
return response . json (). then (
data => data . completed === false
). catch (
err => true
)
}
}
});
Retry with callback:
const res = await $fetch ( "https://jsonplaceholder.typicode.com/todos/1" , {
retry : 3 ,
onRetry : ( response ) => {
console . log ( `Retrying request.` );
}
});