# Wayfinder SDK's (/index) **For AI and LLM users**: Access the complete Wayfinder documentation in plain text format at{" "} llm.txt for easy consumption by AI agents and language models. See [AI Agents & LLMs](/build/agents) for the full agent toolkit. Wayfinder leverages the decentralized ar.io Network to provide robust, censorship-resistant access to data stored on Arweave, removing reliance on centralized gateways. By routing requests through a distributed set of community-operated gateways, Wayfinder ensures high availability, redundancy, and improved performance for users and applications. The `ar://` protocol enables decentralized resolution and access to Arweave data using several flexible URL formats: - `ar://TRANSACTION_ID` — Direct access to a specific Arweave transaction - `ar://NAME` — Resolution of ArNS names (with optional path support) - `ar:///info` — Direct access to gateway endpoints (e.g., `/info`) To learn more about the Wayfinder protocol and how it works, visit [/learn/wayfinder](/learn/wayfinder). ## Getting Started Choose your environment to get started with Wayfinder: } title="@ar.io/wayfinder-core" description="Core SDK for Node.js applications and server environments" href="/sdks/wayfinder/wayfinder-core" /> } title="@ar.io/wayfinder-react" description="React hooks and components for browser applications" href="/sdks/wayfinder/wayfinder-react" /> } title="Wayfinder Router" description="Standalone proxy service with built-in verification and caching" href="/build/run-wayfinder-router" /> **Don't want to embed an SDK?** [Wayfinder Router](/build/run-wayfinder-router) is a standalone proxy you can deploy to provide a single verified endpoint for your users. ## Quick Examples ### Node.js ```javascript // Create a Wayfinder client const wayfinder = createWayfinderClient({ ario: ARIO.mainnet(), }); // Fetch data using the ar:// protocol const response = await wayfinder.request('ar://ardrive'); console.log(response); ``` ### React ```jsx // Wrap your app with the provider function App() { return ( ); } // Use the hook in your components function WayfinderImage({ txId }: { txId: string }) { const { resolvedUrl, isLoading, error } = useWayfinderUrl({ txId }); if (error) { return Error resolving URL: {error.message}; } if (isLoading) { return Resolving URL...; } return ( ); } ``` ## Next Steps } title="Learn about ar.io" description="Understanding the ar.io decentralized infrastructure" href="/learn/what-is-ario" /> } title="Decentralized Access" description="Learn how to access Arweave data in a decentralized way" href="/build/access" /> } title="Run Wayfinder Router" description="Deploy a standalone verified proxy for your users" href="/build/run-wayfinder-router" /> } title="Run a Gateway" description="Join the network by operating your own ar.io gateway" href="/build/run-a-gateway/quick-start" /> # Data Retrieval Strategies (/wayfinder-core/data-retrieval-strategies) Wayfinder supports multiple data retrieval strategies to fetch transaction data from AR.IO gateways. These strategies determine how data is requested and assembled from the underlying storage layer. | Strategy | Use Case | Requirements | | --------------------------------- | ------------------------------------------- | -------------------------------------- | | `ContiguousDataRetrievalStrategy`| Standard data fetching via direct GET | Gateway has the data cached or able to fetch from trusted peers | | `ChunkDataRetrievalStrategy` | Chunk-based data assembly | Gateway supports `/chunk/\/data` endpoint (r58) and has requested transactions indexed | #### ContiguousDataRetrievalStrategy The default strategy that fetches data using a direct GET request to the gateway. This is the most straightforward approach and works for most use cases. ```javascript const wayfinder = new Wayfinder({ dataRetrievalStrategy: new ContiguousDataRetrievalStrategy(), }); ``` #### ChunkDataRetrievalStrategy An advanced strategy that provides the easiest way to load chunks stored on Arweave nodes via the robust chunk API provided by AR.IO gateways. This approach is particularly useful for: - **Direct chunk access**: Efficiently retrieves data directly from the underlying chunk storage layer - **Bundled data items**: Seamlessly fetches data items from within ANS-104 bundles using calculated offsets - **x402 payment compatibility**: Both strategies support custom fetch clients for payment-enabled requests - **Large file handling**: More reliable for large transactions that may time out with direct requests **Requirements:** - Gateway must support the `/chunk/\/data` endpoint (added in [r58](https://github.com/ar-io/ar-io-node/releases/tag/r58)) - Gateway must have the requested transaction indexed (offsets are needed to fetch directly from chunks) ```javascript const wayfinder = new Wayfinder({ dataRetrievalStrategy: new ChunkDataRetrievalStrategy(), }); ``` **How it works:** 1. Makes a HEAD request to get transaction metadata (root transaction ID, data offset, content length) 2. Queries `/tx/{root-tx-id}/offset` to get the root transaction's absolute offset in the weave 3. Calculates the absolute offset for the requested data item 4. Fetches data in chunks using `/chunk/\/data` and assembles the complete data stream 5. Validates that chunks belong to the expected root transaction for security **Sequence Diagram:** ```mermaid sequenceDiagram participant Client participant Wayfinder participant Gateway as AR.IO Gateway participant Arweave as Arweave Nodes Client->>Wayfinder: request('ar://data-item-id') activate Wayfinder Wayfinder->>Gateway: HEAD /tx/{data-item-id} Note over Gateway: Lookup data item metadatafrom indexed bundles Gateway-->>Wayfinder: Headers:- x-root-tx-id (bundle ID)- x-data-offset- content-length Wayfinder->>Gateway: GET /tx/{root-tx-id}/offset Gateway->>Arweave: GET /tx/{root-tx-id}/offset Note over Arweave: Lookup transaction offsetin the weave Arweave-->>Gateway: Root transaction offset Gateway-->>Wayfinder: Root transaction offset in weave Note over Wayfinder: Calculate absolute offset:absolute = root_offset + data_offset loop For each chunk needed Wayfinder->>Gateway: GET /chunk/{absolute-offset}/data Note over Gateway: Serve chunk data fromindexed storage usingroot transaction ID Gateway-->>Wayfinder: Chunk data + validation headers(x-root-tx-id for security) Note over Wayfinder: Validate chunk belongsto expected root TX Wayfinder-->>Client: Stream chunk data end Wayfinder-->>Client: Complete response deactivate Wayfinder ``` **Example with createWayfinderClient:** ```javascript const wayfinder = createWayfinderClient({ dataRetrievalStrategy: new ChunkDataRetrievalStrategy(), }); // Fetch a data item from within an ANS-104 bundle const response = await wayfinder.request('ar://data-item-id'); ``` #### x402 Support Both data retrieval strategies support custom fetch implementations, allowing you to use x402-enabled fetch clients for paid gateway requests. ```javascript const x402Fetch = createX402Fetch({ /* payment config */ }); const wayfinder = createWayfinderClient({ fetch: x402Fetch, dataRetrievalStrategy: new ChunkDataRetrievalStrategy({ fetch: x402Fetch, }), }); ``` # Dynamic Routing (/wayfinder-core/dynamic-routing) Wayfinder supports a `resolveUrl` method which generates dynamic redirect URLs to a target gateway based on the provided routing strategy. This function can be used to directly replace any hard-coded gateway URLs, and instead use Wayfinder's routing logic to select a gateway for the request. #### ArNS names Given an ArNS name, the redirect URL will be the same as the original URL, but with the gateway selected by Wayfinder's routing strategy. ```javascript const redirectUrl = await wayfinder.resolveUrl({ arnsName: 'ardrive', }); // results in https://ardrive.\ ``` #### Transaction Ids Given a txId, the redirect URL will be the same as the original URL, but with the gateway selected by Wayfinder's routing strategy. ```javascript const redirectUrl = await wayfinder.resolveUrl({ txId: 'example-tx-id', }); // results in https://\/example-tx-id ``` #### Legacy URLs Given a legacy arweave.net or arweave.dev URL, the redirect URL will be the same as the original URL, but with the gateway selected by Wayfinder's routing strategy. ```javascript const redirectUrl = await wayfinder.resolveUrl({ originalUrl: 'https://arweave.net/example-tx-id', }); // results in https://\/example-tx-id ``` #### ar:// URLs Given an ar:// URL, the redirect URL will be the same as the original URL, but with the gateway selected by Wayfinder's routing strategy. ```javascript const redirectUrl = await wayfinder.resolveUrl({ originalUrl: 'ar://example-name/subpath?query=value', }); // results in https://\/example-name/subpath?query=value ``` # Events and Monitoring (/wayfinder-core/events-and-monitoring) #### Global Events ```javascript const wayfinder = createWayfinderClient({ routingSettings: { events: { onRoutingStarted: (event) => console.log('Routing started:', event), onRoutingSucceeded: (event) => console.log('Gateway selected:', event), }, }, verificationSettings: { events: { onVerificationProgress: (event) => { const percentage = (event.processedBytes / event.totalBytes) * 100; console.log(`Verification: ${percentage.toFixed(2)}%`); }, onVerificationSucceeded: (event) => console.log('Verified:', event.txId), }, }, }); ``` #### Request-Specific Events ```javascript const response = await wayfinder.request('ar://example', { verificationSettings: { events: { onVerificationProgress: (event) => { console.log(`This request: ${event.txId}`); }, }, }, }); ``` # Gateway Providers (/wayfinder-core/gateway-providers) Gateway providers supply the list of gateways for routing. **By default, `createWayfinderClient` uses a cached `TrustedPeersGatewaysProvider`**. | Provider | Description | Use Case | | ------------------------------ | ---------------------------------------------- | --------------------------------------- | | `NetworkGatewaysProvider` | Returns gateways from AR.IO Network | Leverage AR.IO Network with quality filtering | | `TrustedPeersGatewaysProvider` | Fetches from trusted gateway's peers | Dynamic gateway discovery (default) | | `StaticGatewaysProvider` | Returns a static list of gateways | Testing or specific gateways | | `SimpleCacheGatewaysProvider` | In-memory caching wrapper | Reduce API calls (used by default) | | `LocalStorageGatewaysProvider` | Browser localStorage caching | Persistent caching (used by default in browsers) | | `CompositeGatewaysProvider` | Chains multiple providers with fallback | Maximum resilience with multiple sources | #### NetworkGatewaysProvider Returns a list of gateways from the ARIO Network based on on-chain [Gateway Address Registry](https://docs.ar.io/learn/gateways/gateway-registry). You can specify on-chain metrics for gateways to prioritize the highest quality gateways. Requires `@ar.io/sdk` and `@solana/kit`. ```javascript const ario = ARIO.init({ rpc: createSolanaRpc('https://api.mainnet-beta.solana.com'), }); const gatewayProvider = new NetworkGatewaysProvider({ ario, sortBy: 'operatorStake', sortOrder: 'desc', limit: 10, filter: (gateway) => gateway.status === 'joined', }); ``` #### TrustedPeersGatewaysProvider Fetches a dynamic list of trusted peer gateways from an AR.IO gateway's `/ar-io/peers` endpoint. This provider is useful for discovering available gateways from a trusted source. ```javascript const gatewayProvider = new TrustedPeersGatewaysProvider({ trustedGateway: 'https://turbo-gateway.com', }); ``` #### CompositeGatewaysProvider Chains multiple gateway providers together, trying each in sequence until one succeeds. This is useful for building resilient gateway discovery with fallbacks. **How it works:** 1. Tries each provider in the order they're provided 2. If a provider returns a non-empty list of gateways, those gateways are used 3. If a provider throws an error or returns an empty list, moves to the next provider 4. If all providers fail, throws an error ```javascript import { CompositeGatewaysProvider, NetworkGatewaysProvider, StaticGatewaysProvider, TrustedPeersGatewaysProvider, } from '@ar.io/wayfinder-core'; const ario = ARIO.init({ rpc: createSolanaRpc('https://api.mainnet-beta.solana.com'), }); // Example: Network-first with static fallback const gatewayProvider = new CompositeGatewaysProvider({ providers: [ // Try fetching from AR.IO network first new NetworkGatewaysProvider({ ario, sortBy: 'operatorStake', limit: 10, }), // Fallback to trusted peers if network fetch fails new TrustedPeersGatewaysProvider({ trustedGateway: 'https://turbo-gateway.com', }), // Final fallback to static list new StaticGatewaysProvider({ gateways: ['https://turbo-gateway.com', 'https://g8way.io'], }), ], }); ``` # Wayfinder Core (/wayfinder-core) **Building for the web?** Consider using [@ar.io/wayfinder-react](/sdks/wayfinder/wayfinder-react) for React applications, which provides hooks and components optimized for browser environments. ## Quick Start ### Install ```npm npm install @ar.io/wayfinder-core @ar.io/sdk ``` ### Import and configure ```javascript const wayfinder = createWayfinderClient(); ``` ### Make your first request ```javascript // Use Wayfinder to fetch and verify data using ar:// protocol const response = await wayfinder.request('ar://ardrive'); console.log(response); ``` ### Use custom strategies ```javascript const customWayfinder = createWayfinderClient({ routingStrategy: createRoutingStrategy({ strategy: 'random' }) verificationStrategy: createVerificationStrategy({ strategy: 'hash', trustedGateways: ['https://turbo-gateway.com'] }) }); ``` ### Enable Telemetry (Optional) ```javascript const customWayfinder = createWayfinderClient({ telemetrySettings: { enabled: true, sampleRate: 0.1, // 10% sampling clientName: 'my-app', clientVersion: '1.0.0', } }); ``` ## Next Steps } title="Dynamic Routing" description="Use Wayfinder for dynamic routing" href="/sdks/wayfinder/wayfinder-core/dynamic-routing" /> } title="Gateway Providers" description="Learn about different gateway provider strategies" href="/sdks/wayfinder/wayfinder-core/networkgatewaysprovider" /> } title="Request Flow" description="Understanding how Wayfinder routes and verifies requests" href="/sdks/wayfinder/wayfinder-core/request-flow" /> } title="Monitoring & Events" description="Monitor performance and handle events" href="/sdks/wayfinder/wayfinder-core/global-events" /> # Request Flow (/wayfinder-core/request-flow) ```mermaid sequenceDiagram participant Client participant Wayfinder participant Gateways Provider participant Routing Strategy participant Selected Gateway participant Verification Strategy participant Trusted Gateways Client->>Wayfinder: request('ar://example') activate Wayfinder Wayfinder->>+Gateways Provider: getGateways() Gateways Provider-->>-Wayfinder: List of gateway URLs Wayfinder->>+Routing Strategy: selectGateway() Routing Strategy-->>-Wayfinder: Selected gateway Wayfinder->>+Selected Gateway: HTTP request Selected Gateway-->>-Wayfinder: Response data opt Verification enabled Wayfinder->>+Verification Strategy: verifyData() Verification Strategy->>Trusted Gateways: Get verification data Trusted Gateways-->>Verification Strategy: Verification headers Verification Strategy-->>-Wayfinder: Verification result end Wayfinder-->>Client: Response or error deactivate Wayfinder ``` # Resiliency (/wayfinder-core/resiliency) Wayfinder includes built-in resiliency features: - **Gateway retry**: If a gateway returns a 5xx error or a network failure occurs, Wayfinder automatically re-selects a different gateway and retries (up to 3 attempts). Client errors (4xx) are returned immediately without retry. - **Fetch timeouts**: All outbound requests include configurable timeouts — 10s for metadata (HEAD, peer list), 30s for data retrieval — to prevent indefinite hangs on slow or dead gateways. - **Smart pagination**: `NetworkGatewaysProvider` stops fetching from the on-chain registry once enough gateways pass the filter, avoiding unnecessary RPC calls. # Routing Strategies (/wayfinder-core/routing-strategies) Wayfinder supports multiple routing strategies to select target gateways for your requests. | Strategy | Description | Use Case | | ---------------------------- | ---------------------------------------------- | --------------------------------------- | | `RandomRoutingStrategy` | Selects a random gateway from a list | Good for load balancing and resilience | | `StaticRoutingStrategy` | Always uses a single gateway | When you need to use a specific gateway | | `RoundRobinRoutingStrategy` | Selects gateways in round-robin order | Good for load balancing and resilience | | `FastestPingRoutingStrategy` | Selects the fastest gateway based on ping time | Good for performance and latency | | `PreferredWithFallbackRoutingStrategy` | Uses a preferred gateway, with a fallback strategy if the preferred gateway is not available | Good for performance and resilience. Ideal for builders who run their own gateways. | | `CompositeRoutingStrategy` | Chains multiple routing strategies together, trying each sequentially until one succeeds | Good for complex fallback scenarios and maximum resilience | #### RandomRoutingStrategy Selects a random gateway from a list of gateways. ```javascript const strategy = new RandomRoutingStrategy({ gatewaysProvider: myGatewaysProvider, }); ``` #### FastestPingRoutingStrategy Selects the fastest gateway based on ping time. This strategy pings all available gateways and selects the one with the lowest latency. ```javascript const strategy = new FastestPingRoutingStrategy({ timeoutMs: 1000, gatewaysProvider: myGatewaysProvider, }); ``` #### PreferredWithFallbackRoutingStrategy Uses a preferred gateway, with a fallback strategy if the preferred gateway is not available. This is useful for builders who run their own gateways and want to use their own gateway as the preferred gateway, but also want to have a fallback strategy in case their gateway is not available. This strategy is built using `CompositeRoutingStrategy` internally. It first attempts to ping the preferred gateway (using `PingRoutingStrategy` with `StaticRoutingStrategy`), and if that fails, it falls back to the specified fallback strategy. ```javascript const strategy = new PreferredWithFallbackRoutingStrategy({ preferredGateway: 'https://my-gateway.com', fallbackStrategy: new FastestPingRoutingStrategy({ timeoutMs: 500 }), }); ``` #### CompositeRoutingStrategy The `CompositeRoutingStrategy` allows you to chain multiple routing strategies together, providing maximum resilience by trying each strategy in sequence until one succeeds. This is ideal for complex fallback scenarios where you want to combine different routing approaches. **How it works:** 1. Tries each strategy in the order they're provided 2. If a strategy successfully returns a gateway, that gateway is used (remaining strategies are skipped) 3. If a strategy throws an error, moves to the next strategy 4. If all strategies fail, throws an error **Common use cases:** - **Performance + Resilience**: Try fastest ping first, fallback to random if ping fails - **Preferred + Network**: Use your own gateway first, fallback to AR.IO network selection - **Multi-tier Fallback**: Try premium gateways, then standard gateways, then any available gateway ```javascript import { createWayfinderClient, CompositeRoutingStrategy, FastestPingRoutingStrategy, RandomRoutingStrategy, StaticRoutingStrategy, NetworkGatewaysProvider, } from '@ar.io/wayfinder-core'; const ario = ARIO.init({ rpc: createSolanaRpc('https://api.mainnet-beta.solana.com'), }); // Example 1: Performance-first with resilience fallback const performanceWayfinder = createWayfinderClient({ routingStrategy: new CompositeRoutingStrategy({ strategies: [ // Try fastest ping first (high performance, but may fail if all gateways are slow) new FastestPingRoutingStrategy({ timeoutMs: 500, gatewaysProvider: new NetworkGatewaysProvider({ ario, sortBy: 'operatorStake', limit: 10, }), }), // Fallback to random selection (guaranteed to work if gateways exist) new RandomRoutingStrategy({ gatewaysProvider: new NetworkGatewaysProvider({ ario, sortBy: 'operatorStake', limit: 20, // Use more gateways for fallback }), }), ], }), }); // Example 2: Preferred gateway with multi-tier fallback const preferredWayfinder = createWayfinderClient({ routingStrategy: new CompositeRoutingStrategy({ strategies: [ // First, try your preferred gateway new StaticRoutingStrategy({ gateway: 'https://my-preferred-gateway.com' }), // If that fails, try fastest ping from top-tier gateways new FastestPingRoutingStrategy({ timeoutMs: 1000, gatewaysProvider: new NetworkGatewaysProvider({ ario, sortBy: 'operatorStake', limit: 5, // Only top 5 gateways }), }), // Final fallback: any random gateway from a larger pool new RandomRoutingStrategy({ gatewaysProvider: new NetworkGatewaysProvider({ ario, limit: 50, // Larger pool for maximum availability }), }), ], }), }); ``` # Telemetry (/wayfinder-core/telemetry) Wayfinder can optionally emit OpenTelemetry spans for every request. **By default, telemetry is disabled**. You can control this behavior with the `telemetry` option. ```typescript const wayfinder = createWayfinderClient({ // other settings... telemetrySettings: { enabled: true, sampleRate: 0.1, // 10% sampling exporterUrl: 'https://your-otel-exporter', clientName: 'my-app', clientVersion: '1.0.0', }, }); ``` # Verification Strategies (/wayfinder-core/verification-strategies) Wayfinder includes verification mechanisms to ensure the integrity of retrieved data. Verification strategies offer different trade-offs between complexity, performance, and security. | Verifier | Complexity | Performance | Security | Description | | ------------------------------- | ---------- | ----------- | -------- | ------------------------------------------------------------------------------------------------------------ | | `RemoteVerificationStrategy` | Low | Low | Low | Checks the `x-ar-io-verified` header from the gateway that returned the data. If `true`, the data is considered verified and trusted. | | `HashVerificationStrategy` | Low | High | Low | Computes the SHA-256 hash of the returned data and comparing it to the hash of a **trusted gateway** (_**recommended for most users**_). | | `DataRootVerificationStrategy` | Medium | Medium | Low | Computes the data root for the transaction (most useful for L1 transactions) and compares it to the data root provided by a **trusted gateway**. | | `SignatureVerificationStrategy` | Medium | Medium | Medium | - **ANS-104 Data Items**: Fetches signature components (owner, signature type, tags, etc.) from trusted gateways using range requests, then verifies signatures against the data payload using deep hash calculations following the ANS-104 standard.- **L1 Transactions**: Retrieves transaction metadata from gateway /tx/\ endpoints, computes the data root from the provided data stream, and verifies the signature using Arweave's cryptographic verification. | #### RemoteVerificationStrategy This strategy is used to verify data by checking the `x-ar-io-verified` header from the gateway that returned the data. If the header is set to `true`, the data is considered verified and trusted. This strategy is only recommended for users fetching data from their own gateways and want to avoid the overhead of the other verification strategies. ```javascript const wayfinder = new Wayfinder({ verificationSettings: { // no trusted gateways are required for this strategy enabled: true, strategy: new RemoteVerificationStrategy(), }, }); ``` #### HashVerificationStrategy Verifies data integrity using SHA-256 hash comparison. This is the default verification strategy and is recommended for most users looking for a balance between security and performance. ```javascript const wayfinder = new Wayfinder({ verificationSettings: { enabled: true, strategy: new HashVerificationStrategy({ trustedGateways: [new URL('https://turbo-gateway.com')], }), }, }); ``` #### DataRootVerificationStrategy Verifies data integrity using Arweave by computing the data root for the transaction. This is useful for L1 transactions and is recommended for users who want to ensure the integrity of their data. ```javascript const wayfinder = new Wayfinder({ verificationSettings: { enabled: true, strategy: new DataRootVerificationStrategy({ trustedGateways: [new URL('https://turbo-gateway.com')], }), }, }); ``` #### SignatureVerificationStrategy Verifies signatures of Arweave transactions and data items. Headers are retrieved from trusted gateways for use during verification. For a transaction, its data root is computed while streaming its data and then utilized alongside its headers for verification. For data items, the ANS-104 deep hash method of signature verification is used. ```javascript const wayfinder = new Wayfinder({ verificationSettings: { enabled: true, strategy: new SignatureVerificationStrategy({ trustedGateways: [new URL('https://turbo-gateway.com')], }), }, }); ``` # x402 Payments (/wayfinder-core/x402-payments) Wayfinder can be configured to work with the [x402 payment protocol](https://docs.ar.io/learn/gateways/x402-payments#what-is-x402) for paid gateway services and higher rate limits. This allows you to seamlessly make requests that may require payment without having to manually handle payment flows. To get started, install the `@ar.io/wayfinder-x402-fetch` package. The `@ar.io/wayfinder-x402-fetch` package is a simple wrapper of the [x402-fetch](https://github.com/coinbase/x402/tree/1d4c253aef959b73b46d42e7f0ccf30c7ce64955/typescript/packages/x402-fetch) library, which creates a fetch implementation to automatically handles x402 payment flows. You can use this fetch implementation with Wayfinder to enable x402 payments for your requests. ```javascript // Set up your wallet for x402 payments const privateKey = process.env.X402_PRIVATE_KEY; // Your private key const account = privateKeyToAccount(privateKey); // Create x402-enabled fetch implementation const x402Fetch = createX402Fetch({ walletClient: account, }); // Create Wayfinder client with x402 fetch to handle payments const wayfinder = createWayfinderClient({ fetch: x402Fetch, routingSettings: { // Configure to use x402-enabled gateways strategy: new StaticRoutingStrategy({ gateway: 'https://paid-gateway.example.com', }), }, }); // Requests will now automatically handle x402 payments const response = await wayfinder.request('ar://transaction-id'); ``` **How it works:** 1. When a gateway returns a `402 Payment Required` status 2. The x402 fetch automatically handles the payment flow 3. The request is retried with payment credentials 4. You get access to premium gateway services **Use cases:** - Higher rate limits on data requests - Access to premium gateway features - Supporting gateway operators through payments To learn more about x402 payments, visit the [x402 documentation](https://docs.ar.io/learn/gateways/x402-payments). # useWayfinderRequest (/wayfinder-react/(hooks)/usewayfinderrequest) Fetch the data via wayfinder, and optionally verify the data. ```tsx function WayfinderData({ txId }: { txId: string }) { const request = useWayfinderRequest(); const [data, setData] = useState\(null); const [dataLoading, setDataLoading] = useState(false); const [dataError, setDataError] = useState\(null); useEffect(() => { (async () => { try { setDataLoading(true); setDataError(null); // fetch the data for the txId using wayfinder const response = await request(`ar://${txId}`, { verificationSettings: { enabled: true, // enable verification on the request strict: true, // don't use the data if it's not verified }, }); const data = await response.arrayBuffer(); // or response.json() if you want to parse the data as JSON setData(data); } catch (error) { setDataError(error as Error); } finally { setDataLoading(false); } })(); }, [request, txId]); if (dataError) { return Error loading data: {dataError.message}; } if (dataLoading) { return Loading data...; } if (!data) { return No data; } return ( {data} ); } ``` # useWayfinderUrl (/wayfinder-react/(hooks)/usewayfinderurl) Get a dynamic URL for an existing `ar://` URL or legacy `arweave.net`/`arweave.dev` URL. Example: ```tsx function WayfinderImage({ txId }: { txId: string }) { const { resolvedUrl, isLoading, error } = useWayfinderUrl({ txId }); if (error) { return Error resolving URL: {error.message}; } if (isLoading) { return Resolving URL...; } return ( ); } ``` # Wayfinder React (/wayfinder-react) A set of React hooks and components for integrating Wayfinder, the decentralized data access system for Arweave. Wayfinder-react wraps the functionality of wayfinder-core in user-friendly React components and hooks, making it easy to integrate ar.io network functionality into your React applications with built-in loading states, error handling, and caching. ## Quick Start ### Install Wayfinder React ```npm npm install @ar.io/wayfinder-react @ar.io/wayfinder-core @ar.io/sdk ``` ### Install polyfills (required for web environments) Crypto polyfills are required for web environments due to the use of `crypto`, `buffer` and `process` types in wayfinder-react dependencies (i.e. `arbundles`). ```npm npm install --save-dev vite-plugin-node-polyfills ``` ```js // vite.config.js plugins: [ nodePolyfills({ globals: { Buffer: true, global: true, process: true, }, }), ], }); ``` Configure your bundler (Webpack, Vite, Rollup, etc.) to provide polyfills for `crypto`, `process`, and `buffer`. Refer to your bundler's documentation for polyfill configuration. ### Setup the provider ```jsx // App.tsx function App() { return ( ); } ``` ### Use the available hooks ```typescript function WayfinderImage({ txId }: { txId: string }) { const { resolvedUrl, isLoading, error } = useWayfinderUrl({ txId }); if (error) { return Error resolving URL: {error.message}; } if (isLoading) { return Resolving URL...; } return ( ); } ``` ## Next Steps } title="Hooks Reference" description="Comprehensive guide to all available React hooks" href="/sdks/wayfinder/wayfinder-react/usewayfinderrequest" /> } title="Wayfinder Core" description="Learn about the underlying core library" href="/sdks/wayfinder/wayfinder-core" />