Store NFT on IPFS Using NFT Storage
Tags: nft, javascript, ipfs, crypto
Published: 2021-08-31 11:54:31

When we start a NFT project, we will implement the **ERC721** token that is the core part of the NFT project.  

The content of the NFT token is **metadata** that describes the the reference URL for the actual file.  
For example, the following Json data:

```json
// metadata.json
{
    "name": "The Cat",
    "description": "She is the cutest cat all over the world.",
    "image": "https://thecutestcat.com/cat-0001.png"
}
```

Look the "image" value in this file. This is the reference for the picture of `The Cat`. In this cast, the image file is hosted on a **off-chain** storage like Firebase, AWS, etc...  

But if you want to host it on a **on-chain** so that the image file is persistent, what do you do?  

Perhaps you will use a decentralized storage system like **IPFS**.  

In such a case, the above example would look like this:

```json
// metadata.json
{
    "name": "The Cat",
    "description": "She is the cutest cat all over the world.",
    "image": "https://ipfs.io/ipfs/bafybdiaxrmvcf234hilgoxmapfjcdfseyluhb3uxohebrhx5xilchm2gtq"
}
```

The URL of the "image" value ("**https://ipfs.io/ipfs/bafy...**") is called a **Content addressing**. Please check the **[IPFS Docs](https://docs.ipfs.io/concepts/content-addressing/#identifier-formats)**.  

There is an awesome tool that allows you to host your file on **IPFS** and gets the metadata URL starts from **https://ipfs.io/** easily.  
It's the **[NFT Storage](https://nft.storage/)**.


## NFT Storage

It is a new **Free** service that stores NFT data on **IPFS** and **Filecoin**.  

In this post, we use the npm package named `nft.storage` in Javascript file.  
The basic usage is introduced on the official top page, but **you cannot freely edit the content of metadata using this method**. So here I tell you **how to edit the content of the metadata**

But before that, login on the **[Official page](https://nft.storage/)** and create your **API Key** that is used when you use the `nft.storage` package in javascript file.  

## 1. Create a sample project

First of all, for example here, you will store a text file on **IPFS**.  

Create a directory and initialize a node project.  

```bash
mkdir store-nft
cd store-nft
npm init -y
```

Next, install the npm package `nft.storage`.

```bash
npm install nft.storage
```

And then, create a `sample.txt` on your project root.

```txt
// sample.txt
This is a sample.
```

## 2. Store file and metadata

To be able to edit the metadata as you like, first store the actual data(like `.txt`, `.jpg`, `.html`, etc...) to get its URL, then put the URL in metadata value and finally store the metadata. Let's do it.  

Create a `script.js` on your project root.

```bash
touch script.js
```

This is the entire code in `script.js`:

```javascript
// script.js
const { NFTStorage, Blob } = require('nft.storage');
const fs = require('fs');

// (1)
const client = new NFTStorage({ token: "YOUR_API_KEY" });

async function main() {
    // (2)
    fs.readFile('sample.txt', "utf-8", async (err, data) => {
        if (err) throw err;

        const url = await store(data);
        console.log("Stored NFT successfully!\nMetadata URL: ", url);
    });
}

async function store(data) {
    // (3)
    const fileCid = await client.storeBlob(new Blob([data]));
    const fileUrl = "https://ipfs.io/ipfs/" + fileCid;

    // (4)
    const obj = {
        "name": "The Sample Text",
        "information": "This is a sample text file.",
        "creator": "Michelle Branagah",
        "file_url": fileUrl
    };

    // (5)
    const metadata = new Blob([JSON.stringify(obj)], { type: 'application/json' });
    const metadataCid = await client.storeBlob(metadata);
    const metadataUrl = "https://ipfs.io/ipfs/" + metadataCid;

    return metadataUrl;
}

main();
```

### - Descriptions for the code -

**(1)** Create the client object of the NFT Storage using the API Key created earlier. 
**(2)** Read `sample.txt` file you created. 
**(3)** Store the file then you will get the **[CID(Content Identifiers)](https://docs.ipfs.io/concepts/content-addressing/)**. And create the **IPFS** URL by using it. `client.storeBlob()` function stores the file you specify and returns the file **CID**.
**(4)** Create metadata object. You can edit it freely. The value of "file_url" is the URL of `sample.txt`.
**(5)** Store metadata and create metadata URL.


## 3.Run the code

In project root, run the command:

```bash
node ./script.js
```

You should be able to get the metadata URL like the following:

```bash
Stored NFT successfully!
Metadata URL:  https://ipfs.io/ipfs/bafkreidk5ni7lbicn5a2y3jm2p6und5kkjgvpk5kwpnwvvtbwmt3r3uxgq
```