Blog Home
>
>
A Beginner’s Guide to the Pinata Node.js SDK
A Beginner’s Guide to the Pinata Node.js SDK

A Beginner’s Guide to the Pinata Node.js SDK

7
Min read
A Beginner’s Guide to the Pinata Node.js SDK
Don't let the challenge of reconciling the storage layer of your decentralized stack get you down.

Reconciling the storage layer of the decentralized stack is deceivingly tricky. The main challenge for builders? Finding the right tools that will save them time and sanity. In the world of tooling that leverages the power of IPFS (InterPlanetary File System), Pinata’s robust collection of SDKs fills that gap, allowing builders to seamlessly communicate with IPFS in their application and achieve a decentralized file solution with ease.

The following blog is a beginner-friendly primer to the features and capabilities of the Pinata Node.js SDK. From concept to execution, following along will equip you with the knowledge to harness the magic of the Pinata SDK to utilize IPFS’s decentralized media distribution and management capabilities.

Here’s the video version for all your visual learners out there!

What Is Pinata?

Pinata began its journey in 2018 as the easiest way to use IPFS. Today it is so much more. We’re a full-fledged media distribution and management platform leveraging decentralized file systems. We’re on a mission to permanently shape the future of content distribution and management.

So, why Pinata? In addition to our adorable mascot Pinnie, we’re still the easiest way to use IPFS. We’re also the most secure and reliable out of all pinning services. So scale, security, speedYou can count on us for all of the above. Plus we have a range of flexible pricing plans no matter what level you’re at.

Before we get into the tutorial, let’s do a quick explainer on SDK vs API. This technical distinction is an important one to make before we get into the weeds of it all.

If you want to skip ahead, scroll down to “Part 1.”

SDK vs. API

An API is an application programming interface. We’re an API-first company, and our APIs helps you to communicate easily with the IPFS protocol, abstracting away all the fluff and complexity. It makes storing, managing and distributing content with IPFS as easy as any cloud-based storage system that you’re used to.

But then, as a developer, how do we go about actually using this API for our project?

This is where our software development kit (SDK) comes in. An SDK is a toolbox of code that makes it easier to work directly with an API. SDKs save you time and effort by providing a more streamlined development experience.

It’s like Nespresso coffee pods. The pods make it easy to make coffee, because inside each pod are the ingredients ready-to-go to make a cup of coffee, without having to grind the beans, get the measurements ready, and find the right tool to make it nice. You just pop it into your machine and enjoy.

Inside each SDK, you have specific API methods like <span class="code-inline">pinFileToIPFS</span>, <span class="code-inline">unpin</span> and <span class="code-inline">testAuthentication</span>. Important functions that are a bit more difficult to execute on their own. The Pinata SDK comes pre-loaded with built-in instructions to process each method and make a beautiful cup ‘o coffee.

Advantages of Using the SDK

It is technically possible to call the <span class="code-inline">pinFileToIPFS</span> using the raw API. You could directly make the HTTP requests, parse the responses and manually handle authentication. But if you have the well-oiled machine at hand, why not reap the benefits?

It is technically possible to call the pinFileToIPFS using the raw API. You could directly make the HTTP requests, parse the responses and manually handle authentication. But if you have the well-oiled machine at hand, why not reap the benefits?

It is technically possible to call the pinFileToIPFS using the raw API. You could directly make the HTTP requests, parse the responses and manually handle authentication. But if you have the well-oiled machine at hand, why not reap the benefits?

There are several advantages for using the SDK for developers:

  1. Simplified Integration: The Pinata SDK provides a higher-level abstraction layer that makes it easier to integrate the Pinata API. Instead of manually constructing API requests and handling low-level details, developers can bespoke functions and methods designed for Pinata operations. Write less code and speed up your building process.
  2. Enhanced Functionality and Convenience: Using the SDK, you may unlock additional features and utilities that go beyond the basic API calls. These may include built-in methods for handling file uploads, content pinning, metadata management, and more. Talk about an elevated developer experience!
  3. Versioning and Future Compatibility: Life is too short to worry if your API versions are aligned. Pinata’s API is ever-evolving, but with the SDK, you won’t have to stress about manually adapting the code to reflect these changes. In-built versioning support helps maintain the stability and continuity of your application, even after the aftermath of evolution 🌈.

