Astro
Get started using Pinata with Astro
Setup Astro
To create a new Astro project go ahead and run this command in the terminal:
You can select which options you prefer, but for this exmaple we’ll use the following:
After completing the project setup we can go ahead and cd
into the repo and install pinata-web3
.
Since we want to keep our API key private we will need to make sure our code is deployed server side, and we can use several different adapter options which you can view here. We also need a UI framework to handle our upload form, and there are many to choose from here. We’ll use vercel
and svelte
for this tutorial, and you can install them like so.
This should install the dependencies and alter the astro.config.mjs
for us.
Setup Pinata
In the src
folder make a new folder called utils
, and inside there make a file called pinata.ts
with the following contents:
This will create and export an instance of the IPFS SDK using environment variables, and to set those up make a new file at the root of the project called .env
with the following values:
Create Client Side Form
In the src
folder make another folder called components
, then inside there make file called UploadForm.svelte
.
This component creates a <form>
with a file <input>
as well as a <button>
to send it. The form will trigger the submit
function, which takes our form data and makes an API request to our server side code. Once complete the API will send response with a url
that we can use in the <img>
tag to display it on the page.
Server Side API Route
In the src/pages
folder make a new folder called api
and inside there make a file called upload.ts
. Paste the following code inside it:
This simple API route will parse the incoming formData
and get the file
we attached. If there isn’t a file attached we’ll send a error response. Otherwise we’ll upload the file using the SDK method pinata.upload.file
and deconstruct the response to get the IpfsHash
. With that IpfsHash
(aka CID
) we can use the convert
method to create a gateway URL that we can send back to the client.
Add Component to the Page
The last step here is to update the src/pages/index.astro
file with our new component!