Middleware System
TypeFetch supports middleware for logging, authentication, caching, retries, encryption, and custom request behavior.
client.use(async (ctx, next) => {
console.log('Request:', ctx.url)
const response = await next()
console.log('Response:', response.status)
return response
})Middlewares run in registration order before the request, then unwind in reverse order after the response.
client.use(firstMiddleware)
client.use(secondMiddleware)Execution flow:
firstMiddleware before
secondMiddleware before
fetch
secondMiddleware after
firstMiddleware afterBuilt-in Middlewares
Depending on how you export your middlewares, they can be registered directly or as factories.
Direct middleware example:
client.use(loggingMiddleware, {
debug: true,
logRequest: true,
logResponse: true,
})Factory middleware example:
client.use(cacheMiddleware({ ttl: 60_000 }))
client.use(retryMiddleware({ maxRetries: 3, delay: 300 }))Retry Engine
TypeFetch includes a built-in retry engine on the client.
client.setRetryConfig({
maxRetries: 3,
backoff: 'exponential',
retryCondition: (error, attempt) => {
return error.status !== undefined && error.status >= 500
},
})Supported backoff strategies:
| Strategy | Behavior |
|---|---|
fixed | Same delay each retry |
linear | Delay increases linearly |
exponential | Delay doubles after each retry |
Example:
client.setRetryConfig({
maxRetries: 3,
backoff: 'fixed',
})Timeout and Abort Support
Each request can receive per-call options.
await api.user.getUser(
{
path: { id: '123' },
},
{
timeout: 5000,
}
)You can also pass an external AbortSignal.
const controller = new AbortController()
await api.user.getUser(
{
path: { id: '123' },
},
{
signal: controller.signal,
}
)
controller.abort()