🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Decentralized Storage with IPFS: CIDs, Pinning, and Gateways

Decentralized Storage🟢 Free Lesson
Decentralized Storage

The one-line mental model

IPFS names content by the hash of what it contains rather than by where it is stored, so the same file resolves to the same name everywhere, and availability becomes a question of pinning rather than of hosting.

Prerequisites

  • !Hash functions and why identical inputs give identical digests
  • !HTTP basics: URLs, status codes, and caching headers

What You'll Learn

  • 1Explain how a CID encodes hashing algorithm, digest, and codec
  • 2Pin content deliberately and describe what garbage collection actually deletes
  • 3Chunk and add a large file correctly instead of relying on default settings
  • 4Store IPFS references on chain without creating an unusable dependency

Why the hash is the address

A conventional URL names a location: example.com/files/report.pdf, where the file could be replaced by anyone controlling that server at any moment while the address stays the same. Content addressing inverts the relationship. You compute a hash of the file's bytes, derive an identifier from that hash, and any node holding identical bytes can serve it. Substituting a different file produces a different identifier, so the name itself is a tamper-detection mechanism.

This inversion has a consequence that surprises newcomers: availability is no longer implied by the name existing. A URL keeps working as long as the server does; a content identifier keeps working only as long as some node still has the bytes and is willing to share them. On a public IPFS network, nodes that do not care about your file will eventually garbage-collect it, which is why pinning is a deliberate operational step rather than a default.

Anatomy of a CID

A content identifier is not a plain hash; it is a self-describing stack of fields that tells a client exactly how to interpret the bytes:

FieldExample valuePurpose
VersionCIDv1Allows the richer field layout below
Multicodecraw, dag-pb, carSays what the bytes represent
Multihash codesha2-256, blake3Names the hashing algorithm
Digest length32 bytesGuards against truncated inputs
Digest3f42…a19cThe actual hash of the content

Because the codec and algorithm are embedded, IPFS can evolve to stronger hashes without breaking older clients: a CIDv1 with a different multihash code is simply a different identifier that happens to point at the same bytes. Modern deployments default to CIDv1 encoded in base32 lowercase, which is what you should emit when you store references rather than the older, shorter base58 form used by some legacy tooling.

javascript
import { create, CID } from "multiformats/cid";
import { sha256 } from "multiformats/hashes/sha2";
import * as raw from "multiformats/codecs/raw";

async function computeCid(bytes) {
  const digest = await sha256.digest(bytes);
  const cid = CID.createV1(raw.code, digest);
  return cid.toString(); // base32, CIDv1
}

const metadata = new TextEncoder().encode(JSON.stringify({
  name: "Study Badge #7",
  image: "ipfs://bafybeigdyr…",
}));

console.log(await computeCid(metadata));
// bafkrei…  — same bytes always produce the same identifier

Computing the identifier locally, as above, lets you embed the expected CID in a contract or a manifest before any upload happens, which is the foundation of the verification pattern that matters most: after upload, fetch the content from a gateway and recompute the CID yourself instead of trusting the uploader's claim.

Adding, pinning, and retrieving

The workhorse commands run against a local Kubo daemon, and the flags you pass determine whether the result is durable:

# Start a local node (Kubo) and add a file with default chunking
ipfs daemon &
ipfs add --cid-version=1 notes.pdf

# Large file: smaller chunks, balanced DAG, faster retries
ipfs add --cid-version=1 --chunker=size-1048576 --raw-leaves=true archive.bin

# Pin by CID so local garbage collection will not delete it
ipfs pin add bafkrei7w2q…  --progress

# Verify what is actually pinned
ipfs pin ls --type=recursive | grep bafkrei7w2q

# Fetch through a gateway and confirm the bytes match
curl -sL "https://ipfs.io/ipfs/bafkrei7w2q…" -o fetched.bin
sha256sum archive.bin fetched.bin

--raw-leaves=true matters for deduplication and for verifiability: with raw leaves, each chunk is hashed independently, so two files sharing a large prefix share the corresponding chunks, and a light client can verify one chunk without downloading the rest. That property compounds across a collection: a hundred NFT metadata files that differ only in one field will share nearly every chunk, so the marginal storage cost of the hundredth file approaches the cost of the changed bytes alone.

Pinning on your own daemon protects against your own garbage collector, but it does not protect against node failure, so anything important needs either a second pinning provider or a Filecoin deal, and ideally both. Monitoring matters just as much as the pin itself: a provider can expire a pin, a billing card can fail, and the first sign of trouble is usually a gateway request that times out weeks later, at which point you are recovering from a cache rather than restoring an intended state. Schedule a weekly check that fetches a known CID from an independent gateway and compares the digest, and treat a failure as an incident rather than a nuisance.

Gateways, chunking, and the traps that bite in production

