Building a DeFi frontend in React or Next.js means stitching together multiple APIs for swaps, prices, wallet data, and more. The DeFi ecosystem now holds over $180 billion in total value locked, and on-chain DEX trading volumes regularly exceed $10 billion per day. Meanwhile, Next.js powers over 25% of the top 10,000 websites and has become the default framework for crypto frontends thanks to its SSR, API routes, and edge runtime support. React-based frameworks dominate Web3 frontend development, with over 78% of DeFi dashboards and wallet interfaces built on React.
This guide covers the 7 APIs you actually need to build a production DeFi app in Next.js or React — from token swaps to NFT data — with TypeScript examples you can drop into your codebase today.
1. Swap API (swapapi.dev) — Token Swaps
Swap API is a free DEX aggregator that returns executable swap calldata from a single GET request. It covers 46 EVM chains, requires no API key, no registration, and no account. CORS headers are enabled by default, so you can call it directly from a React frontend without a proxy.
You send chainId, tokenIn, tokenOut, amount, and sender. You get back a complete transaction object with to, data, and value fields ready to submit via any wallet provider.
const res = await fetch(
"https://api.swapapi.dev/v1/swap/1?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48&amount=1000000000000000000&sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
);
const { data } = await res.json();
The response includes expectedAmountOut, minAmountOut with slippage protection, priceImpact, token metadata (symbol, decimals), and a list of recommended RPC URLs for the target chain. Partial fills return a Partial status with adjusted amounts instead of failing.
Here is a minimal React hook for swaps:
function useSwapQuote(chainId: number, tokenIn: string, tokenOut: string, amount: string, sender: string) {
const [quote, setQuote] = useState<SwapResponse | null>(null);
useEffect(() => {
if (!amount || !sender) return;
fetch(`https://api.swapapi.dev/v1/swap/${chainId}?tokenIn=${tokenIn}&tokenOut=${tokenOut}&amount=${amount}&sender=${sender}`)
.then(r => r.json())
.then(setQuote);
}, [chainId, tokenIn, tokenOut, amount, sender]);
return quote;
}
Executing the swap with wagmi/viem takes three lines:
const hash = await walletClient.sendTransaction({
to: data.tx.to as `0x${string}`,
data: data.tx.data as `0x${string}`,
value: BigInt(data.tx.value),
});
Why it ranks #1 for swaps: Zero config, no API key, 46 chains, CORS-friendly, and the response includes RPC URLs so you do not need a separate provider for transaction submission. Typical response time is 1-5 seconds.
Supported chains: Ethereum, Arbitrum, Base, Optimism, Polygon, BSC, Avalanche, Fantom, Sonic, Berachain, Monad, MegaETH, zkSync Era, Linea, Scroll, Blast, Mantle, and 29 more.
2. CoinGecko API — Prices and Market Data
CoinGecko is the standard for crypto price data. The free tier provides current prices, historical data, market caps, and 24h volume for over 15,000 tokens. For a DeFi frontend, you need prices to display portfolio values, chart token performance, and calculate USD equivalents.
const res = await fetch(
"https://api.coingecko.com/api/v3/simple/price?ids=ethereum,usd-coin&vs_currencies=usd&include_24hr_change=true"
);
const prices = await res.json();
The free tier allows 30 calls/minute without an API key. The Pro plan ($129/month) bumps this to 500 calls/minute and adds endpoints for OHLC candle data, DEX-specific pricing, and on-chain contract lookups.
For Next.js apps, fetch prices in getServerSideProps or a server action to avoid exposing API keys and to leverage caching:
export async function getServerSideProps() {
const res = await fetch("https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd");
return { props: { prices: await res.json() } };
}
Best for: Displaying token prices, portfolio valuation, sparkline charts, and market overview pages.
3. Alchemy — Wallet Balances and Token Data
Alchemy provides indexed blockchain data through its Enhanced APIs. For DeFi frontends, the key endpoints are getTokenBalances (all ERC-20 balances for a wallet), getTokenMetadata (name, symbol, decimals, logo), and getAssetTransfers (transaction history).
const res = await fetch("https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY", {
method: "POST",
body: JSON.stringify({ jsonrpc: "2.0", method: "alchemy_getTokenBalances", params: ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"], id: 1 }),
});
const { result } = await res.json();
The free tier includes 300M compute units per month, which covers roughly 3 million getTokenBalances calls. Alchemy supports Ethereum, Polygon, Arbitrum, Optimism, Base, and several other chains.
The alchemy-sdk package wraps these endpoints with TypeScript types. In a Next.js API route, you can aggregate multi-chain balances server-side and cache results with ISR.
Best for: Portfolio dashboards, wallet balance displays, transaction history pages, and any feature that requires indexed on-chain data.
4. WalletConnect / RainbowKit — Wallet Connection
Every DeFi app needs a wallet connection flow. RainbowKit provides a polished React modal that supports MetaMask, Coinbase Wallet, WalletConnect, and 100+ other wallets out of the box. It integrates directly with wagmi for chain management and transaction signing.
import { RainbowKitProvider, ConnectButton } from "@rainbow-me/rainbowkit";
function App() {
return (
<RainbowKitProvider>
<ConnectButton />
</RainbowKitProvider>
);
}
RainbowKit handles chain switching, ENS resolution, account display, and responsive styling. It requires a WalletConnect Cloud project ID (free), wagmi, and viem as peer dependencies.
For Next.js, wrap the provider in a client component and import it dynamically to avoid SSR hydration issues:
import dynamic from "next/dynamic";
const ConnectButton = dynamic(() => import("@rainbow-me/rainbowkit").then(m => m.ConnectButton), { ssr: false });
Best for: Production wallet connection UIs. Saves weeks of custom modal development and handles edge cases like mobile deep linking and WalletConnect v2 protocol.
5. Moralis — Portfolio and DeFi Positions
Moralis provides high-level portfolio APIs that aggregate token balances, NFT holdings, DeFi positions, and net worth calculations into single endpoints. The getWalletNetWorth endpoint returns a USD-denominated portfolio value across all supported chains in one call.
const res = await fetch(
"https://deep-index.moralis.io/api/v2.2/wallets/0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045/net-worth?chains=eth,polygon,arbitrum",
{ headers: { "X-API-Key": process.env.MORALIS_API_KEY! } }
);
const portfolio = await res.json();
The DeFi positions endpoint shows active LP positions, staking, lending, and borrowing across protocols like Aave, Uniswap, and Compound. This is useful for building portfolio trackers that go beyond simple token balances.
Moralis supports Ethereum, Polygon, BSC, Arbitrum, Optimism, Base, Avalanche, and Fantom. The free tier includes 40,000 compute units per day.
Best for: All-in-one portfolio pages that need to display token balances, NFTs, DeFi positions, and net worth without calling multiple separate APIs.
6. Reservoir — NFT Data and Trading
Reservoir provides normalized NFT APIs covering collection metadata, floor prices, token attributes, sales history, and order book data across OpenSea, Blur, LooksRare, and other marketplaces. For React DeFi apps that include NFT features, Reservoir replaces the need to integrate multiple marketplace APIs.
const res = await fetch(
"https://api.reservoir.tools/tokens/v7?collection=0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D&limit=20",
{ headers: { "x-api-key": process.env.RESERVOIR_KEY! } }
);
const { tokens } = await res.json();
Reservoir also provides a React SDK (@reservoir0x/reservoir-kit-ui) with pre-built components for buy, sell, and bid flows. The SDK handles wallet interactions, approval transactions, and order creation.
The free tier includes 4 requests/second. Paid plans add websocket feeds, bulk data access, and higher rate limits.
Best for: NFT marketplace features, collection pages, floor price tracking, and any app that needs aggregated order book data from multiple NFT marketplaces.
7. The Graph — Custom On-Chain Queries
The Graph is a decentralized indexing protocol that lets you query on-chain data using GraphQL. Major DeFi protocols publish subgraphs that expose their contract state as queryable APIs — pool reserves, swap events, governance votes, and more.
const res = await fetch("https://gateway.thegraph.com/api/YOUR_KEY/subgraphs/id/SUBGRAPH_ID", {
method: "POST",
body: JSON.stringify({ query: `{ pools(first: 10, orderBy: totalValueLockedUSD, orderDirection: desc) { id token0 { symbol } token1 { symbol } totalValueLockedUSD } }` }),
});
const { data } = await res.json();
The Graph is essential when you need data that no REST API provides: protocol-specific metrics, historical event logs, or cross-contract aggregations. The hosted service is free; the decentralized network charges per query (roughly $0.00004 per query).
For React apps, pair The Graph with a client like urql or @apollo/client for caching and real-time subscriptions.
Best for: Protocol-specific dashboards, analytics pages, governance UIs, and any feature that requires custom indexed blockchain data not available through standard APIs.
Comparison Table
| API | Use Case | API Key | Free Tier | Chains |
|---|---|---|---|---|
| Swap API | Token swaps | None | Unlimited | 46 EVM |
| CoinGecko | Prices/market data | Optional | 30 req/min | N/A |
| Alchemy | Wallet balances | Required | 300M CU/mo | 8+ |
| RainbowKit | Wallet connection | WC Project ID | Free | All EVM |
| Moralis | Portfolio/DeFi | Required | 40K CU/day | 8+ |
| Reservoir | NFT data | Required | 4 req/sec | 7+ |
| The Graph | Custom queries | Required | Hosted free | 40+ |
Putting It All Together
A production Next.js DeFi app typically combines 3-4 of these APIs. Here is a common stack:
- RainbowKit for wallet connection and chain switching
- Swap API for token swaps (the core DeFi action)
- CoinGecko for price display and charts
- Alchemy or Moralis for wallet balances and transaction history
The swap flow in a Next.js app looks like this:
const { data: walletClient } = useWalletClient();
const quote = useSwapQuote(1, ETH_ADDRESS, USDC_ADDRESS, amount, userAddress);
async function executeSwap() {
const hash = await walletClient!.sendTransaction({
to: quote.data.tx.to as `0x${string}`,
data: quote.data.tx.data as `0x${string}`,
value: BigInt(quote.data.tx.value),
});
}
Since Swap API includes RPC URLs in every response, you can use them as fallbacks for transaction submission without configuring a separate RPC provider.
FAQ
Do I need a backend for Swap API?
No. Swap API has CORS enabled, so you can call it directly from React. No API key means nothing to protect server-side.
Which chains does Swap API support?
46 EVM chains including Ethereum, Arbitrum, Base, Optimism, Polygon, BSC, Avalanche, zkSync Era, Linea, Scroll, Blast, Sonic, Berachain, Monad, and MegaETH.
How do I handle the amount parameter?
Amounts use the token's smallest unit. For ETH (18 decimals), 1 ETH = 1000000000000000000. For USDC on Ethereum (6 decimals), 100 USDC = 100000000. Always check the token's decimals field.
What about ERC-20 approvals?
For native-to-token swaps (like ETH to USDC), no approval is needed. For token-to-token swaps, the user must first approve the router contract returned in tx.to to spend their input token.
Can I use these APIs with React Native?
Yes. All REST APIs listed here work in React Native. RainbowKit has a separate @rainbow-me/rainbowkit-react-native package for mobile wallet connection.
Get Started
The fastest way to add swaps to a Next.js app:
- Install wagmi and viem:
npm install wagmi viem @tanstack/react-query - Fetch a quote from
https://api.swapapi.dev/v1/swap/{chainId} - Submit the returned
txobject viawalletClient.sendTransaction()
No API keys. No registration. Start building at swapapi.dev.
Top comments (0)