Now we’re ready. Let’s look at how to use the Pinata SDK to build something amazing.

Prerequisites:

  1. A Pinata account (sign up here)
  2. A Pinata API key
  3. A package manager (like npm)
  4. Basic/Beginner JavaScript

Part 1: Set up an empty Node.js Project

If you already have a project set up, you can skip ahead to Step 2.

Alternatively, you can clone this repo and install dependencies by running <span class="code-inline">npm i</span>.

💡
This blog covers how to integrate the Pinata Node.js SDK. We have several SDKs for other languages including Python, Go, and more. Find them here

Firstly, navigate to your desired folder in your terminal. Create an empty directory and cd into it.

mkdir pinata-sdk-guide && cd pinata-sdk-guide

Initialize an empty npm project. You will see the following wizard.

This utility will walk you through creating a package.json file.

It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields and exactly
what they do.

Use `npm install <pkg>` afterwards to install a package and save it as a
dependency in the package.json file.

Press ^C at any time to quit.

package name: (pinata-sdk-guide)

You can press the <span class="code-inline">Enter</span> key through most of it, and customize your project as you wish. For this demo we will maintain <span class="code-inline">index.js</span> as our entry point.

If you open up your project in your code editor, you should see a <span class="code-inline">package.json</span> file.

Note:If you have cloned the above repository, you can skip this section and go straight to the ‘Authentication’ section.

Part 2: Install the Pinata SDK

You can have the SDK ready-to-go with one simple command:

npm i --save @pinata/sdk

After installation in complete, create your entry point file:

touch index.js

Part 3: Authentication

Setup

To use the SDK in your project, you’ll need to <span class="code-inline">require</span> kit and create a new instance of it at the top of your file.

const pinataSDK = require('@pinata/sdk');
const pinata = new pinataSDK('yourPinataApiKey', 'yourPinataSecretApiKey');

Before we move onto authentication, make sure you have your Pinata API key handy.

Don’t have a key yet?Create one today by logging into your Pinata account. Here's a video to guide you every step of the way.

dotenv

In order to keep sensitive information (like your API keys and secret) private, we’re going to install <span class="code-inline">dotenv</span>. Navigate back to your terminal, and run the following command:

npm i --save dotenv

If you go into your<span class="code-inline">package.json</span> file, you should see the installed dependency.

Next, create a new file in the root of your project called <span class="code-inline">.env</span>

touch .env
Note:This must be called .env otherwise it will not work.

In your new <span class="code-inline">.env</span> file, you will set up your environment variables like so:

PINATA_API_KEY=[YOUR_PINATA_API_KEY]
PINATA_API_SECRET=[YOUR_API_SECRET]

Afterwards, you will need to import your environment variables into <span class="code-inline">index.js</span>. At the very top of your file, insert the following:

require('dotenv').config();

Preferentially, I like to de-structure my variables like so:

const { PINATA_API_KEY, PINATA_API_SECRET } = process.env;

This way, you can pass your variables as arguments like this:

const pinataSDK = require('@pinata/sdk');
const pinata = new pinataSDK(PINATA_API_KEY, PINATA_API_SECRET);

Check authentication

Copy the first 4 lines of your <span class="code-inline">index.js</span>, navigate to <span class="code-inline">testAuthentication.js</span> and paste into the top of your file. Run the following command inside your terminal:

node testAuthentication.js

If all is well, you should receive the response <span class="code-inline">{ authenticated: true }</span> as a response. If not, double check your keys and sift through the code for any typos 👀.

Part 4: Pinning a File

In this section we’re going to learn how to use the Pinata SDK to call the <span class="code-inline">pinFIleToIPFS</span>, API method and pin a file to IPFS via our account.

Make sure you have the file you want to pin ready. This can be any type of file such as a picture, video, text and more. Store the file in the root of your folder, and navigate back to <span class="code-inline">index.js</span>.

Create a readable stream

<span class="code-inline">fs</span> (”file system”) is a built-in Node.js module that allows you to work with files on your computer.

We need to create a new <span class="code-inline">fs</span> object to create a ‘readable stream’ from our file.

