patternjavascriptTip
IPFS: storing and retrieving NFT metadata with content addressing
Viewed 0 times
Pinata SDK 2.x
IPFSCIDNFT metadatapinatatokenURIcontent addressingpinning
Problem
NFT metadata must be stored in a decentralized, immutable way so that the tokenURI cannot be changed after minting.
Solution
Upload metadata JSON to IPFS and store the CID in the tokenURI. Use services like Pinata or web3.storage with their SDKs. The tokenURI should be ipfs://CID/metadata.json.
const response = await pinata.pinJSONToIPFS(metadata);
const tokenUri = `ipfs://${response.IpfsHash}`;Why
IPFS uses content addressing — the CID is a hash of the content. Once set, the metadata cannot be altered without changing the CID, ensuring NFT immutability.
Gotchas
- IPFS content is only available while at least one node pins it — use a pinning service for persistence
- NFT marketplaces like OpenSea support ipfs:// URIs and resolve them via their own gateways
- Hardcoding an HTTP gateway (https://gateway.ipfs.io/ipfs/CID) creates centralization risk — use ipfs:// URI scheme
Code Snippets
Upload NFT metadata to IPFS via Pinata
import PinataSDK from '@pinata/sdk';
const pinata = new PinataSDK(process.env.PINATA_API_KEY, process.env.PINATA_SECRET);
async function uploadNFTMetadata(name, description, imageIPFSCid) {
const metadata = {
name,
description,
image: `ipfs://${imageIPFSCid}`,
attributes: [
{ trait_type: 'Background', value: 'Blue' },
],
};
const result = await pinata.pinJSONToIPFS(metadata);
return `ipfs://${result.IpfsHash}`;
}Context
Building an NFT minting contract with off-chain metadata storage
Revisions (0)
No revisions yet.