A Beginner’s Guide to Getting Started With The Pinata Node.js SDK

Kelly Kim
Pinata
Published in
7 min readJun 7, 2023

--

This article originally appeared on the Pinata blog.

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 pinFileToIPFS , unpin and testAuthentication. 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 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 npm i.

💡 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 Enter key through most of it, and customize your project as you wish. For this demo we will maintain index.js as our entry point.

If you open up your project in your code editor, you should see a package.json 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 require it 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 dotenv. Navigate back to your terminal, and run the following command:

npm i --save dotenv

If you go into your package.json file, you should see the installed dependency.

Next, create a new file in the root of your project called .env

touch .env

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

In your new .env 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 index.js. 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 index.js, navigate to testAuthentication.js 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 { authenticated: true } 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 pinFIleToIPFS 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 index.js.

Create a readable stream

fs (”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 fs 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 options 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 pinFileToIPFS method onto the Pinata object.

Note that we pass in the readableStreamForFile and the options 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 voila! 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!

--

--

Kelly Kim
Pinata
Writer for

tech sis meets mukbang. korean-kiwi nomadic entrepreneur. building springr.xyz — airbnb for crypto nomads.