For AI agents: the documentation index is at /llms.txt. Markdown versions of pages are available by appending .md to the URL.
Skip to main content

Indexing IPFS Data with Envio

Example Repository: The complete code for this guide can be found here

Introduction​

This guide demonstrates how to fetch and index data stored on IPFS within your Envio indexer. We'll use the Bored Ape Yacht Club NFT collection as a practical example, showing you how to retrieve and store token metadata from IPFS.

IPFS (InterPlanetary File System) is commonly used in blockchain applications to store larger data like images and metadata that would be prohibitively expensive to store on-chain. By integrating IPFS fetching capabilities into your indexers, you can provide a more complete data model that combines on-chain events with off-chain metadata.

Implementation Overview​

Our implementation will follow these steps:

  1. Create a basic indexer for Bored Ape Yacht Club NFT transfers
  2. Extend the indexer to fetch and store metadata from IPFS
  3. Handle IPFS connection issues with fallback gateways

Step 1: Setting Up the Basic NFT Indexer​

First, let's create a basic indexer that tracks NFT ownership:

Initialize the Indexer​

pnpx envio init

Choose From Address - Lookup ABI from block explorer, select ethereum-mainnet, and enter the Bored Ape Yacht Club contract address: 0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D. See the Quickstart for each prompt, or run it without prompts:

pnpx envio init --api-token "YOUR_ENVIO_API_KEY" contract-import explorer -c 0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D -b ethereum-mainnet --single-contract --all-events -d bored-ape-yacht-club-nft-indexer

--api-token writes your Envio API token to the new project's .env as ENVIO_API_TOKEN. See Quickstart with AI for running envio init non-interactively.

The generated src/indexer.test.ts tests the generated BoredApeYachtClub_* entities, so delete or rewrite it when you replace schema.graphql below. To test the effect without calling public gateways, see Effects in Tests.

Configure the Indexer​

Modify the configuration to focus on the Transfer events:

# config.yaml
name: bored-ape-yacht-club-nft-indexer
chains:
- id: 1
start_block: 0
end_block: 12299114 # Optional: limit blocks for development
contracts:
- name: BoredApeYachtClub
address:
- "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D"
events:
- event: Transfer(address indexed from, address indexed to, uint256 indexed tokenId)

Define the Schema​

Create a schema to store NFT ownership data:

# schema.graphql
type Nft {
id: ID! # tokenId
owner: String!
}

Implement the Event Handler​

Track ownership changes by handling Transfer events:

// src/handlers/BoredApeYachtClub.ts
import { indexer } from "envio";

const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";

indexer.onEvent(
{ contract: "BoredApeYachtClub", event: "Transfer" },
async ({ event, context }) => {
if (event.params.from === ZERO_ADDRESS) {
// mint
context.Nft.set({
id: event.params.tokenId.toString(),
owner: event.params.to,
});
} else {
// transfer
const nft = await context.Nft.getOrThrow(event.params.tokenId.toString());
context.Nft.set({
...nft,
owner: event.params.to,
});
}
},
);

Run your indexer with pnpm dev and visit http://localhost:8080 to see the ownership data:

Basic NFT ownership data

Step 2: Fetching IPFS Metadata​

Now, let's enhance our indexer to fetch metadata from IPFS:

Update the Schema​

Extend the schema to include metadata fields:

# schema.graphql
type Nft {
id: ID! # tokenId
owner: String!
image: String!
attributes: String! # JSON string of attributes
}

Create IPFS Effect​

Important! Preload optimization makes your handlers run twice. So instead of direct fetch calls, we're doing it through the Effect API.

Learn how Preload Optimization works in a dedicated guide. It might be a new mental model for you, but this is what can make indexing thousands of times faster.

BASE_URI_UID below is the CID from BAYC's tokenURI (ipfs://QmeSjSinHpPnmXmspMjwiXyN6zS4E9zccariGR3jxcaWtq/<tokenId>). For your own collection, call tokenURI(tokenId) on the contract (or read the URI from an event), strip the ipfs:// prefix and the trailing /<tokenId>, and use the rest (the CID plus any directory) as BASE_URI_UID. The fetch code below appends the token ID. To read tokenURI from a handler, use an effect as shown in Accessing Contract State.

Let's create the getIpfsMetadata effect in the src/utils/ipfs.ts file:

import { createEffect, S, type EffectContext } from "envio";

// Define the schema for the IPFS metadata
// It uses Sury library to define the schema
const nftMetadataSchema = S.schema({
image: S.string,
attributes: S.string,
});

// Infer the type from the schema
type NftMetadata = S.Infer<typeof nftMetadataSchema>;

// Unique identifier for the BoredApeYachtClub IPFS tokenURI
const BASE_URI_UID = "QmeSjSinHpPnmXmspMjwiXyN6zS4E9zccariGR3jxcaWtq";

// Try multiple endpoints to ensure data availability.
// Called inside the effect, so env vars are read per call. A comma-separated
// IPFS_GATEWAYS replaces the whole list, so tests can use only a local stub.
const getEndpoints = () =>
process.env.IPFS_GATEWAYS
? process.env.IPFS_GATEWAYS.split(",")
: [
// Optional paid gateway (set in .env)
...(process.env.PINATA_IPFS_GATEWAY ? [process.env.PINATA_IPFS_GATEWAY] : []),
"https://gateway.pinata.cloud/ipfs",
"https://ipfs.io/ipfs",
];

