Displaying a User's NFT Collection on a Website
The user wants to show their NFTs on a website, but direct blockchain reads are slow and painful. ERC-721 doesn't have a tokensOfOwner method; you have to iterate over events or rely on ERC721Enumerable, which not every contract implements. We use specialized NFT APIs that index events and return ready-made lists. For example, for the BAYC collection, you get all tokens for an owner address in one request, without iterating millions of events. But there are pitfalls: IPFS gateways, slow loading, error handling. Our implementation accounts for all of this.
Why Not Read NFTs Directly from the Contract?
ERC-721 contracts store ownerOf(tokenId) and tokenURI(tokenId), but don't provide a reverse mapping. Without ERC721Enumerable, finding all tokens of a user via RPC means iterating all Transfer events in history or maintaining your own database. NFT APIs (Alchemy, Moralis, OpenSea) do the indexing for us — faster and more reliable. The alternative approach with a custom indexer requires infrastructure and development time, which is unjustified for most projects.
How to Fetch NFTs via Alchemy API
We use alchemy.nft.getNftsForOwner with SDK configuration.
// lib/nft.ts
import { Alchemy, Network, OwnedNft } from 'alchemy-sdk';
const alchemy = new Alchemy({
apiKey: process.env.ALCHEMY_API_KEY,
network: Network.ETH_MAINNET,
});
export interface NftItem {
tokenId: string;
contractAddress: string;
name: string;
description: string;
imageUrl: string;
collectionName: string;
attributes: Array<{ trait_type: string; value: string | number }>;
}
export async function getWalletNfts(
ownerAddress: string,
opts?: { contractAddresses?: string[]; pageSize?: number },
): Promise<NftItem[]> {
const response = await alchemy.nft.getNftsForOwner(ownerAddress, {
contractAddresses: opts?.contractAddresses,
pageSize: opts?.pageSize ?? 100,
omitMetadata: false,
});
return response.ownedNfts.map(mapNft);
}
function mapNft(nft: OwnedNft): NftItem {
const imageUrl = resolveIpfsUrl(
nft.image?.cachedUrl ?? nft.image?.originalUrl ?? '',
);
return {
tokenId: nft.tokenId,
contractAddress: nft.contract.address,
name: nft.name ?? `#${nft.tokenId}`,
description: nft.description ?? '',
imageUrl,
collectionName: nft.contract.name ?? 'Unknown Collection',
attributes: (nft.raw?.metadata?.attributes ?? []) as NftItem['attributes'],
};
}
function resolveIpfsUrl(url: string): string {
if (url.startsWith('ipfs://')) {
return url.replace('ipfs://', 'https://cloudflare-ipfs.com/ipfs/');
}
return url;
}
Example Alchemy API response (truncated)
{
"ownedNfts": [
{
"contract": { "address": "0x..." },
"tokenId": "1",
"tokenType": "ERC721",
"title": "My NFT",
"description": "...",
"metadata": { "image": "ipfs://..." }
}
],
"pageKey": "...",
"totalCount": 42
}
Alchemy NFT API Documentation
For real-time updates, WebSocket notifications about new tokens can be connected, which is useful for dynamic collections.
Gallery and Card Components
Gallery Component
We use React Query for fetching and caching data.
// components/NftGallery.tsx
import { useQuery } from '@tanstack/react-query';
import { getWalletNfts, NftItem } from '@/lib/nft';
interface NftGalleryProps {
address: string;
contractFilter?: string[];
}
export function NftGallery({ address, contractFilter }: NftGalleryProps) {
const { data, isLoading, error } = useQuery({
queryKey: ['nfts', address, contractFilter],
queryFn: () => getWalletNfts(address, { contractAddresses: contractFilter }),
staleTime: 60_000, // NFTs change rarely — cache for a minute
enabled: !!address,
});
if (isLoading) return <NftGridSkeleton count={12} />;
if (error) return <ErrorState message="Не удалось загрузить NFT" />;
if (!data?.length) return <EmptyState />;
return (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
{data.map(nft => (
<NftCard key={`${nft.contractAddress}-${nft.tokenId}`} nft={nft} />
))}
</div>
);
}
Card and Detail View
// components/NftCard.tsx
import { useState } from 'react';
import { NftItem } from '@/lib/nft';
export function NftCard({ nft }: { nft: NftItem }) {
const [imgError, setImgError] = useState(false);
return (
<div className="group relative overflow-hidden rounded-xl border border-white/10 bg-neutral-900">
<div className="aspect-square overflow-hidden bg-neutral-800">
{imgError ? (
<div className="flex h-full items-center justify-center text-neutral-500">
<ImageIcon className="h-12 w-12" />
</div>
) : (
<img
src={nft.imageUrl}
alt={nft.name}
loading="lazy"
decoding="async"
className="h-full w-full object-cover transition-transform group-hover:scale-105"
onError={() => setImgError(true)}
/>
)}
</div>
<div className="p-3">
<p className="truncate text-xs text-neutral-400">{nft.collectionName}</p>
<p className="mt-0.5 truncate font-medium text-white">{nft.name}</p>
</div>
</div>
);
}
// components/NftDetail.tsx
export function NftDetail({ nft }: { nft: NftItem }) {
return (
<div className="space-y-6">
<img src={nft.imageUrl} alt={nft.name} className="w-full rounded-2xl" />
<div>
<h2 className="text-2xl font-bold">{nft.name}</h2>
<p className="mt-1 text-sm text-neutral-400">
{nft.collectionName} · #{nft.tokenId}
</p>
</div>
{nft.description && (
<p className="text-sm leading-relaxed text-neutral-300">{nft.description}</p>
)}
{nft.attributes.length > 0 && (
<div>
<h3 className="mb-3 text-sm font-semibold uppercase tracking-wider text-neutral-500">
Attributes
</h3>
<div className="grid grid-cols-3 gap-2">
{nft.attributes.map((attr, i) => (
<div key={i} className="rounded-lg border border-blue-500/20 bg-blue-500/5 p-2 text-center">
<p className="text-xs text-blue-400">{attr.trait_type}</p>
<p className="mt-0.5 text-sm font-medium">{attr.value}</p>
</div>
))}
</div>
</div>
)}
</div>
);
}
Such a structure allows easy embedding of components into any React project.
ERC-1155 Support and Pagination
For ERC-1155 tokens, Alchemy returns balance. We check tokenType and add a quantity field. For large collections we implement pagination via pageKey.
// utils/nft-extras.ts
export function filterErc1155WithBalance(
nfts: OwnedNft[],
mapNft: (nft: OwnedNft) => NftItem,
) {
return nfts
.filter(nft => nft.tokenType === 'ERC1155')
.map(nft => ({
...mapNft(nft),
quantity: nft.balance,
}));
}
export async function getAllWalletNfts(
ownerAddress: string,
): Promise<NftItem[]> {
const all: NftItem[] = [];
let pageKey: string | undefined;
do {
const response = await alchemy.nft.getNftsForOwner(ownerAddress, {
pageKey,
pageSize: 100,
});
all.push(...response.ownedNfts.map(mapNft));
pageKey = response.pageKey;
} while (pageKey);
return all;
}
Comparison of Solutions
NFT API Comparison
| Criterion | Alchemy | Moralis | OpenSea |
|---|---|---|---|
| Multichain | Ethereum, Polygon, Optimism, Arbitrum | 20+ networks | Ethereum, Polygon, Klaytn |
| Free tier | 100k/month | 40k/month | 10k/month |
| Token types | ERC-721, ERC-1155 | ERC-721, ERC-1155 | ERC-721, ERC-1155 |
| Metadata | Automatic | Partial | Requires own |
| Pagination | pageKey | cursor | next |
RPC vs NFT API
| Aspect | Reading via RPC | NFT API |
|---|---|---|
| Speed | Slow (event iteration) | Fast (indexed data) |
| Complexity | Difficult (own database needed) | Simple (one endpoint) |
| ERC-1155 support | Need to handle separately | Built-in |
| IPFS images | Need caching | Automatically proxied |
Work Stages
- Analysis — determine which networks and contracts are needed, agree on API.
- Integration — connect SDK, implement fetching and display.
- Optimization — lazy loading, caching, error handling.
- Testing — verify on real wallets with large collections.
- Deployment — deploy to production, set up monitoring.
What's Included
- Documentation on integration and API key setup.
- Source code of React/TypeScript components.
- Deployment and update instructions.
- Test access to a working prototype.
- Support for 2 weeks after delivery.
Timelines and Cost
Basic gallery with Alchemy API, lazy loading, and detail view — 1–2 days. Extended version with collection filters, pagination, ERC-1155 support, and multichain — 3–4 days. Cost is calculated individually based on complexity and stack. For example, self-developed infrastructure and time can cost over $5,000; our solution is significantly cheaper. Contact us for a project estimate — we'll find the optimal solution.
Common Integration Mistakes
-
Unhandled IPFS — images don't load without a gateway. Always replace
ipfs://withhttps://cloudflare-ipfs.com/ipfs/. - Ignoring balance for ERC-1155 — can lead to incorrect display of quantity. Always check
tokenType. - Too short staleTime — NFTs change rarely; caching for 1–5 minutes significantly reduces API load.
- Missing fallback for images — show a placeholder on error, otherwise the user sees a broken icon.
For adding NFT search and filtering by collections, we integrate state on the frontend or use server-side search via the Alchemy API. This allows quick finding of desired tokens and sorting by collections.
We guarantee compatibility with leading collections and many years of experience integrating NFT APIs. We have been developing since 2018 and have implemented over 10 projects with NFT display for marketplaces and crypto portfolios. Get a consultation — order integration for your project. Using the Alchemy API can save up to $1,000 per month on servers and indexing.