Gateways are ordinary HTTP servers that resolve content identifiers for browsers and services that cannot speak the IPFS wire protocol. They are the most reliable part of the stack and also the most frequently misunderstood:

ConcernWhat happensPractical response
Gateway outageYour images stop rendering even though content is fineRun two gateways with a fallback and keep CIDs in your data model
Default 256 KB chunkingLarge files split poorly; partial failures retry the whole fileSet an explicit chunker for anything over a few megabytes
No pinningContent vanishes from the network after a few daysPin locally and with at least one commercial provider
Mutable names (IPNS, DNSLink)Name resolves slowly or inconsistentlyPrefer immutable CIDs plus an on-chain pointer for critical data
Gateway cachingStale content after an updateContent addressing makes this a non-issue if you change the CID

The last row is worth pausing on, because it is the pleasant surprise in the system. With location addressing, updating a file means purging caches and hoping every layer respects the purge. With content addressing, a new file means a new identifier, and every cache in the path is automatically correct. The cost is that nothing is ever quietly overwritten, which means any privacy requirement must be handled by encryption before upload rather than by deletion afterwards.

Referencing IPFS content from a contract

Contracts store the identifier as a string or bytes and leave resolution to clients, because a contract cannot fetch HTTP and should not be trusted to interpret it:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract DocumentRegistry {
    struct Doc {
        bytes32 docId;
        string cid;
        address by;
        uint64 at;
    }

    mapping(bytes32 => Doc) public docs;

    event Registered(bytes32 indexed docId, string cid, address indexed by);

    function register(bytes32 docId, string calldata cid) external {
        require(bytes(docs[docId].cid).length == 0, "already registered");
        docs[docId] = Doc(docId, cid, msg.sender, uint64(block.timestamp));
        emit Registered(docId, cid, msg.sender);
    }

    function gatewayUrl(bytes32 docId, string memory gateway)
        external
        view
        returns (string memory)
    {
        return string(abi.encodePacked(gateway, "/", docs[docId].cid));
    }
}

Two refinements make this production-grade. First, store the CID in its canonical CIDv1 base32 form and validate the length on registration, so a typo becomes a revert instead of an unresolvable pointer. Second, if the content must remain private, encrypt before upload and store the encryption key or key-wrapping scheme off chain; a CID of an unencrypted file is a permanent public commitment to whatever you uploaded, whether or not you ever share the link again.

💡Verify uploads yourself

After adding content, fetch it through a gateway and recompute the digest before you accept the CID. A mistyped or maliciously substituted identifier renders as a broken image to users and as an unverifiable claim to auditors, and the failure usually surfaces weeks after the upload when nobody remembers the original file.

Common Mistakes

Relying on a single free gateway as your only retrieval path

Fix: Keep two independent gateways plus your own node, and make the gateway a runtime configuration rather than a hardcoded string

Uploading large files with default chunking and accepting whatever CID comes back

Fix: Set an explicit chunker and raw leaves for large media, then verify the digest after upload

Treating an unpinned CID as durable storage

Fix: Pin with at least two providers for anything referenced by a contract, and monitor that the pins still exist

Assuming deletion on IPFS removes the content

Fix: Encrypt before upload if privacy matters; content addressing makes copies that persist independently of your node

Best Practices

  • Compute CIDs locally and embed them in manifests so clients can verify rather than trust
  • Keep the CID version and encoding consistent across your stack to avoid two identifiers for the same bytes
  • Budget for commercial pinning from the first production deployment; free infrastructure will not carry a business
  • Where permanence truly matters and mutation does not, evaluate Arweave or a Filecoin deal instead of hoping pins survive

Interview Questions

Q1: Why does IPFS use content identifiers instead of URLs?

Because a content identifier is derived from the bytes themselves, so any node holding identical content can serve it, and any mismatch between name and content is detectable by recomputing the hash. URLs name locations, which say nothing about what bytes are actually served.

Q2: What does pinning actually prevent?

It marks content so that the pinning node's own garbage collector will not delete it. It does not guarantee the content is served by anyone else, which is why important content needs multiple independent pins or a storage deal.

Q3: Why store only the CID on chain rather than the data?

Storage on chain is replicated to every full node and priced accordingly, so large payloads are economically impossible. The CID is a tiny, permanent commitment that clients can resolve elsewhere, which gives permanence of reference without permanence of bulk data.

Key Takeaways

  • Content addressing makes the name a tamper check and makes availability a separate operational problem
  • CIDs embed codec and hash algorithm, so clients can evolve without breaking existing references
  • Pinning, chunking, and multiple gateways are the three operational choices that decide whether your data stays reachable
  • Contracts store identifiers, not data, and clients resolve and verify them
  • Encrypt before upload when privacy matters, because content addressing prevents quiet deletion
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement