Retry Link
retryLink is a link that allows you to retry failed operations in your tRPC client. It provides a customizable way to handle transient errors, such as network failures or server errors, by automatically retrying the failed requests based on specified conditions.
If you use @trpc/react-query you will generally not need this link as it's built into the useQuery() and the useMutation() hooks from @tanstack/react-query.
Usage
You can import and add the retryLink to the links array when creating your tRPC client. This link can be placed before or after other links in your setup, depending on your requirements.
ts
ts
In the example above, we add the retryLink before the httpBatchLink. By default, retryLink will:
- Retry the request if the error is a TRPCClientErrorwith a status code of 500 or if we couldn't get a valid TRPC error.
- Retry the request up to 3 times.
You can customize the retry logic by providing a custom retry function.
Options
ts
ts
Handling tracked() events
When using retryLink with subscriptions that use tracked(), the link will automatically include the last known event ID when retrying. This ensures that when a subscription reconnects, it can resume from where it left off without missing any events.
For example, if you're using Server-sent Events (SSE) with httpSubscriptionLink, the retryLink will automatically handle reconnecting with the last event ID when errors like 401 Unauthorized occur.