Build a NextJS UI for Subgraphs on Somnia
Subgraphs allow developers to efficiently query Somnia blockchain data using GraphQL, making it easy to index and retrieve real-time blockchain activity. In this tutorial, you’ll learn how to:
Fetch blockchain data from a Subgraph API
Fix CORS errors using a NextJS API route
Display token transfers in a real-time UI
By the end of this guide, you'll have a fully functional UI that fetches and displays token transfers from Somnia’s Subgraph API.
Prerequisites
Basic knowledge of React & Next.js.
A deployed Subgraph API on Somnia (or use an existing one).
Account on https://somnia.chain.love see guide.
Create a NextJS Project
Start by creating a new Next.js app.
Then, install required dependencies.
Define the Subgraph API in Environment Variables
Create a .env.local file in the root folder.
💡 Note: Restart your development server after modifying .env.local:
Create a NextJS API Route for the Subgraph
Since the Somnia Subgraph API has CORS restrictions, we’ll use a NextJS API route to act as a proxy.
Inside the app directory create the folder paths api/proxy
and add a file route.ts
Update the route.ts
file with the following code:
This code allows your frontend to make requests without triggering CORS errors.
Fetch and Display Token Transfers in the UI
Now that we have the API set up, let’s build a React component that:
Sends the GraphQL query using fetch()
Stores the fetched data using useState()
Displays the token transfers in a simple UI
To fetch the latest 10 token transfers, we’ll use this GraphQL query:
This code fetches the last 10 transfers (first: 10) and orders them by timestamp (latest first). It retrieves wallet addresses (from, to) and the amount transferred (value) and includes the transaction hash (used to generate an explorer link).
Fetch and Display Data in a React Component
Now, let’s integrate the query into our NextJS frontend. Create a folder components
and add a file TokenTransfer.ts
We use useState()
to store transfer data and useEffect()
to fetch it when the component loads.
Once data is fetched, we render it inside the UI.
The UI shows a loading message while data is being fetched. When data is ready, it displays the latest 10 token transfers. It formats transaction values (value / 1e18) to show the correct STT amount and provides a link to view each transaction on Somnia Explorer.
Add the Component to the NextJS Page
Update the page.tsx file:
Restart the development server:
Now your NextJS UI dynamically fetches and displays token transfers from Somnia’s Subgraph! 🔥
Last updated