const fs = require('fs');
const readableStreamForFile = fs.createReadStream('./[your_file_name.xxx]');

Specifying options

We are now going to create an <span class="code-inline">options</span> object in which we’ll combine our metadata and include any additional pinning options.

Read more about the available additional information object here.

// Example
const options = {
    pinataMetadata: {
        name: "[file_name",
        keyvalues: {
            key_1: 'value_1',
            key_2: 'value_2'
        }
    },
    pinataOptions: {
        cidVersion: X
    }
};

Calling the API method

All that is left to do now is to call the <span class="code-inline">pinFIleToIPFS</span> method onto the Pinata object.

Note that we pass in the <span class="code-inline">readableStreamForFile</span> and the <span class="code-inline">options</span> object as arguments.

// We pass in the readable stream for the file, ******and****** the options object.
pinata.pinFileToIPFS(readableStreamForFile, options).then((result) => {
    //handle results here
    console.log(result);
}).catch((err) => {
    //handle error here
    console.log(err);
});

Run the script by entering the following into your terminal:

node index.js

You should receive a response similar to the following:

{
  IpfsHash: 'QmZU3PxZWKCGxnpudtvuCLdKZAgdtW7MwNoGKUAxc8gTf3',
  PinSize: 5938492,
  Timestamp: '2023-05-11T16:28:32.823Z'
}

If you navigate to your Pinata dashboard in the web app, you should now see your file pinned to your account.

And voilà! You’ve successfully used the SDK to pin a file with Pinata.

Final Remarks

In this guide, we covered how to use the official Pinata Node.js SDK to pin a file to IPFS. You should be able to plug and play different API calls as we did with the pin file to IPFS one. If you’re building in another language, you can find more community-made SDKs here.

As a developer, the Pinata SDK will allow you to harness the magic of IPFS and implement a decentralized file solutions with ease.

Ready to ride the revolution of content distribution via decentralized file systems? Let’s go create something magical >> Access the Pinata SDK

Happy pinning!

7
MIN READ

H1 - THE RICH TEXT
EXAMPLE STARTS HERE

H2 - Enabling Widespread Adoption for Music NFTs

paragraph — The first thing the music industry needs is more exposure. For artists, listeners and yeah, the labels. Even with the use cases mentioned above, the majority of the music industry still sees NFTs as a novelty rather than a legitimate way to run a business. We see a future where the experience is built and monetized on the blockchain, with labels taking part of the experience, as well.

Second, there needs to be a big jump in user experience. Listeners know what to expect with Spotify and Apple Music: a smooth, intuitive experience that lets them listen to Lil Nas X with just a few clicks. Web3 platforms aren’t quite there. Music NFTs and related premium content require extra steps that most people don’t yet have an appetite for.

H3 - How Could Music NFTs Save Artists?

paragraph — Musician Daniel Allan spent months building a relationship with the NFT community and raised 50 ETH to fund his new album, Overstimulated. Companies like Audius and artists like Vérité's, who raised $90,000 in an NFT launch, are at the forefront of exploring new ways to get paid. Avenged Sevenfold launched an NFT collection called "Deathbats Club" with 10,000 items that grants holders access to benefits such as meet and greets at shows, lifetime free tickets, limited edition merchandise, and more.

Photo of ETHDenver 2022 with Pinata employees
This can also be styled!! Image caption.

H4 - Static and dynamic content editing

A rich text element can be used with static or dynamic content. For static content, just drop it into any page and begin editing. For dynamic content, add a rich text field to any collection and then connect a rich text element to that field in the settings panel. Voila!

H5 — How to customize formatting for each rich text

Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.

LINK — This is how a link looks like. Please provide normal & hover state (if different than this)

  • This will be bullet points
  • Numbered list is the same but with numbers
  • It has a margin-left applied
  1. Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.
  2. Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.
  3. Headings, paragraphs, blockquotes, figures, images, and figure captions can all be styled after a class is added to the rich text element using the "When inside of" nested selector system.
QUOTE — Everyone is obsessed with making money and seeking alpha, which does a disservice to what [NFTs] can actually do. We have been instructing many bands that NFTs are a ticket for access to an exclusive club.” - M. Shadows, Avenged Sevenfold’s lead singer.