server-side-rpc-proxy.md
1 # Server-Side RPC Proxy 2 3 This document explains how the server-side RPC proxy works to protect private RPC URLs. 4 5 ## Overview 6 7 Instead of exposing private RPC URLs to the client, we use a server-side proxy that handles all RPC requests. This way, the private RPC URLs are only stored on the server and never exposed to the client. 8 9 ## Implementation 10 11 The implementation consists of two main parts: 12 13 1. **API Endpoint** (`pages/api/rpc-proxy.ts`): A Next.js API route that receives RPC requests from the client, forwards them to the appropriate RPC endpoint, and returns the result. 14 15 2. **Custom Provider** (`src/utils/ServerJsonRpcProvider.ts`): A custom ethers provider that routes all RPC requests through the API endpoint instead of directly connecting to the RPC URL. 16 17 ## Configuration 18 19 ### Environment Variables 20 21 Add your private alchemy RPC URLs to your server's environment variables: 22 23 ```env 24 MAINNET_RPC_API_KEY=<your-mainnet-rpc-api-key> 25 POLYGON_RPC_API_KEY=<your-polygon-rpc-api-key> 26 AVALANCHE_RPC_API_KEY=<your-avalanche-rpc-api-key> 27 # Add more as needed 28 ``` 29 30 ## Security Considerations 31 32 1. **Environment Variables**: Make sure your environment variables are properly secured and not leaked in client-side code. 33 34 2. **Rate Limiting**: Consider adding rate limiting to the API endpoint to prevent abuse. 35 36 ## How it Works 37 38 1. When the application needs to make an RPC request, it uses the `getProvider` function in `src/utils/marketsAndNetworksConfig.ts`. 39 40 2. If a private RPC URL is configured for the chain, it creates a `ServerJsonRpcProvider` for that chain. 41 42 3. When a method is called on the provider, it sends a request to the `/api/rpc-proxy` endpoint with the chain ID, method, and parameters. 43 44 4. The API endpoint looks up the private RPC URL for the specified chain, forwards the request, and returns the result. 45 46 5. The result is then returned to the caller as if it was fetched directly from the RPC endpoint. 47 48 ## Adding Support for More Chains 49 50 To add support for more chains: 51 52 1. Add the environment variable in your server environment (e.g., `ZKSYNC_RPC_API_KEY`). 53 54 2. Update the `NETWORK_CONFIG` object in `pages/api/rpc-proxy.ts` to include the new chain and network name.