async function fetchFromEndpoint(
context: EffectContext,
endpoint: string,
tokenId: string
): Promise<NftMetadata | null> {
try {
const response = await fetch(`${endpoint}/${BASE_URI_UID}/${tokenId}`);
if (response.ok) {
const metadata: any = await response.json();
// `output` isn't checked on fresh results, so validate before returning
if (typeof metadata?.image !== "string" || metadata.attributes === undefined) {
context.log.warn(`IPFS metadata is missing fields`, { tokenId, endpoint });
return null; // try the next gateway
}
return {
image: metadata.image,
attributes: JSON.stringify(metadata.attributes),
};
} else {
context.log.warn(`IPFS didn't return 200`, { tokenId, endpoint });
return null;
}
} catch (e) {
context.log.warn(`IPFS fetch failed`, { tokenId, endpoint, err: e });
return null;
}
}

export const getIpfsMetadata = createEffect(
{
name: "getIpfsMetadata",
input: S.string,
output: nftMetadataSchema,
rateLimit: {
calls: 5,
per: "second",
},
},
async ({ input: tokenId, context }) => {
for (const endpoint of getEndpoints()) {
const metadata = await fetchFromEndpoint(context, endpoint, tokenId);
if (metadata) {
return metadata;
}
}

// ⚠️ Dangerous: Sometimes it's better to crash, to prevent corrupted data
// But we're going to use a fallback value, to keep the indexer process running.
// Both approaches have their pros and cons.
context.log.warn(
"Unable to fetch IPFS. Continuing with fallback metadata.",
{
tokenId,
}
);
// Don't cache the fallback, so a later run retries the gateways
context.cache = false;
return { attributes: `["unknown"]`, image: "unknown" };
}
);

Update the Event Handler​

Let's modify the event handler to fetch and store metadata using the getIpfsMetadata effect:

// src/handlers/BoredApeYachtClub.ts
import { indexer } from "envio";
import { getIpfsMetadata } from "../utils/ipfs";

const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";

indexer.onEvent(
{ contract: "BoredApeYachtClub", event: "Transfer" },
async ({ event, context }) => {
if (event.params.from === ZERO_ADDRESS) {
// mint
const metadata = await context.effect(
getIpfsMetadata,
event.params.tokenId.toString()
);
context.Nft.set({
id: event.params.tokenId.toString(),
owner: event.params.to,
image: metadata.image,
attributes: metadata.attributes,
});
} else {
// transfer
const nft = await context.Nft.getOrThrow(event.params.tokenId.toString());
context.Nft.set({
...nft,
owner: event.params.to,
});
}
},
);

When you run the indexer now, it will populate both ownership data and token metadata:

NFT ownership and metadata

Best Practices for IPFS Integration​

When working with IPFS in your indexers, consider these best practices:

1. Use Multiple Gateways​

IPFS gateways can be unreliable, so always implement multiple fallback options:

const getEndpoints = () => [
...(process.env.PINATA_IPFS_GATEWAY ? [process.env.PINATA_IPFS_GATEWAY] : []),
"https://gateway.pinata.cloud/ipfs",
"https://ipfs.io/ipfs",
];

2. Handle Failures Gracefully​

Always include error handling and provide fallback values:

try {
// IPFS fetch logic
} catch (error) {
context.log.error(`Failed to fetch from IPFS`, error as Error);
context.cache = false; // Don't cache the fallback
return { attributes: "[]", image: "default-image-url" };
}

3. Cache Results​

Set cache: true to save effect results in the indexer's database, so the same token's metadata isn't fetched again while the database is kept, including after a restart. This applies to every run, not only local development. Keep context.cache = false in the fallback branch so fallback metadata isn't saved. See Effect API Persistence for details.

export const getIpfsMetadata = createEffect(
{
name: "getIpfsMetadata",
input: S.string,
output: nftMetadataSchema,
rateLimit: {
calls: 5,
per: "second",
},
cache: true, // Enable caching
},
async ({ input: tokenId, context }) => {...}
);

Important: While the example repository includes SQLite-based caching, this approach is outdated and leads to many indexing issues.

Note: Don't commit the .envio/cache directory to your repository; it can get large. On Envio Cloud, save and restore effect caches from the dashboard instead. See Cache on Envio Cloud.

4. Learn about Preload Optimization​

Learn how Preload Optimization works and the Double-Run Footgun in a dedicated guide. It might be a new mental model for you, but this is what can make indexing thousands of times faster.

Understanding IPFS​

What is IPFS?​

IPFS (InterPlanetary File System) is a distributed system for storing and accessing files, websites, applications, and data. It works by:

  1. Splitting files into chunks
  2. Creating content-addressed identifiers (CIDs) based on the content itself
  3. Distributing these chunks across a network of nodes
  4. Retrieving data based on its CID rather than its location

Common Use Cases with Smart Contracts​

IPFS is frequently used alongside smart contracts for:

  • NFTs: Storing images, videos, and metadata while the contract manages ownership
  • Decentralized Identity Systems: Storing credential documents and personal information
  • DAOs: Maintaining governance documents, proposals, and organizational assets
  • dApps: Hosting front-end interfaces and application assets

IPFS Challenges​

IPFS integration comes with several challenges:

  1. Slow Retrieval Times: IPFS data can be slow to retrieve, especially for less widely replicated content
  2. Gateway Reliability: Public gateways can be inconsistent in their availability
  3. Data Persistence: Content may become unavailable if nodes stop hosting it

To mitigate these issues:

  • Use pinning services like Pinata or Infura to ensure data persistence
  • Implement multiple gateway fallbacks
  • Consider paid gateways for production applications