Skip to main content

Add a fallback for RPC requests

It's best practice to ensure your app can still function if your primary RPC endpoint provider fails, enabling JSON-RPC API requests to fall back to an alternative. Wagmi provides a fallback function that fulfils this need, and is based on the corresponding Viem function.

It enables you to add multiple Transports — the element of Viem, and therefore Wagmi, which handles requests — to your app's configuration. If the first fails, the request falls back to the next Transport.

Prerequisites​

Install Wagmi and Viem:

npm install @wagmi/core @wagmi/connectors viem

Viem is required for Wagmi to function. The @wagmi/connectors package is not strictly necessary, since fallback is included in @wagmi/core, but you'll most likely need it for your app anyway.

Usage​

You can implement the fallback transport by adding it to your app's Wagmi configuration:

    export const wagmiConfig = createConfig({
chains: [linea],
transports: {
[linea.id]: fallback([
http('https://linea-mainnet.infura.io/v3/{YOUR_API_KEY}'), // Primary RPC provider
http('https://rpc.linea.build'), // Fallback RPC provider
]),
}

In this example, we define a primary RPC endpoint (Infura) and a fallback (rpc.linea.build).

See full code example
src/config/wagmiConfig.ts
import { createConfig, http, fallback } from '@wagmi/core';
import { jsonRpcProvider } from '@wagmi/core/providers/jsonRpc';
import { linea } from 'viem/chains';

// Add the fallback to the config
export const wagmiConfig = createConfig({
chains: [linea],
transports: {
[linea.id]: fallback([
http('https://rpc.linea.build'), // primary RPC HTTP endpoint
http('https://another.rpc.endpoint/1'), // fallback HTTP endpoint
]),
},
});

Optionally, you can also configure the rank parameter to enable your fallback Transport(s) to be used in order of latency and stability.