Skip to content

Retry Plugin

Retry Plugin automatically retries failed requests based on customizable retry strategies, improving the resilience of your application.

WARNING

Before using this plugin, make sure you understand client context, as retry behavior is managed through context.

Setup

ts
import { RetryLinkPlugin, RetryLinkPluginContext } from '@orpc/client/plugins'

interface ClientContext extends RetryLinkPluginContext {}

const link = new RPCLink<ClientContext>({
  plugins: [
    new RetryLinkPlugin(),
  ],
})

INFO

The link can be any supported oRPC link, such as RPCLink, OpenAPILink, or a custom one.

Usage

By default, retries are disabled. To enable retries, set the retry count in the request context:

ts
const 
planets
= await
client
.
planet
.
list
({
limit
: 10 }, {
context
: {
retry
: 3, // Maximum retry attempts
retryDelay
: 2000, // Delay between retries in ms
shouldRetry
:
options
=> true, // Determines whether to retry based on the error
onRetry
: (
options
) => {
// Hook executed on each retry return (
isSuccess
) => {
// Execute after the retry is complete } }, } })

INFO

The following context options control retry behavior:

  • retry: Maximum number of retry attempts before throwing an error (default: 0).
  • retryDelay: Delay between retry attempts (default: (o) => o.lastEventRetry ?? 2000).
  • shouldRetry: Function that determines whether a retry should be attempted (default: true).

You can override the default retry behavior globally by passing default options when initializing the plugin:

ts
const link = new RPCLink<ClientContext>({
  plugins: [
    new RetryLinkPlugin({
      default: {
        retry: 0,
        retryDelay: o => o.lastEventRetry ?? 2000,
        shouldRetry: o => true,
      }
    }),
  ],
})

Event Source Simulation

To replicate the behavior of EventSource for Event Iterator, use the following configuration:

ts
const streaming = await client.streaming('the input', {
  context: {
    retry: Number.POSITIVE_INFINITY,
  }
})

for await (const message of streaming) {
  console.log(message)
}

Learn More

For implementation details, see the source code.

Released under the MIT License.