<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Steve Simkins on Medium]]></title>
        <description><![CDATA[Stories by Steve Simkins on Medium]]></description>
        <link>https://medium.com/@stevedylandev?source=rss-4d073fd47475------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a3mGjALu2oddI-KofmhAVw.jpeg</url>
            <title>Stories by Steve Simkins on Medium</title>
            <link>https://medium.com/@stevedylandev?source=rss-4d073fd47475------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:44:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stevedylandev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Use Orbiter With Git]]></title>
            <link>https://stevedylandev.medium.com/how-to-use-orbiter-with-git-364eede6cc19?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/364eede6cc19</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 14:20:40 GMT</pubDate>
            <atom:updated>2025-01-12T14:21:53.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Guxg07fKZcNgJ-1l" /></figure><p><a href="https://orbiter.host/blog/how-to-deploy-to-orbiter-with-git-hooks"><em>Originally shared on the Orbiter Blog</em></a></p><p>We built Orbiter as a simple hosting solution in a world of failed CD/CI pipelines and complex build setups. It can even be an escape from Git as we recently just added Version support, making it easy to rollback or preview a previous version of your website. However with all of these features, we should also say you can still use Git in your workflow and even automate your Orbiter deployments. I (Steve) personally love working in the terminal and have written about it frequently, and it’s also why I love building CLIs. I built the Orbiter CLI as a tool for those like me who want the best of both worlds: simplicity with terminal access.</p><p>One of those special terminal tools not many people are familiar with are <a href="https://git-scm.com/book/ms/v2/Customizing-Git-Git-Hooks">Git Hooks</a>. These are scripts you can run based on certain Git conditions, and in this post we’ll show you how you can easily make a Git Hook to deploy your Orbiter site after you commit some changes. Let’s get started!</p><h3>Setup</h3><p>One simple thing you need here is Git installed on your machine, but most of them come with it out of the box. If not simply follow <a href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">this guide</a>. If you haven’t already you should follow one of our guides to hosting on Orbiter, like this one for <a href="https://orbiter.host/blog/how-to-host-a-react-site">React</a> or this one for <a href="https://orbiter.host/blog/how-to-host-an-astro-site">Astro</a>. Both of those initialize the repo with Git, but in the case they didn’t it’s very easy to do. Just run the following command:</p><pre>git init</pre><p>The other piece you’ll need is the Orbiter CLI which can be installed with just one command:</p><pre>npm i -g orbiter-cli</pre><p>Once you’ve downloaded the CLI run the login command with your provider of choice, google or github.</p><pre>orbiter login -p google</pre><p>Last thing you need to do is build your site and then upload it to Orbiter. You can do this with the following command:</p><pre>npm run build &amp;&amp; orbiter create -d mysite ./dist</pre><p>The first one creates the dist folder, the second creates a site with the domain mysite.orbiter.website, and uses the dist folder we just built.</p><h3>Creating the Hook</h3><p>Now that we have all our pieces in place we can build our Git hook. This one will do the following after we commit changes:</p><ul><li>Build our site</li><li>Update our site with the new dist folder</li></ul><p>If you run ls -a in your terminal you should see something called .git; this is actually a folder with all of our Git information like commits and settings. In there by default is another folder called hooks, and that’s where we’ll create our post commit hook. Run the following command inside your terminal:</p><pre>touch .git/hooks/post-commit</pre><p>Now you’ll want to open this new file with your text editor of choice. Once you open the blank file paste in the following code:</p><pre>#!/bin/bash<br># Path: .git/hooks/post-commit<br># Make sure to make this file executable: chmod +x .git/hooks/post-commit<br><br>echo &quot;Running orbiter update...&quot;<br><br># Run the CLI command here<br>npm run build &amp;&amp; orbiter update -d &lt;your-domain&gt; dist<br><br># Alternatively you can use the --siteId instead<br># orbiter update -s &lt;site-id&gt; dist<br><br># Check if the command was successful<br>if [ $? -eq 0 ]; then<br>    echo &quot;Orbiter update completed successfully&quot;<br>    exit 0<br>else<br>    echo &quot;Orbiter update failed&quot;<br>    exit 1<br>fi</pre><p>This is a pretty simple bash script that will run a few commands:</p><ul><li>npm run build - Creates a dist folder for the latest version of our site</li><li>orbiter update -d &lt;your-domain&gt; dist - Updates our site using the new dist folder. We set which site using the -d flag followed by our subdomain. For instance, if I have a site called <a href="http://astro.orbiter.website/">astro.orbiter.website</a> then I would use -d astro.</li></ul><p>Make sure these are both adjusted for your setup, whether you’re using Yarn instead of NPM or your build folder is name something other than dist. Also of course make sure you update the domain! Save your changes then in the terminal run this command:</p><pre>sudo chmod +x .git/hooks/post-commit</pre><p>This will turn your Git hook into an executable bash script. Now we can test it out! Make a change to your website then commit it like so:</p><pre>git add .<br><br>git commit -m &quot;Testing Git hooks!&quot;</pre><p>Then you should see the build compiling and the update to your website made!</p><h3>Wrapping Up</h3><p>Git is really powerful, and there’s a reason it’s become the default version managing software used around the world. While there’s a lot you can do with it, for most people you may just want a simple way to undo a deployment or mistake you made to restore your website. In which case definitely check out our versions feature which makes it a breeze to update your site to an older version.</p><p>Want to give it a shot? Be sure to <a href="https://app.orbiter.host/">try it out on one of our paid plans today</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=364eede6cc19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building IPDB: A Decentralized Database using Base, IPFS, and PGlite]]></title>
            <link>https://medium.com/pinata/building-ipdb-a-decentralized-database-using-base-ipfs-and-pglite-98897bfa98b2?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/98897bfa98b2</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[decentralization]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[base]]></category>
            <category><![CDATA[ipfs]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 15:26:35 GMT</pubDate>
            <atom:updated>2024-10-09T16:36:05.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8A62ZYSyvVZ0koAJ1vGHrw.png" /></figure><p>As Web3 technology has progressed, we’ve seen it replace most computing paradigms with decentralized solutions. However the one exception has been traditional databases. Trying to use EVM smart contracts to store tables ends up being inefficient due to gas and compute costs, and solutions like IPFS don’t work since all files are static. However, new database libraries, like PGLite, could change the discourse and invent a whole new way to manage local and distributed remote databases.</p><p>In this post, we’ll go over a rough proposal, which I’m calling “IPDB” or “InterPlanetary Database.” Keep in mind that while this is not a perfect solution for every use case, it is an interesting path we could see more of in the future. Companies like <a href="https://electric-sql.com/">ElectricSQL</a> who are developing <a href="https://pglite.dev/">PGlite</a> and pushing a model where databases are local first and then sync to a remote database through a sync engine. If you take this model and find a way to create a distributed sync engine, then you have a really unique solution for the Web3 ecosystem!</p><h3>Concept</h3><p>The main idea behind IPDB is go local first and then have a backup system with IPFS and smart contracts on <a href="https://base.org/">Base</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FrD12Svl9ZWTmxOVtgSqA.png" /></figure><p>This flow would involve several steps. First, you would need to create an initial database with your defined tables, dump the database directory into a tarball file, upload that file to IPFS via Pinata, then use a custom smart contract to track the IPFS hash as sort of an index. Once initiated, you can have a client app that will first check if there is a <a href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> file in the browser. If not, it will make a request to the smart contract for the latest index hash, then use that hash to make a request to IPFS for the file. Once the file is downloaded, you can save it to IndexedDB and use it as the database in browser.</p><p>At any point, you can initiate a backup and restore kind of sync, where you can upload an updated database file to IPFS, get a new hash (since all IPFS CIDs are determined by the content), then update the smart contract index with the new hash. You can equally do the opposite where you clear the in-browser IndexedDB to get the most recent database file. In the end, you get a local first database that is incredibly snappy, lightweight, and portable. If you wanted to make it private, then you could try encrypting and decrypting the file or use a fully private system like Pinata’s Files API. Let’s go over some of the details of how we implemented this into a simple to-do app.</p><h3>Smart Contract</h3><p>The beauty of this model is that you can make it as simple or as complicated as you want. For this to-do app, we really one need the following:</p><ul><li>A state variable in the form of a string</li><li>A method to update the state</li><li>A method to get the latest state</li><li>Bonus: An event to emit when the state is updated</li><li>Ownable restrictions</li></ul><p>With those requirements, we have one really simple contract that only the deployer can update.</p><pre>// SPDX-License-Identifier: MIT<br><br>// Compatible with OpenZeppelin Contracts ^5.0.0<br>pragma solidity ^0.8.20;<br><br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br><br>contract IPDB is Ownable {<br>    string private dbState;<br><br>    event dbUpdated(string newCid);<br><br>    constructor() Ownable(msg.sender) {}<br><br>    function update(string memory cid) public onlyOwner {<br>        dbState = cid;<br>        emit dbUpdated(cid);<br>    }<br><br>    function getState() public view returns (string memory) {<br>        return dbState;<br>    }<br>}</pre><p>For our IPDB app, I just deployed this smart contract on Base, copied down the address, and then saved the ABI to be used in our client app. Thanks to the speed and cost effectiveness of Base, we can really utilize this contract to handle our index of state.</p><h3>Client</h3><p>We won’t go too deep into the framework and setup, but in summary, for the app I decided to use <a href="https://pinata.cloud/blog/how-to-upload-files-with-astro-and-pinata/">Astro</a> with a React integration, but you could really use any framework you want as long as it has a way to have secured API routes / server rendered code to keep API keys secure. We’re also going with a local private key method to write to our smart contract, but you could change this to be through a user’s wallet instead, if you wanted to. I’m also not going to do a step by step tutorial, but the source code can be found <a href="https://github.com/PinataCloud/ipdb">here</a> if you want to follow along!</p><p>One of the first things we’re going to make is the script to initialize the database.</p><pre>import { pinata, publicClient, walletClient } from &quot;@/utils/config&quot;;<br>import { account } from &quot;@/utils/account&quot;;<br>import { abi } from &quot;@/utils/contract.json&quot;;<br>import { PGlite } from &quot;@electric-sql/pglite&quot;;<br><br>(async () =&gt; {<br> const db = new PGlite();<br> await db.exec(`<br>    CREATE TABLE IF NOT EXISTS todo (<br>      id SERIAL PRIMARY KEY,<br>      task TEXT,<br>      done BOOLEAN DEFAULT false<br>    );<br>  `);<br> const file = (await db.dumpDataDir(&quot;auto&quot;)) as File;<br> const upload = await pinata.upload.file(file);<br> const { request: contractRequest } = await publicClient.simulateContract({<br>  account,<br>  address: import.meta.env.PUBLIC_CONTRACT_ADDRESS,<br>  abi: abi,<br>  functionName: &quot;update&quot;,<br>  args: [`${upload.IpfsHash}`],<br> });<br> const tx = await walletClient.writeContract(contractRequest);<br> console.log(tx);<br>})();</pre><p>In this script, we create our initial database with PGlite as well as create our to-do table, which just has a simple id, task, and done status. Then we dump that database directory as a tarball file, upload it using Pinata to IPFS, then we make a smart contract function call to update the state using our IPFS hash from the upload. Once this is done we’ll have a starting point for the app to use.</p><p>Next, we’ll have our really big React component which really handles all of our functionality.</p><pre>import { PGlite } from &quot;@electric-sql/pglite&quot;;<br>import { Button } from &quot;./ui/button&quot;;<br>import { useState, useEffect } from &quot;react&quot;;<br>import { Input } from &quot;./ui/input&quot;;<br>import { Checkbox } from &quot;./ui/checkbox&quot;;<br>import { publicClient, pinata } from &quot;@/utils/config&quot;;<br>import { abi } from &quot;@/utils/contract.json&quot;;<br>import { checkDatabaseExists } from &quot;@/utils/db&quot;;<br>import { ReloadIcon } from &quot;@radix-ui/react-icons&quot;;<br>import { useToast } from &quot;@/hooks/use-toast&quot;;<br><br>let db: PGlite | undefined;<br><br>interface ToDo {<br> id: number;<br> task: string;<br> done: boolean;<br>}<br><br>export default function Database() {<br> const [todos, setTodos] = useState&lt;ToDo[]&gt;([]);<br> const [taskName, setTaskName] = useState(&quot;&quot;);<br> const [loading, setLoading] = useState(true);<br> const [saving, setSaving] = useState(false);<br> const { toast } = useToast();<br><br> async function importDb() {<br>  try {<br>   setLoading(true);<br>   const dbCid = await publicClient.readContract({<br>    address: import.meta.env.PUBLIC_CONTRACT_ADDRESS,<br>    abi: abi,<br>    functionName: &quot;getState&quot;,<br>   });<br>   console.log(dbCid);<br>   const dbExists = await checkDatabaseExists(&quot;todo-db&quot;);<br>   if (!dbExists) {<br>    const dbFile = await pinata.gateways.get(dbCid as unknown as string);<br>    const file = dbFile.data as Blob;<br>    db = new PGlite({<br>     loadDataDir: file,<br>     dataDir: &quot;idb://todo-db&quot;,<br>    });<br>    console.log(&quot;used remote db&quot;);<br>   } else {<br>    db = new PGlite({<br>     dataDir: &quot;idb://todo-db&quot;,<br>    });<br>    console.log(&quot;used local db&quot;);<br>   }<br>   const ret = await db?.query(`<br>    SELECT * from todo ORDER BY id ASC;<br>   `);<br>   setTodos(ret?.rows as ToDo[]);<br>   toast({<br>    title: &quot;Database Restored&quot;,<br>   });<br>   setLoading(false);<br>  } catch (error) {<br>   setLoading(false);<br>   console.log(error);<br>  }<br> }<br><br> async function addTodo() {<br>  try {<br>   await db?.query(&quot;INSERT INTO todo (task, done) VALUES ($1, false)&quot;, [<br>    taskName,<br>   ]);<br>   const ret = await db?.query(`<br>        SELECT * from todo;<br>      `);<br>   setTodos(ret?.rows as ToDo[]);<br>   setTaskName(&quot;&quot;);<br>   console.log(ret?.rows);<br>  } catch (error) {<br>   console.log(error);<br>  }<br> }<br><br> async function updateTodo(id: number, done: boolean) {<br>  try {<br>   await db?.query(&quot;UPDATE todo SET done = $1 WHERE id = $2&quot;, [done, id]);<br>   const ret = await db?.query(&quot;SELECT * from todo ORDER BY ID ASC;&quot;);<br>   setTodos(ret?.rows as ToDo[]);<br>  } catch (error) {<br>   console.log(error);<br>  }<br> }<br> async function deleteTodo(id: number) {<br>  try {<br>   await db?.query(&quot;DELETE FROM todo WHERE id = $1&quot;, [id]);<br>   const ret = await db?.query(&quot;SELECT * from todo ORDER BY ID ASC;&quot;);<br>   setTodos(ret?.rows as ToDo[]);<br>  } catch (error) {<br>   console.log(error);<br>  }<br> }<br><br> async function saveDb() {<br>  try {<br>   setSaving(true);<br>   const dbFile = await db?.dumpDataDir(&quot;auto&quot;);<br>   if (!dbFile) {<br>    throw new Error(&quot;Failed to dump database&quot;);<br>   }<br>   const data = new FormData();<br>   data.append(&quot;file&quot;, dbFile);<br>   const req = await fetch(&quot;/api/upload&quot;, {<br>    method: &quot;POST&quot;,<br>    body: data,<br>   });<br>   const res = await req.json();<br>   console.log(res);<br>   toast({<br>    title: &quot;Database Saved&quot;,<br>   });<br>   setSaving(false);<br>  } catch (error) {<br>   setSaving(false);<br>   console.log(error);<br>  }<br> }<br><br> function taskNameHandle(e: React.ChangeEvent&lt;HTMLInputElement&gt;) {<br>  setTaskName(e.target.value);<br> }<br><br> useEffect(() =&gt; {<br>  importDb();<br> }, []);<br><br> return (<br>  &lt;div className=&quot;flex flex-col gap-2&quot;&gt;<br>   {loading ? (<br>    &lt;ReloadIcon className=&quot;h-12 w-12 animate-spin&quot; /&gt;<br>   ) : (<br>    &lt;&gt;<br>     &lt;div className=&quot;flex flex-row items-center gap-4&quot;&gt;<br>      &lt;Input value={taskName} onChange={taskNameHandle} type=&quot;text&quot; /&gt;<br>      &lt;Button onClick={addTodo}&gt;Add Todo&lt;/Button&gt;<br>     &lt;/div&gt;<br>     &lt;div className=&quot;flex flex-col gap-2 items-start&quot;&gt;<br>      {todos ? (<br>       todos.map((item: ToDo) =&gt; (<br>        &lt;div<br>         className=&quot;w-full flex items-center justify-between gap-2&quot;<br>         key={item.id}<br>        &gt;<br>         &lt;div className=&quot;flex items-center gap-2&quot;&gt;<br>          &lt;Checkbox<br>           onCheckedChange={(checked) =&gt;<br>            updateTodo(item.id, checked as boolean)<br>           }<br>           checked={item.done}<br>          /&gt;<br>          &lt;p className={item.done ? &quot;line-through&quot; : &quot;&quot;}&gt;<br>           {item.task}<br>          &lt;/p&gt;<br>         &lt;/div&gt;<br>         &lt;Button<br>          size=&quot;icon&quot;<br>          variant=&quot;destructive&quot;<br>          onClick={() =&gt; deleteTodo(item.id)}<br>         &gt;<br>          X<br>         &lt;/Button&gt;<br>        &lt;/div&gt;<br>       ))<br>      ) : (<br>       &lt;p&gt;No todos yet&lt;/p&gt;<br>      )}<br>     &lt;/div&gt;<br>     &lt;div className=&quot;w-full&quot;&gt;<br>      {saving ? (<br>       &lt;Button className=&quot;w-full&quot; disabled&gt;<br>        &lt;ReloadIcon className=&quot;mr-2 h-4 w-4 animate-spin&quot; /&gt;<br>        Saving...<br>       &lt;/Button&gt;<br>      ) : (<br>       &lt;Button className=&quot;w-full&quot; onClick={saveDb}&gt;<br>        Save<br>       &lt;/Button&gt;<br>      )}<br>     &lt;/div&gt;<br>    &lt;/&gt;<br>   )}<br>  &lt;/div&gt;<br> );<br>}</pre><p>Admittedly, this is a gnarly piece of code with a lot going on, but we’ll go piece by piece to explain what’s happening and how it’s working. The first function we’ll want to look closer at is our importDb() function that runs once the app is started via useEffect.</p><pre>async function importDb() {<br>  try {<br>   setLoading(true);<br>   const dbCid = await publicClient.readContract({<br>    address: import.meta.env.PUBLIC_CONTRACT_ADDRESS,<br>    abi: abi,<br>    functionName: &quot;getState&quot;,<br>   });<br>   console.log(dbCid);<br>   const dbExists = await checkDatabaseExists(&quot;todo-db&quot;);<br>   if (!dbExists) {<br>    const dbFile = await pinata.gateways.get(dbCid as unknown as string);<br>    const file = dbFile.data as Blob;<br>    db = new PGlite({<br>     loadDataDir: file,<br>     dataDir: &quot;idb://todo-db&quot;,<br>    });<br>    console.log(&quot;used remote db&quot;);<br>   } else {<br>    db = new PGlite({<br>     dataDir: &quot;idb://todo-db&quot;,<br>    });<br>    console.log(&quot;used local db&quot;);<br>   }<br>   const ret = await db?.query(`<br>    SELECT * from todo ORDER BY id ASC;<br>   `);<br>   setTodos(ret?.rows as ToDo[]);<br>   toast({<br>    title: &quot;Database Restored&quot;,<br>   });<br>   setLoading(false);<br>  } catch (error) {<br>   setLoading(false);<br>   console.log(error);<br>  }<br> }</pre><p>The first thing we do is get the initial state from our smart contract in the form of a CID or IPFS Hash. Then we run a helper function to check if there is an IndexedDB instance with the name “todo-db”. This prevents downloading the DB every single time, but in the case that there is no IndexedDB then we can download the file using Pinata from IPFS, parse it, then feed it into the PGlite instance. What’s really cool here is that not only will it load the tarball file of our DB into memory, but it will also persist it to idb (IndexedDB) making it local, that way if we ran this check again, we’ll just use that local instance instead. Once the database is loaded, we make a simple query to fetch all of our todos and put them into some React state.</p><p>When it comes to updating our to-do’s we can just follow a simple CRUD pattern.</p><pre>async function addTodo() {<br>  try {<br>   await db?.query(&quot;INSERT INTO todo (task, done) VALUES ($1, false)&quot;, [<br>    taskName,<br>   ]);<br>   const ret = await db?.query(`<br>        SELECT * from todo;<br>      `);<br>   setTodos(ret?.rows as ToDo[]);<br>   setTaskName(&quot;&quot;);<br>   console.log(ret?.rows);<br>  } catch (error) {<br>   console.log(error);<br>  }<br> }<br><br> async function updateTodo(id: number, done: boolean) {<br>  try {<br>   await db?.query(&quot;UPDATE todo SET done = $1 WHERE id = $2&quot;, [done, id]);<br>   const ret = await db?.query(&quot;SELECT * from todo ORDER BY ID ASC;&quot;);<br>   setTodos(ret?.rows as ToDo[]);<br>  } catch (error) {<br>   console.log(error);<br>  }<br> }<br> async function deleteTodo(id: number) {<br>  try {<br>   await db?.query(&quot;DELETE FROM todo WHERE id = $1&quot;, [id]);<br>   const ret = await db?.query(&quot;SELECT * from todo ORDER BY ID ASC;&quot;);<br>   setTodos(ret?.rows as ToDo[]);<br>  } catch (error) {<br>   console.log(error);<br>  }<br> }</pre><p>Each of these are pretty self explanatory, but the piece to keep in mind is that it’s all happening with the IndexedDB; local first!</p><p>For saving the database state and writing it to the smart contract, we have the following saveDb function.</p><pre>async function saveDb() {<br>  try {<br>   setSaving(true);<br>   const dbFile = await db?.dumpDataDir(&quot;auto&quot;);<br>   if (!dbFile) {<br>    throw new Error(&quot;Failed to dump database&quot;);<br>   }<br>   const data = new FormData();<br>   data.append(&quot;file&quot;, dbFile);<br>   const req = await fetch(&quot;/api/upload&quot;, {<br>    method: &quot;POST&quot;,<br>    body: data,<br>   });<br>   const res = await req.json();<br>   console.log(res);<br>   toast({<br>    title: &quot;Database Saved&quot;,<br>   });<br>   setSaving(false);<br>  } catch (error) {<br>   setSaving(false);<br>   console.log(error);<br>  }<br> }</pre><p>This will dump the client side database directory and send it as a file to an API route where it’s uploaded.</p><pre>import type { APIRoute } from &quot;astro&quot;;<br>import { pinata, walletClient, publicClient } from &quot;@/utils/config&quot;;<br>import { account } from &quot;@/utils/account&quot;;<br>import { abi } from &quot;@/utils/contract.json&quot;;<br><br>export const POST: APIRoute = async ({ request }) =&gt; {<br> const data = await request.formData();<br> const file = data.get(&quot;file&quot;) as File;<br> if (!file) {<br>  return new Response(<br>   JSON.stringify({<br>    message: &quot;Missing file&quot;,<br>   }),<br>   { status: 400 },<br>  );<br> }<br> const { IpfsHash } = await pinata.upload.file(file);<br> const { request: contractRequest } = await publicClient.simulateContract({<br>  account,<br>  address: import.meta.env.PUBLIC_CONTRACT_ADDRESS,<br>  abi: abi,<br>  functionName: &quot;update&quot;,<br>  args: [IpfsHash],<br> });<br> const tx = await walletClient.writeContract(contractRequest);<br> const transaction = await publicClient.waitForTransactionReceipt({<br>  hash: tx,<br> });<br> return new Response(<br>  JSON.stringify({<br>   data: transaction.status,<br>  }),<br>  { status: 200 },<br> );<br>};</pre><p>This is almost identical to our initialization script where we taking the incoming file through formData, upload it to Pinata, get the IPFS hash, and write it to the contract. That easy! In the end we have an app that can load a remote database, keep it local, yet still backup to IPFS and smart contracts.</p><p>This whole app can be deployed yourself using <a href="https://github.com/PinataCloud/ipdb-contract">this smart contract repo</a> and the app repo <a href="https://github.com/PinataCloud/ipdb">here</a>, with all the instructions for each in the README files. Would love to see what people could build with them!</p><h3>Wrapping Up</h3><p>Like we mentioned earlier, this concept isn’t bulletproof depending on your use case, but in our opinion, it creates some interesting possibilities. One such possibility, suggested by Sam Willis, one of the builders of PGlite, is to write a virtual file system on top of IPFS, allowing the sync of content by individual files instead of dumping the entire directory. This would allow for more frequent and faster sync methods that could be applied. On the Web3 side of things, there’s lot of flexibility in how you manage the database indexes. In our example, we have events emit when a new state is changed, so you could use that as a version history of save states. Another idea is to use a contract factory so each database can be tied to a wallet by implemented SIWE.</p><p>Overall we’re excited by the advancement of tech like PGlite and Base which really enable ideas like this. Pinata’s mission from the beginning was to make IPFS easy, and we still do that along with <a href="https://pinata.cloud/blog/introducing-the-internets-files-api/">private file uploads</a>, so be sure to <a href="https://bit.ly/3Yf1Dhw">try it out</a> if you haven’t already! Happy Pinning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98897bfa98b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pinata/building-ipdb-a-decentralized-database-using-base-ipfs-and-pglite-98897bfa98b2">Building IPDB: A Decentralized Database using Base, IPFS, and PGlite</a> was originally published in <a href="https://medium.com/pinata">Pinata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Guestbook with PGlite, Clerk, and Pinata]]></title>
            <link>https://medium.com/pinata/building-a-guestbook-with-pglite-clerk-and-pinata-c6ff2ea5f756?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6ff2ea5f756</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 16:17:11 GMT</pubDate>
            <atom:updated>2024-09-24T16:17:11.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V_c-zFFDhK4eug0zsjTEQ.png" /></figure><p>When I was first getting started in web development, I remember seeing someone’s website and was immediately impressed by one thing: a guestbook. You could sign in with Github and leave a message, similar to someone’s Facebook wall back in the day. I thought that was the coolest thing, but had no idea how to build it. Fast forward to this weekend, I was reminded how cool that was and I decided to build it for my own website.</p><p>Normally, I would use Supabase DB + Auth for something like this, for the ease of use, but I wanted to take a slightly different route. I’ve been playing with PGLite quite a bit in the last few weeks and decided it would be fun to see if I can host it as a server. My coworker, Justin, <a href="https://pinata.cloud/blog/how-to-build-a-persistent-crud-app-using-sqlite-and-deno-js/">recently had a post about building a CRUD app with Deno, SQLite and Pinata</a> to handle backups, and it seemed like the perfect setup to pair with PGLite.</p><p>With a weekend to spare, I built this out and you can check it out now with <a href="https://stevedylan.dev/guestbook">this link</a>! In this post, I’ll show you how I built the server, integrated Clerk auth into both the server and the backend, and finally rendered it out into a UI for people to use.</p><h3>Setup</h3><p>When it came to setting up this project, there were several moving pieces that had to work together.</p><h3>Pinata</h3><p>Naturally, since I work for Pinata, I already have an account ready to go for this project, but if you haven’t tried it yet, then you really should! Creating your account, getting your API key, and firing up the SDK takes just minutes to add file uploads to your account. It was actually the easiest piece of this project, so don’t be shy and try it out <a href="https://app.pinata.cloud/register">here</a>.</p><h3>Clerk</h3><p>Since I wasn’t going to use Supabase for this project, I decided to try out <a href="https://clerk.com/">Clerk</a>. I’ve heard nothing but good things, and there’s a reason for that. This platform truly understands how to make auth easy while also giving you loads of control, if you want it. Setting it up for my website and the server was super simple, just followed the quick start guide when I onboarded and it was done. Since I’m using Github as my login method, I also followed <a href="https://clerk.com/docs/authentication/social-connections/github">this guide</a> to set that piece up.</p><h3>Server</h3><p>There are so many options out there for building a server/API, so by all means use what feels best for your needs, but I personally love using <a href="https://hono.dev/">Hono</a> via Bun. Starting up the project was as simple as the command below:</p><pre>bun create hono guestbook-db</pre><p>Once the repo was created and initialized, I installed a few other packages I would need.</p><pre>bun add pinata @clerk/backend @hono/clerk-auth @electric-sql/pglite croner</pre><p>With everything installed, I did some initial setup for the project. In the index.ts file, I imported my dependencies, setup some of the middleware like Clerk and CORS, and just have an entry point setup.</p><pre>import { Hono } from &quot;hono&quot;;<br>import { cors } from &quot;hono/cors&quot;;<br>import { PGlite } from &quot;@electric-sql/pglite&quot;;<br>import { pinata } from &quot;./pinata&quot;;<br>import { Cron } from &quot;croner&quot;;<br>import { clerkMiddleware, getAuth } from &quot;@hono/clerk-auth&quot;;<br><br>const app = new Hono();<br><br>app.use(&quot;/*&quot;, cors());<br>app.use(&quot;*&quot;, clerkMiddleware());<br><br>app.get(&quot;/&quot;, (c) =&gt; {<br> return c.text(&quot;Welcome!&quot;);<br>});<br><br>export default app;</pre><p>The only other file I needed to add was in the same src folder called pinata.ts with a quick export of the Pinata SDK instance.</p><pre>import { PinataSDK } from &quot;pinata&quot;;<br><br>export const pinata = new PinataSDK({<br> pinataJwt: process.env.PINATA_JWT,<br> pinataGateway: process.env.GATEWAY_URL,<br>});</pre><p>Finally, we have a simple .env to handle our secrets and vars.</p><pre>PINATA_JWT= # The primary Pinata API key<br>GATEWAY_URL= # Your Pinata gateway domain e.g. example.mypinata.cloud<br>GROUP_ID= # Group ID where we will store backups<br>CLERK_PUBLISHABLE_KEY= # Clerk public key<br>CLERK_SECRET_KEY= # Clerk private key<br>ADMIN_KEY= # optional key for your own overrides</pre><h3>Backend</h3><p>With the database server setup, it was time to work on adding in the database itself. PGLite is unique in that it runs on WASM, making it lightweight and operable in a browser. For this project, I took advantage of the size by creating a backup and restore feature into the server. Instead of relying on a local disk setup, the server will routinely backup copies of the database to Pinata, and, if at any point it needs to restart, it will reboot from the last backup. Depending on how your database library works, you could also add it writing to disk as well for extra security.</p><p>To setup this workflow, I created the following initDb function and call it using an immediately invoked function expression.</p><pre>async function initDb(): Promise&lt;string&gt; {<br> try {<br>  const files = await pinata.files<br>   .list()<br>   .group(process.env.GROUP_ID!)<br>   .order(&quot;DESC&quot;);<br>  if (files.files) {<br>   const dbFile = await pinata.gateways.get(files.files[0].cid);<br>   const file = dbFile.data as Blob;<br>   db = new PGlite({ loadDataDir: file });<br>   return files.files[0].created_at;<br>  }<br>  db = new PGlite(&quot;./guestbook&quot;);<br>  await db.exec(`<br>        CREATE TABLE IF NOT EXISTS messages (<br>          id SERIAL PRIMARY KEY,<br>          note TEXT,<br>          author TEXT,<br>          user_id TEXT,<br>          pfp_url TEXT,<br>          username TEXT<br>        );<br>     `);<br>  return &quot;New DB Created&quot;;<br> } catch (error) {<br>  console.log(error);<br>  throw error;<br> }<br>}<br><br>(async () =&gt; {<br> try {<br>  const status = await initDb();<br>  console.log(&quot;Database initialized. Snapshot:&quot;, status);<br> } catch (error) {<br>  console.log(&quot;Failed to initialize database:&quot;, error);<br> }<br>})();</pre><p>This initialization function will first check if there is a backup file using Pinata. We keep the files organized by creating a group, and this allows us to filter our files by said group and order them by date. This group was created beforehand, and you could use a script, like the following, to do so.</p><pre>import { PinataSDK } from &quot;pinata&quot;;<br><br>const pinata = new PinataSDK({<br>  pinataJwt: process.env.PINATA_JWT!,<br>  pinataGateway: &quot;example-gateway.mypinata.cloud&quot;,<br>});<br><br>const group = await pinata.groups.create({<br> name: &quot;My New Group&quot;<br>});</pre><p>If there is a database backup in the group, then we download it as a file using the SDK once more with pinata.gateways.get. Then we simply create and load up a new instance of the database using new PGPlite({ loadDataDir: file }). However, if there isn&#39;t a database backup on Pinata, the function will create a new instance of DB locally and create the default table. Then it&#39;s just a matter of calling the function as soon as the server starts!</p><p>With the database setup and ready to go, it was time to start building some endpoints. The first one would be a simple GET /messages to fetch all current rows in the database and return them as JSON. Additionally, we structured the query to reverse the feed results, so the most recent would be at the top.</p><pre>app.get(&quot;/messages&quot;, async (c) =&gt; {<br> if (db) {<br>  const ret = await db.query(`<br>  SELECT * FROM messages ORDER BY id DESC LIMIT 50;<br>  `);<br>  return c.json(ret.rows);<br> }<br> return c.text(&quot;Restore database first&quot;);<br>});</pre><p>Of course, we’ll need an endpoint to actually add messages to the database and we’ll use that with the same route /messages but as a POST method.</p><pre>interface Message {<br> note: string;<br> author: string;<br> user_id: string;<br> username: string;<br>}<br><br>app.post(&quot;/messages&quot;, async (c) =&gt; {<br> const body = (await c.req.json()) as Message;<br><br> const auth = getAuth(c);<br> const clerkClient = c.get(&quot;clerk&quot;);<br><br> if (!auth?.userId) {<br>  return c.json(<br>   {<br>    message: &quot;You are not logged in.&quot;,<br>   },<br>   401,<br>  );<br> }<br><br> if (!body.note || typeof body.note !== &quot;string&quot;) {<br>  return c.json({ error: &quot;Invalid note&quot; }, 400);<br> }<br><br> const user = await clerkClient.users.getUser(auth?.userId);<br><br> try {<br>  if (db &amp;&amp; auth) {<br>   const res = await db.query(<br>    &quot;INSERT INTO messages (note, author, user_id, pfp_url, username) VALUES ($1, $2, $3, $4, $5)&quot;,<br>    [body.note, user.firstName, auth?.userId, user.imageUrl, user.username],<br>   );<br><br>   return c.json(res.rows);<br>  }<br> } catch (error) {<br>  console.error(&quot;Error creating message:&quot;, error);<br>  return c.json({ error: &quot;Failed to create message&quot; }, 500);<br> }<br>});</pre><p>Here is where things start to get good. Instead of having the client send a full JSON payload, we can use Clerk to securely fetch some of that information for us as we use Github OAuth as the only authentication method. In the database, we have the note, author or name of the writer, user_id from Clerk which we&#39;ll get into later, and the username for link to the writer&#39;s Github profile. All we have to do is use the Clerk Hono middleware to get the auth object and verify the user is logged in, otherwise we send a 401. We also make sure that the note attached from the client is a string. Finally, we can get a user object from Clerk using the userId and getting all the information we need! Then we just insert a row into the table and return it back to the client.</p><p>In the event that someone mistyped something and wanted to delete their message, or if someone left something unkind, we will want a method to delete it. This time we’ll use DELETE /messages/:id and get the id of a message using the path param.</p><pre>app.delete(&quot;/messages/:id&quot;, async (c) =&gt; {<br> const id = c.req.param(&quot;id&quot;);<br> const auth = getAuth(c);<br> const admin = c.req.header(&quot;Authorization&quot;);<br><br> if (!auth?.userId &amp;&amp; admin !== process.env.ADMIN_KEY) {<br>  return c.json(<br>   {<br>    message: &quot;You are not logged in.&quot;,<br>   },<br>   401,<br>  );<br> }<br><br> try {<br>  if (db) {<br>   const checkQuery = await db.query&lt;MessageRow&gt;(<br>    &quot;SELECT user_id FROM messages WHERE id = $1&quot;,<br>    [id],<br>   );<br><br>   if (checkQuery.rows.length === 0) {<br>    return c.json({ error: &quot;Message not found&quot; }, 404);<br>   }<br><br>   const messageUserId = checkQuery.rows[0].user_id;<br><br>   if (admin !== process.env.ADMIN_KEY &amp;&amp; auth?.userId !== messageUserId) {<br>    return c.json(<br>     { error: &quot;You are not authorized to delete this message&quot; },<br>     403,<br>    );<br>   }<br><br>   const res = await db.query(&quot;DELETE FROM messages WHERE id = $1&quot;, [id]);<br><br>   if (res.affectedRows === 0) {<br>    return c.json({ error: &quot;Message not found&quot; }, 404);<br>   }<br>   return c.text(&quot;Ok&quot;);<br>  }<br> } catch (error) {<br>  console.error(&quot;Error deleting message:&quot;, error);<br>  return c.json({ error: &quot;Failed to delete message&quot; }, 500);<br> }<br>});</pre><p>With this endpoint, we have to check a few things. First we need to grab the id of the target note. Then we need to do a general auth check to see if the requester is a user or the admin (me). If they pass that, then we do a query of the messages for that note id, and then we do a check if the requester is either the admin or the author of the note. If they pass, then we delete the row from the table and send back an Ok message.</p><p>That really covers the majority of what I wanted in the guestbook but, if we wanted to, we could easily add a PUT message as well to enable editing old messages. There are a few things left to do though, including our /restore and /backup routes.</p><pre>app.post(&quot;/restore&quot;, async (c) =&gt; {<br> const admin = c.req.header(&quot;Authorization&quot;);<br><br> if (admin !== process.env.ADMIN_KEY) {<br>  return c.json(<br>   {<br>    message: &quot;You are not logged in.&quot;,<br>   },<br>   401,<br>  );<br> }<br><br> try {<br>  await initDb();<br>  return c.text(&quot;Ok&quot;);<br> } catch (error) {<br>  console.error(&quot;Error restoring database:&quot;, error);<br>  return c.json({ error: &quot;Failed to restore database.&quot; }, 500);<br> }<br>});<br><br>app.post(&quot;/backup&quot;, async (c) =&gt; {<br> const admin = c.req.header(&quot;Authorization&quot;);<br><br> if (admin !== process.env.ADMIN_KEY) {<br>  return c.json(<br>   {<br>    message: &quot;You are not logged in.&quot;,<br>   },<br>   401,<br>  );<br> }<br><br> try {<br>  if (db) {<br>   const dbFile = (await db.dumpDataDir(&quot;auto&quot;)) as File;<br>   const upload = await pinata.upload<br>    .file(dbFile)<br>    .group(process.env.GROUP_ID ?? &quot;&quot;);<br>   return c.json(upload);<br>  }<br> } catch (error) {<br>  console.error(&quot;Error backing up database:&quot;, error);<br>  return c.json({ error: &quot;Failed to backup database&quot; }, 500);<br> }<br>});</pre><p>These are really simple routes, but play an important role in our database. The /restore route is a manual reset without restarting the server, where it runs our initDb() function from the beginning. /backup will dump our current database state as a compact zip file into our Pinata group using the best upload experience: pinata.upload.file — <em>chef’s kiss</em>. We’ll use the same logic in our cron job to regularly backup the database.</p><pre>const job = Cron(&quot;0 0 * * *&quot;, async () =&gt; {<br> if (db) {<br>  const dbFile = (await db.dumpDataDir(&quot;auto&quot;)) as File;<br>  const upload = await pinata.upload<br>   .file(dbFile)<br>   .group(process.env.GROUP_ID ?? &quot;&quot;);<br>  console.log(upload);<br> }<br>});</pre><p>Just like that, our server is ready!</p><h3>Front End</h3><p>Now, the fun part, pulling everything together in the app. 😎 To start, I needed to install and setup Clerk for Astro using <a href="https://clerk.com/docs/quickstarts/astro">this guide</a>. To stay somewhat in my comfort zone, I used the React plugin for Astro so I could make a component that handles everything, and once again, Clerk <a href="https://clerk.com/docs/references/astro/react">made that easy too</a>.</p><p>I made a new component called GuestbookFeed.tsx and slowly built out the following:</p><pre>import { useStore } from &quot;@nanostores/react&quot;;<br>import { $sessionStore, $userStore } from &quot;@clerk/astro/client&quot;;<br>import { useState, useEffect } from &quot;react&quot;;<br>import {<br> SignedIn,<br> SignedOut,<br> UserButton,<br> SignUpButton,<br>} from &quot;@clerk/astro/react&quot;;<br><br>type Message = {<br> id: number;<br> note: string;<br> author: string;<br> user_id: string;<br> pfp_url: string;<br> username: string;<br>};<br><br>const API_URL = import.meta.PUBLIC_API_ENDPOINT<br><br>export default function GuestbookFeed() {<br> const [messages, setMessages] = useState&lt;Message[]&gt;([]);<br> const [isLoading, setIsLoading] = useState(true);<br> const [isSending, setIsSending] = useState(false);<br> const [inputText, setInputText] = useState(&quot;&quot;);<br> const session = useStore($sessionStore);<br> const user = useStore($userStore);<br><br> async function fetchMessages() {<br>  setIsLoading(true);<br>  try {<br>   const req = await fetch(`${API_URL}/messages`);<br>   const res = await req.json();<br>   console.log(res);<br>   setMessages(res);<br>  } catch (error) {<br>   console.log(error);<br>  } finally {<br>   setIsLoading(false);<br>  }<br> }<br><br> function inputHandeler(e) {<br>  setInputText(e.target.value);<br> }<br><br> async function sendMessage() {<br>  setIsSending(true);<br>  try {<br>   const req = await fetch(`${API_URL}/messages`, {<br>    method: &quot;POST&quot;,<br>    headers: {<br>     Authorization: `Bearer ${await session.getToken()}`,<br>    },<br>    body: JSON.stringify({ note: inputText }),<br>   });<br>   const res = await req.json();<br>   console.log(res);<br>   setInputText(&quot;&quot;);<br>   setIsSending(false);<br>   await fetchMessages();<br>  } catch (error) {<br>   console.log(error);<br>   setIsSending(false);<br>  }<br> }<br><br> async function deleteMessage(id: number) {<br>  try {<br>   const req = await fetch(`${API_URL}/messages/${id}`, {<br>    method: &quot;DELETE&quot;,<br>    headers: {<br>     Authorization: `Bearer ${await session.getToken()}`,<br>    },<br>   });<br>   const res = await req.json();<br>   console.log(res);<br>   await fetchMessages();<br>  } catch (error) {<br>   console.log(error);<br>  }<br> }<br><br> useEffect(() =&gt; {<br>  fetchMessages();<br> }, []);<br><br> return (<br>  &lt;div className=&quot;flex flex-col gap-6&quot;&gt;<br>   &lt;div className=&quot;&quot;&gt;<br>    &lt;SignedOut&gt;<br>     &lt;SignUpButton<br>      signInForceRedirectUrl=&quot;/guestbook&quot;<br>      signInFallbackRedirectUrl=&quot;/guestbook&quot;<br>      forceRedirectUrl=&quot;/guestbook&quot;<br>      mode=&quot;modal&quot;<br>      className=&quot;border-2 border-current rounded-md py-1 px-2 cursor-pointer&quot;<br>     &gt;<br>      Sign in with Github<br>     &lt;/SignUpButton&gt;<br>    &lt;/SignedOut&gt;<br>    &lt;SignedIn&gt;<br>     &lt;div className=&quot;flex items-start gap-4 w-full&quot;&gt;<br>      &lt;UserButton<br>       appearance={{<br>        layout: {<br>         animations: false,<br>        },<br>       }}<br>       afterSignOutUrl=&quot;/guestbook&quot;<br>      /&gt;<br>      &lt;input<br>       className=&quot;p-1 bg-bgColor border-current border-2 rounded-md w-96&quot;<br>       type=&quot;text&quot;<br>       onChange={inputHandeler}<br>       value={inputText}<br>      /&gt;<br>      &lt;button<br>       className=&quot;border-2 border-current rounded-md py-1 px-2 cursor-pointer&quot;<br>       onClick={sendMessage}<br>       type=&quot;button&quot;<br>      &gt;<br>       {isSending ? &quot;Posting...&quot; : &quot;Post&quot;}<br>      &lt;/button&gt;<br>     &lt;/div&gt;<br>    &lt;/SignedIn&gt;<br>   &lt;/div&gt;<br>   {isLoading ? (<br>    &lt;p&gt;Loading...&lt;/p&gt;<br>   ) : (<br>    &lt;div className=&quot;flex flex-col gap-6&quot;&gt;<br>     {messages.map((note: Message) =&gt; (<br>      &lt;div<br>       className=&quot;flex flex-row justify-between items-start&quot;<br>       key={note.id}<br>      &gt;<br>       &lt;div className=&quot;flex flex-row gap-2 items-start&quot;&gt;<br>        &lt;a<br>         className=&quot;flex-shrink-0 h-7 w-7&quot;<br>         href={`https://github.com/${note.username}`}<br>         target=&quot;_blank&quot;<br>         rel=&quot;noreferrer&quot;<br>        &gt;<br>         &lt;img<br>          className=&quot;h-full w-full rounded-full object-cover&quot;<br>          src={note.pfp_url}<br>          alt={note.author}<br>         /&gt;<br>        &lt;/a&gt;<br>        &lt;div className=&quot;flex flex-col justify-between&quot;&gt;<br>         &lt;a<br>          href={`https://github.com/${note.username}`}<br>          className=&quot;font-bold text-gray-400&quot;<br>          target=&quot;_blank&quot;<br>          rel=&quot;noreferrer&quot;<br>         &gt;<br>          {note.author}<br>         &lt;/a&gt;<br>         &lt;p className=&quot;break-words&quot;&gt;{note.note}&lt;/p&gt;<br>        &lt;/div&gt;<br>       &lt;/div&gt;<br>       {user &amp;&amp; user.id === note.user_id &amp;&amp; (<br>        &lt;button<br>         onClick={async () =&gt; deleteMessage(note.id)}<br>         type=&quot;button&quot;<br>        &gt;<br>         x<br>        &lt;/button&gt;<br>       )}<br>      &lt;/div&gt;<br>     ))}<br>    &lt;/div&gt;<br>   )}<br>  &lt;/div&gt;<br> );<br>}</pre><p>It’s a lot of code to look at, but when you break it down it’s pretty easy to understand, so let’s do that now. To start, we have our main imports at the top.</p><pre>import { $sessionStore, $userStore } from &quot;@clerk/astro/client&quot;;<br>import { useState, useEffect } from &quot;react&quot;;<br>import {<br> SignedIn,<br> SignedOut,<br> UserButton,<br> SignUpButton,<br>} from &quot;@clerk/astro/react&quot;;<br><br>type Message = {<br> id: number;<br> note: string;<br> author: string;<br> user_id: string;<br> pfp_url: string;<br> username: string;<br>};<br><br>const API_URL = import.meta.env.PUBLIC_API_URL<br><br>export default function GuestbookFeed() {<br> const [messages, setMessages] = useState&lt;Message[]&gt;([]);<br> const [isLoading, setIsLoading] = useState(true);<br> const [isSending, setIsSending] = useState(false);<br> const [inputText, setInputText] = useState(&quot;&quot;);<br> const session = useStore($sessionStore);<br> const user = useStore($userStore);<br>//...</pre><p>Here we have some simple, yet important, pieces to our component. The first is our stores, like $sessionStore and $userStore. These are provided by the Clerk middleware and will give us access to the logged in user&#39;s session tokens to authorize requests. We also have some neat components from Clerk, which we&#39;ll get into shortly. Finally, we have a slew of state from React to handle inputs and loading states, as well as the useStore for our auth stores.</p><p>Below that, we have just a few primary functions.</p><pre> async function fetchMessages() {<br>  setIsLoading(true);<br>  try {<br>   const req = await fetch(`${API_URL}/messages`);<br>   const res = await req.json();<br>   console.log(res);<br>   setMessages(res);<br>  } catch (error) {<br>   console.log(error);<br>  } finally {<br>   setIsLoading(false);<br>  }<br> }<br><br> function inputHandeler(e) {<br>  setInputText(e.target.value);<br> }<br><br> async function sendMessage() {<br>  setIsSending(true);<br>  try {<br>   const req = await fetch(`${API_URL}/messages`, {<br>    method: &quot;POST&quot;,<br>    headers: {<br>     Authorization: `Bearer ${await session.getToken()}`,<br>    },<br>    body: JSON.stringify({ note: inputText }),<br>   });<br>   const res = await req.json();<br>   console.log(res);<br>   setInputText(&quot;&quot;);<br>   setIsSending(false);<br>   await fetchMessages();<br>  } catch (error) {<br>   console.log(error);<br>   setIsSending(false);<br>  }<br> }<br><br> async function deleteMessage(id: number) {<br>  try {<br>   const req = await fetch(`${API_URL}/messages/${id}`, {<br>    method: &quot;DELETE&quot;,<br>    headers: {<br>     Authorization: `Bearer ${await session.getToken()}`,<br>    },<br>   });<br>   const res = await req.json();<br>   console.log(res);<br>   await fetchMessages();<br>  } catch (error) {<br>   console.log(error);<br>  }<br> }<br><br> useEffect(() =&gt; {<br>  fetchMessages();<br> }, []);</pre><p>At the top, we have our function to fetch messages from our API. We made this a public endpoint, so we don’t have to authorize it at all, and we just store the array of messages from the database into our Message array. Next, we have our inputHandler as well as our sendMessage function, which again just takes the input state and sends it as an API request. What&#39;s special here is the Authorization header where we use the await session.getToken() so that our API can authenticate the request. Simple, clean, and effective. If successful, we&#39;ll clear the input and refetch the messages. We also have a deleteMessage function so the author can delete a note from the site if they want to, and finally we have a simple useEffect to load our messages when the page loads.</p><p>Now all that’s left is rendering our UI:</p><pre> return (<br>  &lt;div className=&quot;flex flex-col gap-6&quot;&gt;<br>   &lt;div className=&quot;&quot;&gt;<br>    &lt;SignedOut&gt;<br>     &lt;SignUpButton<br>      signInForceRedirectUrl=&quot;/guestbook&quot;<br>      signInFallbackRedirectUrl=&quot;/guestbook&quot;<br>      forceRedirectUrl=&quot;/guestbook&quot;<br>      mode=&quot;modal&quot;<br>      className=&quot;border-2 border-current rounded-md py-1 px-2 cursor-pointer&quot;<br>     &gt;<br>      Sign in with Github<br>     &lt;/SignUpButton&gt;<br>    &lt;/SignedOut&gt;<br>    &lt;SignedIn&gt;<br>     &lt;div className=&quot;flex items-start gap-4 w-full&quot;&gt;<br>      &lt;UserButton<br>       appearance={{<br>        layout: {<br>         animations: false,<br>        },<br>       }}<br>       afterSignOutUrl=&quot;/guestbook&quot;<br>      /&gt;<br>      &lt;input<br>       className=&quot;p-1 bg-bgColor border-current border-2 rounded-md w-96&quot;<br>       type=&quot;text&quot;<br>       onChange={inputHandeler}<br>       value={inputText}<br>      /&gt;<br>      &lt;button<br>       className=&quot;border-2 border-current rounded-md py-1 px-2 cursor-pointer&quot;<br>       onClick={sendMessage}<br>       type=&quot;button&quot;<br>      &gt;<br>       {isSending ? &quot;Posting...&quot; : &quot;Post&quot;}<br>      &lt;/button&gt;<br>     &lt;/div&gt;<br>    &lt;/SignedIn&gt;<br>   &lt;/div&gt;<br>   {isLoading ? (<br>    &lt;p&gt;Loading...&lt;/p&gt;<br>   ) : (<br>    &lt;div className=&quot;flex flex-col gap-6&quot;&gt;<br>     {messages.map((note: Message) =&gt; (<br>      &lt;div<br>       className=&quot;flex flex-row justify-between items-start&quot;<br>       key={note.id}<br>      &gt;<br>       &lt;div className=&quot;flex flex-row gap-2 items-start&quot;&gt;<br>        &lt;a<br>         className=&quot;flex-shrink-0 h-7 w-7&quot;<br>         href={`https://github.com/${note.username}`}<br>         target=&quot;_blank&quot;<br>         rel=&quot;noreferrer&quot;<br>        &gt;<br>         &lt;img<br>          className=&quot;h-full w-full rounded-full object-cover&quot;<br>          src={note.pfp_url}<br>          alt={note.author}<br>         /&gt;<br>        &lt;/a&gt;<br>        &lt;div className=&quot;flex flex-col justify-between&quot;&gt;<br>         &lt;a<br>          href={`https://github.com/${note.username}`}<br>          className=&quot;font-bold text-gray-400&quot;<br>          target=&quot;_blank&quot;<br>          rel=&quot;noreferrer&quot;<br>         &gt;<br>          {note.author}<br>         &lt;/a&gt;<br>         &lt;p className=&quot;break-words&quot;&gt;{note.note}&lt;/p&gt;<br>        &lt;/div&gt;<br>       &lt;/div&gt;<br>       {user &amp;&amp; user.id === note.user_id &amp;&amp; (<br>        &lt;button<br>         onClick={async () =&gt; deleteMessage(note.id)}<br>         type=&quot;button&quot;<br>        &gt;<br>         x<br>        &lt;/button&gt;<br>       )}<br>      &lt;/div&gt;<br>     ))}<br>    &lt;/div&gt;<br>   )}<br>  &lt;/div&gt;<br> );</pre><p>Again, a lot of code, but overall not too complicated. At the top, we have our Clerk components that determine what a user sees based on their login state. If they’re not logged in, then we have a &lt;SignUpButton /&gt;. Once they do sign in, we show them a profile button with &lt;UserButton /&gt;, input to put a message in, and a button to <a href="https://youtu.be/RSuLFvalhnQ">send it</a>. Below our Clerk components, we have the actual message feed which renders our messages array, and includes things like their pfp, name, message, and even an &lt;a /&gt; tag to link to their Github profile. Finally, we also have a little button that will appear for that specific user if they want to delete one of their messages, but not anyone else&#39;s.</p><h3>Wrapping Up</h3><p>Overall, this was a really great little project to build and it touches some of the key pieces of the web: uploads/storage, databases, backend APIs, and front end UIs. It gives you a great feel and stretches your understanding of how all of these pieces work together and how the space is moving.</p><p>Using tools like Pinata or Clerk really give you the best of both worlds when building tools, which is a great developer experience and a solid, finished product.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6ff2ea5f756" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pinata/building-a-guestbook-with-pglite-clerk-and-pinata-c6ff2ea5f756">Building a Guestbook with PGlite, Clerk, and Pinata</a> was originally published in <a href="https://medium.com/pinata">Pinata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Upload Files with SvelteKit and Pinata]]></title>
            <link>https://medium.com/pinata/how-to-upload-files-with-sveltekit-and-pinata-bbecf7ca5381?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbecf7ca5381</guid>
            <category><![CDATA[sveltekit]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 15:39:22 GMT</pubDate>
            <atom:updated>2024-09-16T15:39:22.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXDMoktiiTf5kyc3Tbj10Q.png" /></figure><p>You have likely heard of Svelte if you’ve spent time on the web for the last few years, and there’s a good reason for that. Svelte is a JavaScript framework that is compiled, lightweight, and fairly simple to use. It simplifies things that usually require a lot of custom components and code to get working, such as a simple counter.</p><pre>&lt;script&gt;<br> let count = 0;<br><br> function handleClick() {<br>  count += 1;<br> }<br>&lt;/script&gt;<br><br>&lt;button on:click={handleClick}&gt;<br> Clicked {count}<br> {count === 1 ? &#39;time&#39; : &#39;times&#39;}<br>&lt;/button&gt;</pre><p>Svelte takes what you already know from JavaScript and makes it easy to connect it to your markup, creating a very pleasing developer experience. It’s already adopted by some big names like the New York Times, Squarespace, and even IBM. In this tutorial, we’ll show you how to setup an app using SvelteKit and add file uploads using Pinata!</p><h3>Setup</h3><p>To start, you will need a free Pinata account, which you can create in just a minute or two <a href="https://app.pinata.cloud/register">here</a>. Once you’re in, you’ll want to create an API key, which you can do from the <a href="https://app.pinata.cloud/developers/api-keys">API Keys</a> tab and then clicking New Key in the top right. Give it a name, admin permissions, and be sure to save the JWT which we’ll be using in just a bit. Then, you’ll want to grab the Gateway domain, which is included with your account from the <a href="https://app.pinata.cloud/gateway">Gateways</a> tab. It it should look something like <a href="http://aqua-keen-cobra-996.mypinata.cloud/">aqua-keen-cobra-996.mypinata.cloud</a> which you can copy down where you kept the JWT.</p><p>Now, we can start up our app, which you can do as long as you have Node.js installed and a text editor. Open your terminal and run this command:</p><pre>npm create svelte@latest pinata-app</pre><p>When it gives you the options, we’ll want to just select the skeleton project template. Once it has finished installing the dependencies, run the next command to cd into the repo and install pinata.</p><pre>cd pinata-app &amp;&amp; npm i pinata</pre><p>Finally, we will want to make a new file in the root of the project called env.local and put in the following values:</p><pre>PINATA_JWT= # The Pinata API Key JWT we made earlier <br>PUBLIC_GATEWAY_URL= # The Gateway domain just as we copied it from the Pinata app</pre><h3>Adding Uploads</h3><p>With our project all setup, we can write some code to upload some files. If you take a look at the project structure, it should look something like this:</p><pre>.<br>├── README.md<br>├── package-lock.json<br>├── package.json<br>├── src<br>│   ├── app.d.ts<br>│   ├── app.html<br>│   ├── lib<br>│   │   └── index.ts<br>│   └── routes<br>│       └── +page.svelte<br>├── static<br>│   └── favicon.png<br>├── svelte.config.js<br>├── tsconfig.json<br>└── vite.config.ts</pre><p>Our main focus will be in the lib folder, as well as the routes directory, where our pages will be rendered. To start, let’s make a new folder in lib called server , and in that new folder make a file called pinata.ts. This is where our Pinata SDK instance will live, ensuring our API key are not exposed to the client. In pinata.ts let’s put the following code:</p><pre>import { PinataSDK } from &quot;pinata&quot;<br>import { PINATA_JWT } from &quot;$env/static/private&quot;;<br>import { PUBLIC_GATEWAY_URL } from &quot;$env/static/public&quot;;<br><br>export const pinata = new PinataSDK({<br>  pinataJwt: `${PINATA_JWT}`,<br>  pinataGateway: `${PUBLIC_GATEWAY_URL}`<br>})</pre><p>This exports a very simple instance of the SDK using the variables from our .env.local file. Now, we can setup our client side form in the +page.svelte file.</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br>  import { enhance } from &#39;$app/forms&#39;;<br>  import type { ActionData } from &#39;./$types&#39;;<br><br>  export let form: ActionData;<br>  let uploading = false;<br><br>  function handleUpload() {<br>    uploading = true;<br>      return async ({ update }) =&gt; {<br>        await update();<br>        uploading = false;<br>      };<br>  }<br>&lt;/script&gt;<br><br>&lt;main class=&quot;w-full min-h-screen m-auto flex flex-col justify-center items-center&quot;&gt;<br>  &lt;form method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot; use:enhance={handleUpload}&gt;<br>    &lt;input type=&quot;file&quot; id=&quot;file&quot; name=&quot;fileToUpload&quot; accept=&quot;.jpg, .jpeg, .png, .webp&quot; /&gt;<br>    &lt;button disabled={uploading} type=&quot;submit&quot;&gt;<br>      {uploading ? &#39;Uploading...&#39; : &#39;Upload&#39;}<br>    &lt;/button&gt;<br>  &lt;/form&gt;<br>&lt;/main&gt;ty</pre><p>In here, we have a pretty simple form setup using an input and a button to select a file then submit it. We also have a handleUpload function which will be used by the form, but at the moment it doesn’t do anything. In order to make it work, we need to make a server action by creating a file titled +page.server.ts in the same directory. Let’s do that now and add this code:</p><pre>import { fail, json, type Actions } from &quot;@sveltejs/kit&quot;;<br>import { pinata } from &quot;$lib/server/pinata&quot;;<br><br>export const actions: Actions = {<br>  default: async ({ request }) =&gt; {<br>    try {<br>      const formData = await request.formData();<br>      const uploadedFile = (formData?.get(&#39;fileToUpload&#39;) as File);<br><br>      if (!uploadedFile.name || uploadedFile.size === 0) {<br>        return fail(400, {<br>          error: true,<br>          message: &quot;You must provide a file to upload&quot;<br>        })<br>      }<br><br>      const upload = await pinata.upload.file(uploadedFile);<br>      const url = await pinata.gateways.createSignedURL({<br>        cid: upload.cid,<br>        expires: 360<br>      });<br>      return { url, filename: uploadedFile.name, status: 200 };<br>    } catch (error) {<br>      console.log(error);<br>      return json(<br>        { error: &quot;Internal Server Error&quot; },<br>        { status: 500 }<br>      );<br>    }<br>  }<br>}</pre><p>In this handy little server action, our form will by default send the submission here. Then, we can parse the attached form data, make sure there is a file, and then simply upload it with the Pinata SDK! We’ll go one step further by creating a temporary URL we can send back to the client and view the content. The SDK also makes this a breeze, so all we have to do is return the data back to the client. The only thing we’re missing is that, back in the client, we want to render the returned URL, which we can do by adding an if statement to the +page.svelte file.</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br>  import { enhance } from &#39;$app/forms&#39;;<br>  import type { ActionData } from &#39;./$types&#39;;<br><br>  export let form: ActionData;<br>  let uploading = false;<br><br>  function handleUpload() {<br>    uploading = true;<br>      return async ({ update }) =&gt; {<br>        await update();<br>        uploading = false;<br>      };<br>  }<br>&lt;/script&gt;<br><br>&lt;main&gt;<br>  &lt;form method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot; use:enhance={handleUpload}&gt;<br>    &lt;input type=&quot;file&quot; id=&quot;file&quot; name=&quot;fileToUpload&quot; accept=&quot;.jpg, .jpeg, .png, .webp&quot; /&gt;<br>    &lt;button disabled={uploading} type=&quot;submit&quot;&gt;<br>      {uploading ? &#39;Uploading...&#39; : &#39;Upload&#39;}<br>    &lt;/button&gt;<br>  &lt;/form&gt;<br>  {#if form &amp;&amp; form.status === 200}<br>    &lt;img src={form.url} alt={form.filename} /&gt;<br>  {/if}<br>&lt;/main&gt;</pre><p>Thats all we need! If you spin up the dev server with npm run dev you should get a simple form that uploads a file and displays it on the page!</p><h3>Wrapping Up</h3><p>This is only touching the surface of what you could build with SvelteKit and Pinata. Need inspiration? Check out some of our <a href="https://pinata.cloud/blog">other blog posts</a> and read up on our <a href="https://docs.pinata.cloud/">docs</a> to launch your next app!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbecf7ca5381" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pinata/how-to-upload-files-with-sveltekit-and-pinata-bbecf7ca5381">How to Upload Files with SvelteKit and Pinata</a> was originally published in <a href="https://medium.com/pinata">Pinata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Upload Files with Next.js and Pinata]]></title>
            <link>https://medium.com/pinata/how-to-upload-files-with-next-js-and-pinata-c9d430e202eb?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9d430e202eb</guid>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[upload]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 18:02:21 GMT</pubDate>
            <atom:updated>2024-09-09T18:02:21.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2eLMkmSangXLq1AFxHJxA.png" /></figure><p><a href="https://nextjs.org/">Next.js</a> is, without a doubt, one of the most popular web frameworks used to build apps, with over 125K Github stars and used in over 3 millions projects worldwide. There’s good reasons for this too, as Next makes it pretty easy to launch a simple app and iterate into more advance architecture. If you’re trying to turn an idea into a SaaS you need to be quick and nimble, building out an MVP to see if there’s enough users and interest to justify it long term. Chances are your idea will also need file uploads, and you need something equally easy and fast to implement. Pinata has you covered with an intuitive <a href="https://pinata.cloud/blog/introducing-the-internets-files-api/">Files API</a> and first class SDK. Don’t take my word for it, let’s see how easy it truly is!</p><h3>Setup</h3><p>First thing we’ll need to do is sign up for a <a href="https://app.pinata.cloud/register">free Pinata account</a>, giving you plenty of room to test out file uploads. After you’ve made it into the dashboard, you’ll want to make an API key by clicking on the API Keys tab on the sidebar, then clicking New Key in the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbePQJ4uGaBCYELcoRUTSA.gif" /></figure><p>Give it a name, and make sure it has Admin level access. Once the key is created you’ll see the pinata_api_key, pinata_api_secret, and JWT. These are only shown once so be sure to copy them somewhere safe; we’ll primarily be using the longer JWT.</p><p>After grabbing your API key, you’ll want to grab your Gateway domain by clicking on the Gateways tab on the side. You’ll see the domain in the format of <a href="http://random-example.mypinata.cloud/">random-example.mypinata.cloud</a> and you’ll want to copy that down too in the exact same format. This is what we will use to retrieve files.</p><p>With those set-up, we can go ahead and start up our Next.js app! Open your terminal and run:</p><pre>npx create-next-app@latest pinata-next</pre><p>For this tutorial we’ll select all the default options, which is Typescript and Tailwindcss, but you can still follow along without those. Once it has created the repo, we will want to cd into it and install the <a href="https://docs.pinata.cloud/sdk">Pinata SDK</a>.</p><pre>cd pinata-next &amp;&amp; npm i pinata </pre><p>Once we are inside the project and have installed our dependencies, we will want to make a new file in the root of project called .env.local where we’ll fill in our JWT and the Gateway domain.</p><pre>PINATA_JWT=<br>NEXT_PUBLIC_GATEWAY_URL=</pre><p>Now, we can start writing some code!</p><h3>Uploading with Pinata</h3><p>When it comes to using Pinata to upload files in Next, there are two primary methods:</p><ol><li>Server Side — File is sent over an API route and uploaded server side using the primary API key</li><li>Client Side — File is uploaded directly on the client side using a temporary API key</li></ol><p>Both of these methods work great and will ultimately depend on your app needs. The server side method is generally less code, however the size of the file that can be passed through and API route in Next is limited. The client side method uses a little more code, but the file size is only limited to what Pinata can handle (which is a lot). For this tutorial we’ll just show the server side method, however, you can find the <a href="https://docs.pinata.cloud/frameworks/next-js#client-side-setup">client side method in our docs</a>.</p><p>To start, let’s make a new folder in the root of the project called utils and put a new file inside called config.ts , then paste in the following code:</p><pre>import { PinataSDK } from &quot;pinata&quot;<br><br>export const pinata = new PinataSDK({<br>  pinataJwt: `${process.env.PINATA_JWT}`,<br>  pinataGateway: `${process.env.NEXT_PUBLIC_GATEWAY_URL}`<br>})</pre><p>All this does is create and export a new instance of the Pinata SDK that we can use throughout the app. Now, back in our main page.tsx file, let’s clear out all the boiler plate and put in this code:</p><pre>&quot;use client&quot;;<br><br>import { useState, useRef } from &quot;react&quot;;<br><br>export default function Home() {<br>  const [file, setFile] = useState(&quot;&quot;);<br>  const [url, setUrl] = useState(&quot;&quot;);<br>  const [uploading, setUploading] = useState(false);<br>  const inputFile = useRef(null);<br><br>  const uploadFile = async () =&gt; {<br>    try {<br>      setUploading(true);<br>      const data = new FormData();<br>      data.set(&quot;file&quot;, file);<br>      const uploadRequest = await fetch(&quot;/api/files&quot;, {<br>        method: &quot;POST&quot;,<br>        body: data,<br>      });<br>      const signedUrl = await uploadRequest.json();<br>      setUrl(signedUrl);<br>      setUploading(false);<br>    } catch (e) {<br>      console.log(e);<br>      setUploading(false);<br>      alert(&quot;Trouble uploading file&quot;);<br>    }<br>  };<br><br>  const handleChange = (e: any) =&gt; {<br>    setFile(e.target.files[0]);<br>  };<br><br>  return (<br>    &lt;main className=&quot;max-w-[500px] min-h-screen m-auto flex flex-col gap-4 justify-center items-center&quot;&gt;<br>      &lt;input type=&quot;file&quot; id=&quot;file&quot; ref={inputFile} onChange={handleChange} /&gt;<br>      &lt;button className=&quot;bg-white text-black p-2 rounded-md&quot; disabled={uploading} onClick={uploadFile}&gt;<br>        {uploading ? &quot;Uploading...&quot; : &quot;Upload&quot;}<br>      &lt;/button&gt;<br>      {url &amp;&amp; &lt;a href={url} className=&quot;underline&quot; target=&quot;_blank&quot;&gt;{url}&lt;/a&gt;}<br>    &lt;/main&gt;<br>  );<br>}</pre><p>This is a really simple page where we have a function that uploads our file, taking a user input, and then sending it to /api/files using FormData. We can also see that it takes the response of the request and turns it into a URL we can use to view the file. Since we don’t have that API route, let’s make it now by creating an api folder inside of the app folder. Then, make another folder inside of api called files. Finally, make a route.ts file inside of the files directory. Overall, our path should look like app/api/files/route.ts, and we will paste in the code below.</p><pre>import { NextResponse, NextRequest } from &quot;next/server&quot;;<br>import { pinata } from &quot;@/utils/config&quot;<br><br>export const config = {<br>  api: {<br>    bodyParser: false,<br>  },<br>};<br><br>export async function POST(request: NextRequest) {<br>  try {<br>    const data = await request.formData();<br>    const file: File | null = data.get(&quot;file&quot;) as unknown as File;<br>    const { cid } = await pinata.upload.file(file)<br>    const url = await pinata.gateways.createSignedURL({<br>   cid: cid,<br>   expires: 3600,<br>  });<br>    return NextResponse.json(url, { status: 200 });<br>  } catch (e) {<br>    console.log(e);<br>    return NextResponse.json(<br>      { error: &quot;Internal Server Error&quot; },<br>      { status: 500 }<br>    );<br>  }<br>}</pre><p>The Pinata SDK really makes this simple for us; we simply get the file from the request made by the client, then upload it with await pinata.upload.file(file). This returns a cid or “Content Identifier” which works as a unique hash for our file, which we can use in the next method to make a temporary viewing link for our file. We need this since all files uploaded to Pinata are, by default, private, but could be made public using <a href="https://docs.pinata.cloud/files/file-groups">Groups</a>. In this case, we just returned our signed URL to the client so someone can view or download the file. With everything saved, you can run npm run dev, upload a file, and get a URL back!</p><p>That’s it! You just added file uploads to your Next.js app with just a few lines of code, and that’s how it should be.</p><h3>Conclusion</h3><p>Nothing is more valuable than your time, so why waste it with something like S3 that has endless configuration? Get your ideas out there faster and with less pain, and way less code. <a href="https://docs.pinata.cloud/">Check out our docs</a> and see how Pinata can make uploads seamless for your app!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9d430e202eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pinata/how-to-upload-files-with-next-js-and-pinata-c9d430e202eb">How to Upload Files with Next.js and Pinata</a> was originally published in <a href="https://medium.com/pinata">Pinata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build a Simple Podcast Hosting App]]></title>
            <link>https://medium.com/pinata/how-to-build-a-simple-podcast-hosting-app-280979ef5368?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/280979ef5368</guid>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[podcast]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 20:47:02 GMT</pubDate>
            <atom:updated>2024-09-05T21:26:14.393Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQn7so8n8EUxtrH4PRdPqg.png" /></figure><p>Ever find yourself in “Founder Mode” but lack the platform to tell people about it? Look no further! Behold: <a href="http://foundercloud.live/">FounderCloud.live</a>, a podcast platform for founders that need to yap. Whats under the hood? <a href="https://pinata.cloud/blog/introducing-the-internets-files-api/">The Pinata Fils API,</a> enabling seamless uploads into your app experience. In this post we’ll show you how to use it to build a podcast hosting app that allows users to create podcasts and upload episodes to it. Not only that, but we’ll be pairing Pinata with Next, Supabase, and shadcn/ui for a really clean and polished app. Let’s get started!</p><h3>Setup</h3><p>There’s a few moving pieces here so let’s go over all the things you’ll need before we start building the app itself.</p><h3>Pinata</h3><p>First thing you’ll want to do is <a href="https://auth.pinata.cloud/realms/pinata/protocol/openid-connect/registrations?client_id=pinata-app&amp;response_type=code&amp;scope=openid%20email%20profile&amp;redirect_uri=https%3A%2F%2Fapp.pinata.cloud">create a free Pinata account</a>. Once inside the Pinata App select “API Keys” from the sidebar, then click “New Key” in the top right. We would recommend starting with Admin privileges and unlimited uses to start. You will receive a pinata_api_key, pinata_api_secret, and a JWT. The JWT is the most common authentication method and what we’ll be using for this tutorial.</p><p>Next you will want to grab your Gateway domain by clicking the Gateways tab in the sidebar. You should see it listed in the format fun-llama-300.mypinata.cloud and you will want to copy it exactly like that. Save all those details and we’ll use them again soon.</p><h3>Supabase</h3><p>To handle the records of our podcasts and episodes we’re going to use <a href="https://supabase.com/">Supabase</a> to spin up a quick database. To do that create a free account and then make a new project. With that project you should get a Project URL and an API Key that you will want to save somewhere safe.</p><p>Now to create our tables, you can simple copy the code below and past it into the SQL Editor located in the top left.</p><pre>create table<br>  public.podcasts (<br>    id bigint generated by default as identity not null,<br>    created_at timestamp with time zone not null default now(),<br>    name text null,<br>    group_id text null,<br>    description text null,<br>    image_url text null<br>  ) tablespace pg_default;<br><br>create table<br>  public.episodes (<br>    id bigint generated by default as identity not null,<br>    created_at timestamp with time zone not null default now(),<br>    podcast bigint null references public.podcasts (id),<br>    audio_url text null,<br>    description text null,<br>    name text null<br>  ) tablespace pg_default;</pre><p>This is a pretty simple database setup where we have a primary podcasts table that has columns like name, description, image_url for the cover, and group_id for our uploads piece. The secondary table is episodes and its very similar, only this time uses an audio_url for the content and has a foreign key to link the episode to a specific podcast.</p><h3>Next App</h3><p>With all of that taken care of we can start moving it into our app. To do this you’ll need a little experience with <a href="https://nextjs.org/">Next.js</a> or React frameworks in general, Node installed on your computer, and a good text editor. When you’re ready run the following command in your terminal and select all the defaults:</p><pre>npx create-next-app@latest founder-cloud</pre><p>Once its been initalized you will want to run the next command to cd into the repo and install some dependencies.</p><pre>cd founder-cloud &amp;&amp; npm i pinata uuid @supabase/supabase-js</pre><p>Now like we said earlier we’re going to use <a href="https://ui.shadcn.com/">shadcn/ui</a> for our components; they look great and save us a bunch of time from doing our own styles. Installation is simple:</p><pre>npx shadcn@latest init</pre><p>Once that has finished running we will run the next command to add our components.</p><pre>npx shadcn@latest add button card dialog form input</pre><p>This will put all of our UI components into a folder under components/ui. Since they’re only installed incrementally you can edit the components in that folder to meet whatever style you want down the road!</p><p>It’s time to get our API keys and URLs setup, and we’ll do that by creating a new file called .env.local in the root of our project with the following variables:</p><pre>PINATA_JWT= # the Pinata JWT API key from earlier<br>NEXT_PUBLIC_GATEWAY_URL= # the Pinata Gateway URL from your acccount, in the format &lt;my-domain&gt;.mypinata.cloud<br>SUPABASE_URL= # your Supabase Project URL<br>SUPABASE_KEY= # your Supabase API Key</pre><p>With those values in place we can add some little utility files to create instances we can use throughout our app. To start make a new file under the lib folder called pinata.ts and put in the following code:</p><pre>import { PinataSDK } from &quot;pinata&quot;;<br><br>export const pinata = new PinataSDK({<br> pinataJwt: process.env.PINATA_JWT!,<br> pinataGateway: process.env.NEXT_PUBLIC_GATEWAY_URL,<br>});</pre><p>This tiny little constant will be our ticket to easy uploads as you’ll experience soon! If you ever need the docs to see what else it can do be sure to check them out <a href="https://docs.pinata.cloud/sdk">here</a>.</p><p>Another piece we’ll need is access to our database. In the same lib folder make a new file called db.ts with this piece of code.</p><pre>import { createClient } from &quot;@supabase/supabase-js&quot;;<br><br>// Create a single supabase client for interacting with your database<br>export const supabase = createClient(<br> process.env.SUPABASE_URL!,<br> process.env.SUPABASE_KEY!,<br>);</pre><p>Normally these keys could be public, but since we are not implementing auth or RLS (row level security) in this tutorial we’ll just keep all our database interactions server side and treat them as secret.</p><p>With all of that setup we can finally start building our podcast app!</p><h3>Building the Podcasts</h3><p>In order for our app to work there are a few things it will need to do:</p><ul><li>Create podcasts</li><li>List podcasts</li><li>List episodes within a podcast</li><li>Create episodes within a podcast</li></ul><p>Since our app needs are nested we’ll make the structure fairly nested as well. When building with Next App Router it helps to visualize those needs and structures and identify them as server or client components. For our app it might look something like this:</p><ul><li>Home page (server)</li><li>Lists podcasts</li><li>Button to create a podcast (client)</li><li>Podcast page (server)</li><li>Show podcast info</li><li>List episodes (server)</li><li>Button to add episode (client)</li></ul><p>With all of that in mind lets build our server rendered home page under app/page.tsx. Remove all the boilerplate and put this code in.</p><pre>import { CreatePodcastForm } from &quot;@/components/create-podcast-form&quot;;<br>import { supabase } from &quot;@/lib/db&quot;;<br>import { Card } from &quot;@/components/ui/card&quot;;<br>import Link from &quot;next/link&quot;;<br><br>export const revalidate = 60;<br><br>export type Podcast = {<br> id: number;<br> created_at: string;<br> name: string;<br> group_id: string;<br> description: string;<br> image_url: string;<br>};<br><br>async function fetchData(): Promise&lt;Podcast[]&gt; {<br> try {<br>  const supabase = createClient();<br>  const { data, error } = await supabase.from(&quot;podcasts&quot;).select(&quot;*&quot;);<br>  return data as Podcast[];<br> } catch (error) {<br>  console.log(error);<br>  return [];<br> }<br>}<br><br>export default async function Home() {<br> const data = await fetchData();<br> console.log(data);<br><br> return (<br>  &lt;main className=&quot;flex min-h-screen flex-col items-center justify-start p-24 gap-12&quot;&gt;<br>   &lt;div className=&quot;flex flex-col gap-2 text-center&quot;&gt;<br>    &lt;h1 className=&quot;scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl&quot;&gt;<br>     FounderCloud<br>    &lt;/h1&gt;<br>    &lt;h4 className=&quot;scroll-m-20 text-xl font-semibold tracking-tight&quot;&gt;<br>     Yap like you have nothing else to do<br>    &lt;/h4&gt;<br>   &lt;/div&gt;<br>   {data.map((item: Podcast) =&gt; (<br>    &lt;Card className=&quot;overflow-hidden max-w-[400px]&quot; key={item.id}&gt;<br>     &lt;Link href={`/podcast/${item.id}`}&gt;<br>      &lt;img<br>       src={item.image_url}<br>       className=&quot;max-h-[400px] max-w-[400px] object-cover&quot;<br>       alt={item.id.toString()}<br>      /&gt;<br>      &lt;div className=&quot;p-2 flex flex-col gap-2&quot;&gt;<br>       &lt;h3 className=&quot;croll-m-20 text-2xl font-semibold tracking-tight&quot;&gt;<br>        {item.name}<br>       &lt;/h3&gt;<br>       &lt;p&gt;{item.description}&lt;/p&gt;<br>      &lt;/div&gt;<br>     &lt;/Link&gt;<br>    &lt;/Card&gt;<br>   ))}<br>  &lt;/main&gt;<br> );<br>}</pre><p>Let’s go over what’s happening in this code. First we import all of our components and utilities, then we declare some types as well as revalidate export to make sure we see new podcasts as they’re created. Then we declare a fetchData function which fetches all the podcasts from our database table podcasts. The beauty here is since all components and pages are by default SSR we don’t have to use anything like useEffect or useState to fetch everything; It just loads all of it when the page loads. To take advantage of that we just call the fetchData function inside our Home page, then map over it and make little card components.</p><p>When you do this you’ll notice there’s no podcasts; duh! We need to make some! To give users the ability to create a podcast we’ll need two pieces. First let’s make a new API route by creating a folder called api , then podcast, then a route.ts file inside of that. Over all the path should be app/api/podcast/route.ts. Inside that file we’ll put the following code.</p><pre>import type { NextRequest } from &quot;next/server&quot;;<br>import { NextResponse } from &quot;next/server&quot;;<br>import { pinata } from &quot;@/lib/pinata&quot;;<br>import { supabase } from &quot;@/lib/db&quot;;<br><br>export async function POST(request: NextRequest) {<br> try {<br>  const formData = await request.formData();<br>  const name = formData.get(&quot;name&quot;);<br>  const description = formData.get(&quot;description&quot;);<br>  const file: File | null = formData.get(&quot;image&quot;) as unknown as File;<br>  const group = await pinata.groups.create({<br>   name: name as string,<br>   isPublic: true,<br>  });<br>  const { cid } = await pinata.upload.file(file).group(group.id);<br>  const imageUrl = `https://${process.env.NEXT_PUBLIC_GATEWAY_URL}/files/${cid}`;<br>  const { data, error } = await supabase<br>   .from(&quot;podcasts&quot;)<br>   .insert({<br>    name: name,<br>    group_id: group.id,<br>    description: description,<br>    image_url: imageUrl,<br>   })<br>   .select();<br>  console.log(data);<br>  if (error) {<br>   console.log(error);<br>   return NextResponse.json(<br>    { error: &quot;Internal Server Error&quot; },<br>    { status: 500 },<br>   );<br>  }<br><br>  return NextResponse.json(data, { status: 200 });<br> } catch (e) {<br>  console.log(e);<br>  return NextResponse.json(<br>   { error: &quot;Internal Server Error&quot; },<br>   { status: 500 },<br>  );<br> }<br>}</pre><p>This API route will essentially create a podcast in our database. In order to create a podcast we need a title, description, and cover image. Let’s hone in on the cover image a bit: all files on the new Files API by Pinata will be private by default. Since this is content we don’t mind being public, we need to first created a group and make it public. The SDK makes this a breeze with just a few lines of code, where we make a group using the name of the podcast and then marking isPublic as true. With the group created we can then upload our file into that group in just one line of code! This will return a cid which acts as a unique identifier and hash of our file. We’ll use it to form an image URL that we store in the database. Then its just a matter of inserting all the data as a row into our podcasts table and sending back the response; nice!</p><p>All of this is great, but in order to get the user input and make an API call, we need to make one more component. Make a new file called create-podcast-form.tsx in the components folder and put in the following code:</p><pre>&quot;use client&quot;;<br><br>import { zodResolver } from &quot;@hookform/resolvers/zod&quot;;<br>import { useForm } from &quot;react-hook-form&quot;;<br>import { useState } from &quot;react&quot;;<br>import { z } from &quot;zod&quot;;<br>import { Button } from &quot;@/components/ui/button&quot;;<br>import {<br> Form,<br> FormControl,<br> FormDescription,<br> FormField,<br> FormItem,<br> FormLabel,<br> FormMessage,<br>} from &quot;@/components/ui/form&quot;;<br>import { Input } from &quot;@/components/ui/input&quot;;<br>import {<br> Dialog,<br> DialogContent,<br> DialogTrigger,<br> DialogTitle,<br>} from &quot;@/components/ui/dialog&quot;;<br>import { ReloadIcon } from &quot;@radix-ui/react-icons&quot;;<br><br>const formSchema = z.object({<br> name: z.string().min(2),<br> description: z.string().min(2),<br> file: z.any(),<br>});<br><br>export function CreatePodcastForm() {<br> const [isLoading, setIsLoading] = useState(false);<br><br> const form = useForm&lt;z.infer&lt;typeof formSchema&gt;&gt;({<br>  resolver: zodResolver(formSchema),<br>  defaultValues: {<br>   name: &quot;&quot;,<br>  },<br> });<br><br> const fileRef = form.register(&quot;file&quot;);<br><br> async function onSubmit(values: z.infer&lt;typeof formSchema&gt;) {<br>  setIsLoading(true);<br>  const file: File | null = values.file ? values.file[0] : null;<br>  <br>  if (file) {<br>   const data = new FormData();<br>   data.append(&quot;name&quot;, values.name);<br>   data.append(&quot;description&quot;, values.description);<br>   data.append(&quot;image&quot;, file);<br>   const createPodcastRequest = await fetch(&quot;/api/podcast&quot;, {<br>    method: &quot;POST&quot;,<br>    body: data,<br>   });<br>   const createPodcast = await createPodcastRequest.json();<br>   console.log(createPodcast);<br>   setIsLoading(false);<br>  } else {<br>   console.log(&quot;no file selected&quot;);<br>   setIsLoading(false);<br>  }<br> }<br><br> function ButtonLoading() {<br>  return (<br>   &lt;Button disabled&gt;<br>    &lt;ReloadIcon className=&quot;mr-2 h-4 w-4 animate-spin&quot; /&gt;<br>    Please wait<br>   &lt;/Button&gt;<br>  );<br> }<br> return (<br>  &lt;Dialog&gt;<br>   &lt;DialogTrigger&gt;<br>    &lt;Button&gt;Create Podcast&lt;/Button&gt;<br>   &lt;/DialogTrigger&gt;<br><br>   &lt;DialogContent&gt;<br>    &lt;DialogTitle&gt;Create a Podcast&lt;/DialogTitle&gt;<br>    &lt;Form {...form}&gt;<br>     &lt;form onSubmit={form.handleSubmit(onSubmit)} className=&quot;space-y-8&quot;&gt;<br>      &lt;FormField<br>       control={form.control}<br>       name=&quot;name&quot;<br>       render={({ field }) =&gt; (<br>        &lt;FormItem&gt;<br>         &lt;FormLabel&gt;Name&lt;/FormLabel&gt;<br>         &lt;FormControl&gt;<br>          &lt;Input placeholder=&quot;Founder Mode&quot; {...field} /&gt;<br>         &lt;/FormControl&gt;<br>         &lt;FormDescription&gt;<br>          What&#39;s the name of your Podcast?<br>         &lt;/FormDescription&gt;<br>         &lt;FormMessage /&gt;<br>        &lt;/FormItem&gt;<br>       )}<br>      /&gt;<br>      &lt;FormField<br>       control={form.control}<br>       name=&quot;description&quot;<br>       render={({ field }) =&gt; (<br>        &lt;FormItem&gt;<br>         &lt;FormLabel&gt;Description&lt;/FormLabel&gt;<br>         &lt;FormControl&gt;<br>          &lt;Input placeholder=&quot;Just go founder mode&quot; {...field} /&gt;<br>         &lt;/FormControl&gt;<br>         &lt;FormDescription&gt;What is your podcast about?&lt;/FormDescription&gt;<br>         &lt;FormMessage /&gt;<br>        &lt;/FormItem&gt;<br>       )}<br>      /&gt;<br>      &lt;FormField<br>       control={form.control}<br>       name=&quot;file&quot;<br>       render={({ field }) =&gt; (<br>        &lt;FormItem&gt;<br>         &lt;FormLabel&gt;Cover Image&lt;/FormLabel&gt;<br>         &lt;FormControl&gt;<br>          &lt;Input type=&quot;file&quot; {...fileRef} /&gt;<br>         &lt;/FormControl&gt;<br>         &lt;FormDescription&gt;<br>          Select a cover image for your podcast<br>         &lt;/FormDescription&gt;<br>         &lt;FormMessage /&gt;<br>        &lt;/FormItem&gt;<br>       )}<br>      /&gt;<br>      {isLoading ? (<br>       ButtonLoading()<br>      ) : (<br>       &lt;Button type=&quot;submit&quot;&gt;Submit&lt;/Button&gt;<br>      )}<br>     &lt;/form&gt;<br>    &lt;/Form&gt;<br>   &lt;/DialogContent&gt;<br>  &lt;/Dialog&gt;<br> );<br>}</pre><p>There’s a lot of code here, but the actual logic is pretty simple. First we make this a client side component with &quot;use client&quot; at the top of the file so we can have things like buttons and inputs. We import a bunch of UI components to build a form for people to fill out as well as a dialog. This works like a modal, so when the user clicks the Create Podcast button inside the &lt;DialogTrigger&gt; it will open the &lt;DialogContent&gt; with our form to fill out. Really smooth!</p><p>With that form we have to put together a schema which can help us validate the intake of our form, then we have the almighty onSubmit function. This takes all of our form inputs and attached them to an API request we make to the endpoint we just made: /api/podcast.</p><p>Let’s go back into our app/page.tsx file and add this component in right below the podcast list:</p><pre>import { CreatePodcastForm } from &quot;@/components/create-podcast-form&quot;;<br>// rest of imports<br><br>// rest of the code<br>export default async function Home() {<br> const data = await fetchData();<br> console.log(data);<br><br> return (<br>  &lt;main className=&quot;flex min-h-screen flex-col items-center justify-start p-24 gap-12&quot;&gt;<br>   &lt;div className=&quot;flex flex-col gap-2 text-center&quot;&gt;<br>    &lt;h1 className=&quot;scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl&quot;&gt;<br>     FounderCloud<br>    &lt;/h1&gt;<br>    &lt;h4 className=&quot;scroll-m-20 text-xl font-semibold tracking-tight&quot;&gt;<br>     Yap like you have nothing else to do<br>    &lt;/h4&gt;<br>   &lt;/div&gt;<br>   {data.map((item: Podcast) =&gt; (<br>    &lt;Card className=&quot;overflow-hidden max-w-[400px]&quot; key={item.id}&gt;<br>     &lt;Link href={`/podcast/${item.id}`}&gt;<br>      &lt;img<br>       src={item.image_url}<br>       className=&quot;max-h-[400px] max-w-[400px] object-cover&quot;<br>       alt={item.id.toString()}<br>      /&gt;<br>      &lt;div className=&quot;p-2 flex flex-col gap-2&quot;&gt;<br>       &lt;h3 className=&quot;croll-m-20 text-2xl font-semibold tracking-tight&quot;&gt;<br>        {item.name}<br>       &lt;/h3&gt;<br>       &lt;p&gt;{item.description}&lt;/p&gt;<br>      &lt;/div&gt;<br>     &lt;/Link&gt;<br>    &lt;/Card&gt;<br>   ))}<br>   &lt;CreatePodcastForm /&gt;<br>  &lt;/main&gt;<br> );<br>}</pre><p>Now you can give it a shot; try making a podcast! Keep in mind that the name of the podcast has to be unique, as the Groups feature of the Files API requires a unique name for your account.</p><p>We have our podcast, but we need a page for each podcast to list and add episodes to it. To do that we’ll use a dynamic route in Next. Start by making a folder inside the app folder called podcast and in there we’ll make one more folder called [id] . Finally inside of that folder make a page.tsx file, so our full path looks like app/podcast/[id]/page.tsx. With this structure we can pass an argument in the path like <a href="http://localhost:3000/podcast/1">http://localhost:3000/podcast/1</a> to pull information for podcast id 1. Inside our page.tsx file let’s put in the following code:</p><pre>import { EpisodeList } from &quot;@/components/episode-list&quot;;<br>import { supabase } from &quot;@/lib/db&quot;;<br><br>export type Podcast = {<br> id: number;<br> created_at: string;<br> name: string;<br> group_id: string;<br> description: string;<br> image_url: string;<br>};<br><br>async function fetchData(id: string): Promise&lt;Podcast[]&gt; {<br> try {<br>  const { data, error } = await supabase<br>   .from(&quot;podcasts&quot;)<br>   .select(&quot;*&quot;)<br>   .eq(&quot;id&quot;, id);<br>  return data as Podcast[];<br> } catch (error) {<br>  console.log(error);<br>  return [];<br> }<br>}<br><br>export default async function Page({ params }: { params: { id: string } }) {<br> const data = await fetchData(params.id);<br> console.log(data);<br> const show = data[0];<br> return (<br>  &lt;main className=&quot;flex min-h-screen flex-col items-center justify-start p-24 gap-12&quot;&gt;<br>   &lt;div className=&quot;flex flex-col items-start gap-12&quot;&gt;<br>    &lt;div className=&quot;overflow-hidden&quot; key={show.id}&gt;<br>     &lt;img<br>      src={show.image_url}<br>      className=&quot;max-h-[400px] max-w-[400px] object-cover&quot;<br>      alt={show.id.toString()}<br>     /&gt;<br>     &lt;div className=&quot;p-2 flex flex-col gap-2&quot;&gt;<br>      &lt;h3 className=&quot;croll-m-20 text-2xl font-semibold tracking-tight&quot;&gt;<br>       {show.name}<br>      &lt;/h3&gt;<br>      &lt;p&gt;{show.description}&lt;/p&gt;<br>     &lt;/div&gt;<br>    &lt;/div&gt;<br>   &lt;/div&gt;<br>  &lt;/main&gt;<br> );<br>}</pre><p>You’ll notice this looks pretty similar to our original page but with just a few small tweaks. To start we have the path param that we discussed earlier and we use that as an argument in our fetchData function. With this setup we’ll only select the podcast that matches the id passed in the path, then display it’s data.</p><h3>Building the Episodes</h3><p>We’ve got everything we need now to actually list and create episodes for each podcast. To start this up we’ll make a new file called episode-list.tsx inside the components folder and put the following content inside.</p><pre>import { supabase } from &quot;@/lib/db&quot;;<br>import { CreateEpisodeForm } from &quot;./create-episode-form&quot;;<br>import { Button } from &quot;./ui/button&quot;;<br>import Link from &quot;next/link&quot;;</pre><pre>export const revalidate = 60;</pre><pre>export type Episode = {<br> id: number;<br> created_at: string;<br> podcast: string;<br> audio_url: string;<br> description: string;<br> name: string;<br>};</pre><pre>async function fetchData(id: string): Promise&lt;Episode[]&gt; {<br> try {<br>  const { data, error } = await supabase<br>   .from(&quot;episodes&quot;)<br>   .select(&quot;*&quot;)<br>   .eq(&quot;podcast&quot;, id);<br>  return data as Episode[];<br> } catch (error) {<br>  console.log(error);<br>  return [];<br> }<br>}<br>export async function EpisodeList({<br> id,<br> groupId<br>}: { id: string; groupId: string; }) {<br> const data = await fetchData(id);<br> console.log(data);<br> return (<br>  &lt;div className=&quot;flex flex-col gap-12 w-full&quot;&gt;<br>   {data.map((item: Episode) =&gt; (<br>    &lt;div key={item.id} className=&quot;flex flex-col gap-2&quot;&gt;<br>     &lt;h4 className=&quot;scroll-m-20 text-xl font-semibold tracking-tight&quot;&gt;<br>      {item.name}<br>     &lt;/h4&gt;<br>     &lt;p&gt;{item.description}&lt;/p&gt;<br>     &lt;audio controls src={item.audio_url}&gt;<br>      &lt;track kind=&quot;captions&quot; src=&quot;&quot; label=&quot;English&quot; /&gt;<br>     &lt;/audio&gt;<br>    &lt;/div&gt;<br>   ))}<br>   &lt;div className=&quot;flex justify-center gap-4&quot;&gt;<br>    &lt;Button asChild&gt;<br>     &lt;Link href=&quot;/&quot;&gt; Go Back &lt;/Link&gt;<br>    &lt;/Button&gt;<br>    &lt;CreateEpisodeForm<br>     id={id}<br>     groupId={groupId}<br>    /&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br> );<br>}</pre><p>This component is also pretty simple and works similar to our other server rendered pages, where we have some parameters and fetch the episodes from our database. In particular we only pull episodes from the podcast we’re looking at, aka the id. We also take in a groupId that we’ll need for putting episodes into, which we’ll see soon. The episode data includes things like the linked podcast, the name and description of the episode, and of course the audio for it. For our app we’re just doing audio but since the Files API allows any kind of file you could also do video here too! Once we fetch that data from the database we just map it into the JSX.</p><p>You’ll notice from the code above that we have another component we haven’t made yet; let’s do that now! Inside the componenets folder make a new file called create-episode-form.tsx and put in the following code.</p><pre>&quot;use client&quot;;</pre><pre>import { zodResolver } from &quot;<a href="http://twitter.com/hookform/resolvers">@hookform/resolvers</a>/zod&quot;;<br>import { useForm } from &quot;react-hook-form&quot;;<br>import { useState } from &quot;react&quot;;<br>import { z } from &quot;zod&quot;;<br>import { Button } from &quot;@/components/ui/button&quot;;<br>import {<br> Form,<br> FormControl,<br> FormDescription,<br> FormField,<br> FormItem,<br> FormLabel,<br> FormMessage,<br>} from &quot;@/components/ui/form&quot;;<br>import { Input } from &quot;@/components/ui/input&quot;;<br>import {<br> Dialog,<br> DialogContent,<br> DialogTitle,<br> DialogTrigger,<br>} from &quot;@/components/ui/dialog&quot;;<br>import { ReloadIcon } from &quot;<a href="http://twitter.com/radix">@radix</a>-ui/react-icons&quot;;<br>import { pinata } from &quot;@/lib/pinata&quot;;</pre><pre>const formSchema = z.object({<br> name: z.string().min(2),<br> description: z.string().min(2),<br> file: z.any(),<br>});</pre><pre>export function CreateEpisodeForm({<br> groupId,<br> id,<br>}: { groupId: string; id: string; }) {<br> const [isLoading, setIsLoading] = useState(false);</pre><pre>const form = useForm&lt;z.infer&lt;typeof formSchema&gt;&gt;({<br>  resolver: zodResolver(formSchema),<br>  defaultValues: {<br>   name: &quot;&quot;,<br>  },<br> });</pre><pre>const fileRef = form.register(&quot;file&quot;);</pre><pre>async function onSubmit(values: z.infer&lt;typeof formSchema&gt;) {<br>  setIsLoading(true);<br>  const file: File | null = values.file ? values.file[0] : null;<br>  if (file) {<br>   const keyRequest = await fetch(&quot;/api/key&quot;);<br>   const keys = await keyRequest.json();<br>   const uploadFile = await pinata.upload<br>    .file(file)<br>    .key(keys.JWT)<br>    .group(groupId);<br>   const data = new FormData();<br>   data.append(&quot;name&quot;, values.name);<br>   data.append(&quot;description&quot;, values.description);<br>   data.append(<br>    &quot;audio&quot;,<br>    `<a href="https://${process.env.next_public_gateway_url}/files/$%7BuploadFile.cid%7D%60">https://${process.env.NEXT_PUBLIC_GATEWAY_URL}/files/${uploadFile.cid}`</a>,<br>   );<br>   data.append(&quot;podcastId&quot;, id);<br>   const createEpisodeRequest = await fetch(&quot;/api/episode&quot;, {<br>    method: &quot;POST&quot;,<br>    body: data,<br>   });<br>   const createEpisode = await createEpisodeRequest.json();<br>   console.log(createEpisode);<br>   setIsLoading(false);<br>  } else {<br>   console.log(&quot;no file selected&quot;);<br>   setIsLoading(false);<br>  }<br> }</pre><pre>function ButtonLoading() {<br>  return (<br>   &lt;Button disabled&gt;<br>    &lt;ReloadIcon className=&quot;mr-2 h-4 w-4 animate-spin&quot; /&gt;<br>    Please wait<br>   &lt;/Button&gt;<br>  );<br> }</pre><pre>return (<br>  &lt;Dialog&gt;<br>   &lt;DialogTrigger&gt;<br>    &lt;Button&gt;Add Episode&lt;/Button&gt;<br>   &lt;/DialogTrigger&gt;</pre><pre>&lt;DialogContent&gt;<br>    &lt;DialogTitle&gt;Add an Episode&lt;/DialogTitle&gt;<br>    &lt;Form {...form}&gt;<br>     &lt;form onSubmit={form.handleSubmit(onSubmit)} className=&quot;space-y-8&quot;&gt;<br>      &lt;FormField<br>       control={form.control}<br>       name=&quot;name&quot;<br>       render={({ field }) =&gt; (<br>        &lt;FormItem&gt;<br>         &lt;FormLabel&gt;Name&lt;/FormLabel&gt;<br>         &lt;FormControl&gt;<br>          &lt;Input placeholder=&quot;Once upon a time&quot; {...field} /&gt;<br>         &lt;/FormControl&gt;<br>         &lt;FormDescription&gt;<br>          What&#39;s the title of the episode<br>         &lt;/FormDescription&gt;<br>         &lt;FormMessage /&gt;<br>        &lt;/FormItem&gt;<br>       )}<br>      /&gt;<br>      &lt;FormField<br>       control={form.control}<br>       name=&quot;description&quot;<br>       render={({ field }) =&gt; (<br>        &lt;FormItem&gt;<br>         &lt;FormLabel&gt;Description&lt;/FormLabel&gt;<br>         &lt;FormControl&gt;<br>          &lt;Input placeholder=&quot;On this week&#39;s episode...&quot; {...field} /&gt;<br>         &lt;/FormControl&gt;<br>         &lt;FormDescription&gt;<br>          What happens in this episode?<br>         &lt;/FormDescription&gt;<br>         &lt;FormMessage /&gt;<br>        &lt;/FormItem&gt;<br>       )}<br>      /&gt;<br>      &lt;FormField<br>       control={form.control}<br>       name=&quot;file&quot;<br>       render={({ field }) =&gt; (<br>        &lt;FormItem&gt;<br>         &lt;FormLabel&gt;Audio&lt;/FormLabel&gt;<br>         &lt;FormControl&gt;<br>          &lt;Input type=&quot;file&quot; {...fileRef} /&gt;<br>         &lt;/FormControl&gt;<br>         &lt;FormDescription&gt;<br>          Select the Audio file for the Podcast<br>         &lt;/FormDescription&gt;<br>         &lt;FormMessage /&gt;<br>        &lt;/FormItem&gt;<br>       )}<br>      /&gt;<br>      {isLoading ? (<br>       ButtonLoading()<br>      ) : (<br>       &lt;Button type=&quot;submit&quot;&gt;Submit&lt;/Button&gt;<br>      )}<br>     &lt;/form&gt;<br>    &lt;/Form&gt;<br>   &lt;/DialogContent&gt;<br>  &lt;/Dialog&gt;<br> );<br>}</pre><p>If you take a look you’ll see it looks very similar to the other form we created; in fact it’s almost identical except for one very important piece. When it comes to doing uploads in Next.js there is a size limit of what can be passed through our API route, 4mb to be precise. While that’s fine for the cover image we did earlier, its not ideal for a larger audio or video file that we need for the episode. Since this is a client side component we risk exposing our API key if we try to use our pinata instance here to upload it. Thankfully the Pinata SDK has a trick up it’s sleeve 😏</p><p>Right before we start the API call to make an episode, we have a request to /api/key; let’s make that API path right now and make a route.ts file inside with this code:</p><pre>import { type NextRequest, NextResponse } from &quot;next/server&quot;;<br>const { v4: uuidv4 } = require(&quot;uuid&quot;);<br>import { pinata } from &quot;@/lib/pinata&quot;;<br><br>export const dynamic = &quot;force-dynamic&quot;;<br><br>export async function GET(req: NextRequest, res: NextResponse) {<br> try {<br>  const uuid = uuidv4();<br>  const keyData = await pinata.keys.create({<br>   keyName: uuid.toString(),<br>   permissions: {<br>    endpoints: {<br>     pinning: {<br>      pinFileToIPFS: true,<br>     },<br>    },<br>   },<br>   maxUses: 1,<br>  });<br>  return NextResponse.json(keyData, { status: 200 });<br> } catch (error) {<br>  console.log(error);<br>  return NextResponse.json(<br>   { text: &quot;Error creating API Key:&quot; },<br>   { status: 500 },<br>  );<br> }<br>}</pre><p>This little handler here will make a limited scope/use Pinata JWT. It can only do a single file upload, which is all we need! The SDK makes it easy to create these keys and scope them as necessary. We just make the key and send it back to the client.</p><p>Now you may be saying “but Steve, how do we use an API key if we already passed it into our instance?” I’m glad you asked! (and only slightly offended if you didn’t 😉) The SDK has a special method on uploads that allows you to pass in a temporary API key! So if we look closer at our upload flow it looks something like this:</p><pre>// rest of onSubmit()<br>const keyRequest = await fetch(&quot;/api/key&quot;);<br>const keys = await keyRequest.json();<br>const uploadFile = await pinata.upload<br>	.file(file)<br>	.key(keys.JWT)<br>	.group(groupId);<br>// rest of function</pre><p>With just a few lines of code we essentially created a signed JWT that we can use for our larger file upload on the client, bypassing the restrictive file size of the Next API routes! The SDK shines at being flexible for whatever situations you might find yourself in. We also used that groupId that was passed into the component, making sure our audio files stay in the same group as our podcast. Now if we continue the onSubmit function you’ll notice something else.</p><pre>// rest of onSubmit()<br>const data = new FormData();<br>data.append(&quot;name&quot;, values.name);<br>data.append(&quot;description&quot;, values.description);<br>data.append(<br>	&quot;audio&quot;,<br>	`https://${process.env.NEXT_PUBLIC_GATEWAY_URL}/files/${uploadFile.cid}`,<br>);<br>data.append(&quot;podcastId&quot;, id);<br>const createEpisodeRequest = await fetch(&quot;/api/episode&quot;, {<br>	method: &quot;POST&quot;,<br>	body: data,<br>});<br>const createEpisode = await createEpisodeRequest.json();<br>console.log(createEpisode);<br>setIsLoading(false);</pre><p>You’ll see here we attach all of our properties like we did earlier with the podcast form such as the name and description. We also form our audio_url just like we did on the /api/podcast route but just client side this time. From there we append our podcastId and then make another API call to /api/episode; you know the drill, let’s make app/api/episode/route.ts and put this code in:</p><pre>import type { NextRequest } from &quot;next/server&quot;;<br>import { NextResponse } from &quot;next/server&quot;;<br>import { supabase } from &quot;@/lib/db&quot;;<br><br>export async function POST(request: NextRequest) {<br> try {<br>  const formData = await request.formData();<br>  const name = formData.get(&quot;name&quot;);<br>  const description = formData.get(&quot;description&quot;);<br>  const podcastId = formData.get(&quot;podcastId&quot;);<br>  const audioUrl = formData.get(&quot;audio&quot;);<br>  const { data, error } = await supabase<br>   .from(&quot;episodes&quot;)<br>   .insert({<br>    name: name,<br>    description: description,<br>    audio_url: audioUrl,<br>    podcast: podcastId,<br>   })<br>   .select();<br>  console.log(data);<br>  if (error) {<br>   console.log(error);<br>   return NextResponse.json(<br>    { error: &quot;Internal Server Error&quot; },<br>    { status: 500 },<br>   );<br>  }<br>  return NextResponse.json(data, { status: 200 });<br> } catch (e) {<br>  console.log(e);<br>  return NextResponse.json(<br>   { error: &quot;Internal Server Error&quot; },<br>   { status: 500 },<br>  );<br> }<br>}</pre><p>Even simpler than the last one; we just take all our form items and push them as a new row in our episodes table. Before you even realized it, we’re done! We have a fully functioning podcast hosting app, targeted at Founders who really need to yap.</p><h3>Wrapping Up</h3><p>The truth is this is just the beginning of where you can take this. Ideally you would want to setup something like auth to make sure the right people are uploading to the right podcast. Luckily for you we did that in our final repo which you can check out <a href="https://github.com/PinataCloud/foundercloud">here</a>. If this is what you can do with public files, imagine what you can do with private files! Pinata makes it so easy to upload files in your app and access them with public groups like we did here, or with signed URLs that expire after a period of time:</p><pre>import { PinataSDK } from &quot;pinata&quot;;<br><br>const pinata = new PinataSDK({<br>  pinataJwt: process.env.PINATA_JWT!,<br>  pinataGateway: &quot;example-gateway.mypinata.cloud&quot;,<br>});<br><br>const url = await pinata.gateways.createSignedURL({<br> cid: &quot;bafkreib4pqtikzdjlj4zigobmd63lig7u6oxlug24snlr6atjlmlza45dq&quot;,<br> expires: 2400,<br>});</pre><p>We’re excited about the possibilities this new Files API brings and we’ll be sharing them along the way, so be sure to subscribe below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=280979ef5368" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pinata/how-to-build-a-simple-podcast-hosting-app-280979ef5368">How To Build a Simple Podcast Hosting App</a> was originally published in <a href="https://medium.com/pinata">Pinata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing the Pinata CLI in GO]]></title>
            <link>https://medium.com/pinata/writing-the-pinata-cli-in-go-94892e97a400?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/94892e97a400</guid>
            <category><![CDATA[ipfs]]></category>
            <category><![CDATA[web3-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 18:48:28 GMT</pubDate>
            <atom:updated>2024-01-18T18:48:28.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*TIGuNFVguoAPAZoaSayPTA.jpeg" /></figure><p><a href="https://www.pinata.cloud/blog/writing-the-pinata-cli-in-go"><em>This article was originally published on the Pinata Blog</em></a></p><p>If you’re a developer then there’s a strong chance you do a fair bit of work in the terminal. We use it for things like making new directories or files, cloning Git repositories, or setting up a new app with a command like npx create-pinata-app (try that one by the way). To help streamline work in the terminal many people also utilize Command Line Interfaces or CLI’s. They work like programs or shortcuts to multiple different script files or binaries to accomplish an array of different tasks. Pinata has had a Node.js CLI for several years that allowed people to upload files to IPFS. It’s been well loved, however not without its problems.</p><p>One of the downsides to the older Pinata CLI is that it was written in Node.js. Now don’t get me wrong, JavaScript has some pretty incredible flexibility to do lots of things, but it sometimes comes at the cost of performance. It was this notion that spurred us to rewrite the CLI in <a href="https://golang.org/">Golang</a> (aka Go), a language known for its speed and efficiency. It is actually the language <a href="https://www.pinata.cloud/blog/kubo-vs-helia-vs-elastic-ipfs-comparing-the-major-ipfs-implementations-ease-of-working-with">most IPFS nodes are implemented with</a>. Today, we’re sharing “the what” went into this rewrite so anyone can implement Go-based dev tools today.</p><h3>Starting Small</h3><p>When embarking on a project like this, the best thing you can do is start small. Focus on the smallest step and then slowly grow into more complex goals. Since we already had an existing CLI, we knew what functionality it would have to have. First, we needed to be able to authenticate a user with the <a href="https://docs.pinata.cloud/docs/api-keys">Pinata JWT</a>. To start we just wrote a simple Go program to make sure we could run a function. Then, we made a quick little function to test authentication with an API request.</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;log&quot;<br>	&quot;net/http&quot;<br>)<br><br>func TestAuthentication() {<br><br>	req, err := http.NewRequest(&quot;GET&quot;, &quot;&lt;https://api.pinata.cloud/data/testAuthentication&gt;&quot;, nil)<br>	if err != nil {<br>		log.Fatal(&quot;err with request&quot;, err)<br>	}<br><br>	req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+JWT)<br><br>	client := &amp;http.Client{}<br>	resp, err := client.Do(req)<br>	if err != nil {<br>		log.Fatal(&quot;error sending request&quot;, err)<br>	}<br><br>	defer resp.Body.Close()<br>status := resp.StatusCode<br>	if status == 200 {<br>		fmt.Println(&quot;testAuthentication: ✅&quot;)<br>	} else {<br>		fmt.Println(&quot;testAuthentication: ❌&quot;, status)<br>	}<br>}</pre><p>Now that we had this and could run it with the JWT variable, we needed to adjust it to accept a JWT, write it to the user’s dot files, then read it from that file and make sure it worked the same way.</p><pre>package main<br><br>import (<br>	&quot;errors&quot;<br>	&quot;fmt&quot;<br>	&quot;net/http&quot;<br>	&quot;os&quot;<br>	&quot;path/filepath&quot;<br>	&quot;time&quot;<br>)<br><br>func SaveJWT(jwt string) error {<br>	home, err := os.UserHomeDir()<br>	if err != nil {<br>		return err<br>	}<br>	p := filepath.Join(home, &quot;.pinata-go-cli&quot;)<br>	err = os.WriteFile(p, []byte(jwt), 0600)<br>	if err != nil {<br>		return err<br>	}<br>	host := GetHost()<br>	url := fmt.Sprintf(&quot;https://%s/data/testAuthentication&quot;, host)<br>	req, err := http.NewRequest(&quot;GET&quot;, url, nil)<br>	if err != nil {<br>		return err<br>	}<br><br>	req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+jwt)<br><br>	client := &amp;http.Client{<br>		Timeout: time.Duration(time.Second * 3),<br>	}<br>	resp, err := client.Do(req)<br>	if err != nil {<br>		return err<br>	}<br><br>	defer resp.Body.Close()<br>	status := resp.StatusCode<br>	if status != 200 {<br>		return errors.New(&quot;Authentication failed, make sure you are using the Pinata JWT&quot;)<br>	}<br><br>	fmt.Println(&quot;Authentication Successful!&quot;)<br>	return nil<br>}<br><br>func GetHost() string {<br>	return GetEnv(&quot;PINATA_HOST&quot;, &quot;api.pinata.cloud&quot;)<br>}<br><br>func GetEnv(key, defaultValue string) string {<br>	value := os.Getenv(key)<br>	if len(value) == 0 {<br>		return defaultValue<br>	}<br>	return value<br>}</pre><p>With the JWT saved to the user’s computer, we can now just read it for all of our other CLI functions rather than making them provide it every single time.</p><h3>Adding Complexity</h3><p>Now that we have authorization taken care of it was time to try something a bit harder: uploading a file. While it can sound a little daunting, all it takes is a bit of research and perhaps AI to figure out the best way to send a file via an API request. Then we just have to conform it to what the Pinata API expects. Since we wanted this upload function to accept files or folders without distinction, we made a helper function to check what the input was and append it accordingly.</p><pre>func pathsFinder(filePath string, stats os.FileInfo) ([]string, error) {<br>	var err error<br>	files := make([]string, 0)<br>	fileIsASingleFile := !stats.IsDir()<br>	if fileIsASingleFile {<br>		files = append(files, filePath)<br>		return files, err<br>	}<br>	err = filepath.Walk(filePath,<br>		func(path string, info os.FileInfo, err error) error {<br>			if err != nil {<br>				return err<br>			}<br>			if !info.IsDir() {<br>				files = append(files, path)<br>			}<br>			return nil<br>		})<br><br>	if err != nil {<br>		return nil, err<br>	}<br><br>	return files, err<br>}</pre><p>We also made a separate function to create the multipart request you normally need for file uploads. In it, we take in multiple arguments for the files, the version of the CID, and the name you would like for the file to be called once uploaded to Pinata.</p><pre>func createMultipartRequest(filePath string, files []string, body io.Writer, stats os.FileInfo, version int, name string) (string, error) {<br>	contentType := &quot;&quot;<br>	writer := multipart.NewWriter(body)<br><br>	fileIsASingleFile := !stats.IsDir()<br>	for _, f := range files {<br>		file, err := os.Open(f)<br>		if err != nil {<br>			return contentType, err<br>		}<br>		defer func(file *os.File) {<br>			err := file.Close()<br>			if err != nil {<br>				log.Fatal(&quot;could not close file&quot;)<br>			}<br>		}(file)<br><br>		var part io.Writer<br>		if fileIsASingleFile {<br>			part, err = writer.CreateFormFile(&quot;file&quot;, filepath.Base(f))<br>		} else {<br>			relPath, _ := filepath.Rel(filePath, f)<br>			part, err = writer.CreateFormFile(&quot;file&quot;, filepath.Join(stats.Name(), relPath))<br>		}<br>		if err != nil {<br>			return contentType, err<br>		}<br>		_, err = io.Copy(part, file)<br>		if err != nil {<br>			return contentType, err<br>		}<br>	}<br><br>	pinataOptions := Options{<br>		CidVersion: version,<br>	}<br><br>	optionsBytes, err := json.Marshal(pinataOptions)<br>	if err != nil {<br>		return contentType, err<br>	}<br>	err = writer.WriteField(&quot;pinataOptions&quot;, string(optionsBytes))<br><br>	if err != nil {<br>		return contentType, err<br>	}<br><br>	pinataMetadata := Metadata{<br>		Name: func() string {<br>			if name != &quot;nil&quot; {<br>				return name<br>			}<br>			return stats.Name()<br>		}(),<br>	}<br>	metadataBytes, err := json.Marshal(pinataMetadata)<br>	if err != nil {<br>		return contentType, err<br>	}<br>	_ = writer.WriteField(&quot;pinataMetadata&quot;, string(metadataBytes))<br>	err = writer.Close()<br>	if err != nil {<br>		return contentType, err<br>	}<br><br>	contentType = writer.FormDataContentType()<br><br>	return contentType, nil<br>}</pre><p>Finally, we can put it all together for an Upload function that handles errors, formats the response, and prints results to the user.</p><pre>func Upload(filePath string, version int, name string, cidOnly bool) (UploadResponse, error) {<br>	jwt, err := findToken()<br>	if err != nil {<br>		return UploadResponse{}, err<br>	}<br><br>	stats, err := os.Stat(filePath)<br>	if os.IsNotExist(err) {<br>		fmt.Println(&quot;File or folder does not exist&quot;)<br>		return UploadResponse{}, errors.Join(err, errors.New(&quot;file or folder does not exist&quot;))<br>	}<br><br>	files, err := pathsFinder(filePath, stats)<br>	if err != nil {<br>		return UploadResponse{}, err<br>	}<br><br>	body := &amp;bytes.Buffer{}<br>	contentType, err := createMultipartRequest(filePath, files, body, stats, version, name)<br>	if err != nil {<br>		return UploadResponse{}, err<br>	}<br><br>	totalSize := int64(body.Len())<br>	fmt.Printf(&quot;Uploading %s (%s)\\n&quot;, stats.Name(), formatSize(int(totalSize)))<br><br>	progressBody := newProgressReader(body, totalSize)<br><br>	host := GetHost()<br>	url := fmt.Sprintf(&quot;https://%s/pinning/pinFileToIPFS&quot;, host)<br>	req, err := http.NewRequest(&quot;POST&quot;, url, progressBody)<br>	if err != nil {<br>		return UploadResponse{}, errors.Join(err, errors.New(&quot;failed to create the request&quot;))<br>	}<br>	req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+string(jwt))<br>	req.Header.Set(&quot;content-type&quot;, contentType)<br><br>	client := &amp;http.Client{}<br>	resp, err := client.Do(req)<br>	if err != nil {<br>		return UploadResponse{}, errors.Join(err, errors.New(&quot;failed to send the request&quot;))<br>	}<br>	if resp.StatusCode != 200 {<br>		return UploadResponse{}, fmt.Errorf(&quot;server Returned an error %d&quot;, resp.StatusCode)<br>	}<br>	err = progressBody.bar.Set(int(totalSize))<br>	if err != nil {<br>		return UploadResponse{}, err<br>	}<br>	fmt.Println()<br>	defer func(Body io.ReadCloser) {<br>		err := Body.Close()<br>		if err != nil {<br>			log.Fatal(&quot;could not close request body&quot;)<br>		}<br>	}(resp.Body)<br><br>	var response UploadResponse<br>	err = json.NewDecoder(resp.Body).Decode(&amp;response)<br>	if err != nil {<br>		return UploadResponse{}, err<br>	}<br>	if cidOnly {<br>		fmt.Println(response.IpfsHash)<br>	} else {<br>		fmt.Println(&quot;Success!&quot;)<br>		fmt.Println(&quot;CID:&quot;, response.IpfsHash)<br>		fmt.Println(&quot;Size:&quot;, formatSize(response.PinSize))<br>		fmt.Println(&quot;Date:&quot;, response.Timestamp)<br>		if response.IsDuplicate {<br>			fmt.Println(&quot;Already Pinned: true&quot;)<br>		}<br>	}<br>	return response, nil<br>}</pre><p>Now that we have our main functions, the next goal is to build the CLI. Thankfully there are lots of great frameworks and tools to make the process easier, and personally, we fell in love with <a href="https://cli.urfave.org/">urfave/cli</a>. It makes everything pretty straightforward when it comes to building commands. Here’s what our CLI would look like with just authentications and uploads.</p><pre>package main<br><br>import (<br>	&quot;errors&quot;<br>	&quot;github.com/urfave/cli/v2&quot;<br>	&quot;log&quot;<br>	&quot;os&quot;<br>)<br><br>type UploadResponse struct {<br>	IpfsHash    string `json:&quot;IpfsHash&quot;`<br>	PinSize     int    `json:&quot;PinSize&quot;`<br>	Timestamp   string `json:&quot;Timestamp&quot;`<br>	IsDuplicate bool   `json:&quot;isDuplicate&quot;`<br>}<br><br>type Options struct {<br>	CidVersion int `json:&quot;cidVersion&quot;`<br>}<br><br>type Metadata struct {<br>	Name      string                 `json:&quot;name&quot;`<br>	KeyValues map[string]interface{} `json:&quot;keyvalues&quot;`<br>}<br><br>func main() {<br>	app := &amp;cli.App{<br>		Name:  &quot;pinata&quot;,<br>		Usage: &quot;A CLI for uploading files to Pinata! To get started make an API key at &lt;https://app.pinata.cloud/keys&gt;, then authorize the CLI with the auth command with your JWT&quot;,<br>		Commands: []*cli.Command{<br>			{<br>				Name:      &quot;auth&quot;,<br>				Aliases:   []string{&quot;a&quot;},<br>				Usage:     &quot;Authorize the CLI with your Pinata JWT&quot;,<br>				ArgsUsage: &quot;[your Pinata JWT]&quot;,<br>				Action: func(ctx *cli.Context) error {<br>					jwt := ctx.Args().First()<br>					if jwt == &quot;&quot; {<br>						return errors.New(&quot;no jwt supplied&quot;)<br>					}<br>					err := SaveJWT(jwt)<br>					return err<br>				},<br>			},<br>			{<br>				Name:      &quot;upload&quot;,<br>				Aliases:   []string{&quot;u&quot;},<br>				Usage:     &quot;Upload a file or folder to Pinata&quot;,<br>				ArgsUsage: &quot;[path to file]&quot;,<br>				Flags: []cli.Flag{<br>					&amp;cli.IntFlag{<br>						Name:    &quot;version&quot;,<br>						Aliases: []string{&quot;v&quot;},<br>						Value:   1,<br>						Usage:   &quot;Set desired CID version to either 0 or 1. Default is 1.&quot;,<br>					},<br>					&amp;cli.StringFlag{<br>						Name:    &quot;name&quot;,<br>						Aliases: []string{&quot;n&quot;},<br>						Value:   &quot;nil&quot;,<br>						Usage:   &quot;Add a name for the file you are uploading. By default it will use the filename on your system.&quot;,<br>					},<br>          &amp;cli.BoolFlag{<br>            Name: &quot;cid-only&quot;,<br>            Usage: &quot;Use if you only want the CID returned after an upload&quot;,<br>          },<br>				},<br>				Action: func(ctx *cli.Context) error {<br>					filePath := ctx.Args().First()<br>					version := ctx.Int(&quot;version&quot;)<br>					name := ctx.String(&quot;name&quot;)<br>          cidOnly := ctx.Bool(&quot;cid-only&quot;)<br>					if filePath == &quot;&quot; {<br>						return errors.New(&quot;no file path provided&quot;)<br>					}<br>					_, err := Upload(filePath, version, name, cidOnly)<br>					return err<br>				},<br>			},<br>		},<br>	}<br><br>	if err := app.Run(os.Args); err != nil {<br>		log.Fatal(err)<br>	}<br>}</pre><p>The urfave framework allows you to set up different commands with names, help tips, and more. You can also include flags for certain logic, so for instance, on upload, you can run pinata upload --version 0 and it would return a V0 CID QmVLwvmGehsrNEvhcCnnsw5RQNseohgEkFNN1848zNzdng vs the default V1 CID bafkreih5aznjvttude6c3wbvqeebb6rlx5wkbzyppv7garjiubll2ceym4. With this, we now have our MVP!</p><h3>Expanding Further</h3><p>Now that we have a general pattern and structure for our CLI, adding other commands is easy! For instance, to add a delete command to delete a file, we just add a new file called Delete.go and add in our code to make a request with the CID as the argument.</p><pre>package main<br><br>import (<br>	&quot;errors&quot;<br>	&quot;fmt&quot;<br>	&quot;net/http&quot;<br>)<br><br>func Delete(cid string) error {<br>	jwt, err := findToken()<br>	if err != nil {<br>		return err<br>	}<br>	host := GetHost()<br>	url := fmt.Sprintf(&quot;https://%s/pinning/unpin/%s&quot;, host, cid)<br><br>	req, err := http.NewRequest(&quot;DELETE&quot;, url, nil)<br>	if err != nil {<br>		return errors.Join(err, errors.New(&quot;failed to create the request&quot;))<br>	}<br>	req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+string(jwt))<br>	req.Header.Set(&quot;content-type&quot;, &quot;application/json&quot;)<br><br>	client := &amp;http.Client{}<br>	resp, err := client.Do(req)<br>	if err != nil {<br>		return errors.Join(err, errors.New(&quot;failed to send the request&quot;))<br>	}<br>	defer resp.Body.Close()<br><br>	if resp.StatusCode != 200 {<br>		return fmt.Errorf(&quot;server Returned an error %d, check CID&quot;, resp.StatusCode)<br>	}<br><br>	fmt.Println(&quot;File Deleted&quot;)<br><br>	return nil<br><br>}</pre><p>Then we just add that command to our main list of commands for the CLI.</p><pre>{<br>	Name:      &quot;delete&quot;,<br>	Aliases:   []string{&quot;d&quot;},<br>	Usage:     &quot;Delete a file by CID&quot;,<br>	ArgsUsage: &quot;[CID of file]&quot;,<br>	Action: func(ctx *cli.Context) error {<br>		cid := ctx.Args().First()<br>		if cid == &quot;&quot; {<br>			return errors.New(&quot;no CID provided&quot;)<br>		}<br>		err := Delete(cid)<br>		return err<br>	},<br>},</pre><p>With this, we can run pinata delete QmVLwvmGehsrNEvhcCnnsw5RQNseohgEkFNN1848zNzdng and it will unpin the file from our account. But what if you don’t have the CID? Well, let’s add in a file list too!</p><pre>package main<br><br>import (<br>	&quot;encoding/json&quot;<br>	&quot;errors&quot;<br>	&quot;fmt&quot;<br>	&quot;net/http&quot;<br>)<br><br>func ListFiles(amount string, cid string, name string, status string, offset string) (ListResponse, error) {<br>	jwt, err := findToken()<br>	if err != nil {<br>		return ListResponse{}, err<br>	}<br>	host := GetHost()<br>	url := fmt.Sprintf(&quot;https://%s/data/pinList?includesCount=false&amp;pageLimit=%s&amp;status=%s&quot;, host, amount, status)<br><br>	if cid != &quot;null&quot; {<br>		url += &quot;&amp;hashContains=&quot; + cid<br>	}<br>	if name != &quot;null&quot; {<br>		url += &quot;&amp;metadata[name]=&quot; + name<br>	}<br>	if offset != &quot;null&quot; {<br>		url += &quot;&amp;pageOffset=&quot; + offset<br>	}<br><br>	req, err := http.NewRequest(&quot;GET&quot;, url, nil)<br>	if err != nil {<br>		return ListResponse{}, errors.Join(err, errors.New(&quot;failed to create the request&quot;))<br>	}<br>	req.Header.Set(&quot;Authorization&quot;, &quot;Bearer &quot;+string(jwt))<br>	req.Header.Set(&quot;content-type&quot;, &quot;application/json&quot;)<br><br>	client := &amp;http.Client{}<br>	resp, err := client.Do(req)<br>	if err != nil {<br>		return ListResponse{}, errors.Join(err, errors.New(&quot;failed to send the request&quot;))<br>	}<br>	defer resp.Body.Close()<br><br>	if resp.StatusCode != 200 {<br>		return ListResponse{}, fmt.Errorf(&quot;server Returned an error %d&quot;, resp.StatusCode)<br>	}<br><br>	var response ListResponse<br><br>	err = json.NewDecoder(resp.Body).Decode(&amp;response)<br>	if err != nil {<br>		return ListResponse{}, err<br>	}<br>	formattedJSON, err := json.MarshalIndent(response.Rows, &quot;&quot;, &quot;    &quot;)<br>	if err != nil {<br>		return ListResponse{}, errors.New(&quot;failed to format JSON&quot;)<br>	}<br><br>	fmt.Println(string(formattedJSON))<br><br>	return response, nil<br><br>}</pre><p>This one is interesting as the /data/pinList endpoint has a lot of acceptable queries, so depending on what the user enters we’ll add in several here and add the command to our CLI like the others.</p><pre>{<br>	Name:    &quot;list&quot;,<br>	Aliases: []string{&quot;l&quot;},<br>	Usage:   &quot;List most recent files&quot;,<br>	Flags: []cli.Flag{<br>		&amp;cli.StringFlag{<br>			Name:    &quot;cid&quot;,<br>			Aliases: []string{&quot;c&quot;},<br>			Value:   &quot;null&quot;,<br>			Usage:   &quot;Search files by CID&quot;,<br>		},<br>		&amp;cli.StringFlag{<br>			Name:    &quot;amount&quot;,<br>			Aliases: []string{&quot;a&quot;},<br>			Value:   &quot;10&quot;,<br>			Usage:   &quot;The number of files you would like to return, default 10 max 1000&quot;,<br>		},<br>		&amp;cli.StringFlag{<br>			Name:    &quot;name&quot;,<br>			Aliases: []string{&quot;n&quot;},<br>			Value:   &quot;null&quot;,<br>			Usage:   &quot;The name of the file&quot;,<br>		},<br>		&amp;cli.StringFlag{<br>			Name:    &quot;status&quot;,<br>			Aliases: []string{&quot;s&quot;},<br>			Value:   &quot;pinned&quot;,<br>			Usage:   &quot;Status of the file. Options are &#39;pinned&#39;, &#39;unpinned&#39;, or &#39;all&#39;. Default: &#39;pinned&#39;&quot;,<br>		},<br>		&amp;cli.StringFlag{<br>			Name:    &quot;pageOffset&quot;,<br>			Aliases: []string{&quot;p&quot;},<br>			Value:   &quot;null&quot;,<br>			Usage:   &quot;Allows you to paginate through files. If your file amount is 10, then you could set the pageOffset to &#39;10&#39; to see the next 10 files.&quot;,<br>		},<br>	},<br>	Action: func(ctx *cli.Context) error {<br>		cid := ctx.String(&quot;cid&quot;)<br>		amount := ctx.String(&quot;amount&quot;)<br>		name := ctx.String(&quot;name&quot;)<br>		status := ctx.String(&quot;status&quot;)<br>		offset := ctx.String(&quot;pageOffset&quot;)<br>		_, err := ListFiles(amount, cid, name, status, offset)<br>		return err<br>	},<br>},</pre><p>With this command, I can easily fetch my 10 latest files with pinata list! We purposely make the output of the command to be formatted JSON so developers can pipe it into files or other services, as well as plenty of flags to search and filter their results.</p><h3>Wrapping Up</h3><p>After we had built out this CLI and tested it we noticed quite a boost in performance compared to its Node.js predecessor, and it gave us the opportunity to explore what else we could make it do. The result is a CLI that mimics most of the Pinata API and gives you the tools you need to extend your IPFS workflow. It’s been so fun and easy to use that I find myself using it in my own workflows all the time for projects like <a href="https://cosmiccowboys.cloud/">Cosmic Cowboys</a> and beyond. Don’t take my word for it; try it out now! Just visit <a href="https://github.com/PinataCloud/pinata-go-cli">this link</a> and follow the download instructions and usage guide to get started.</p><p>This project is just the beginning as we plan to port the Pinata API into a new Typescript SDK, as well as other programming languages. Our community has done a great job making <a href="https://docs.pinata.cloud/docs/sdks#community-sdks">their own implementations</a>, but we’re excited to focus on developers and continue supporting them no matter what language they’re working in.</p><p>Happy Pinning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94892e97a400" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pinata/writing-the-pinata-cli-in-go-94892e97a400">Writing the Pinata CLI in GO</a> was originally published in <a href="https://medium.com/pinata">Pinata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Encrypt And Decrypt Files On IPFS Using Lit Protocol And Pinata]]></title>
            <link>https://medium.com/pinata/how-to-encrypt-and-decrypt-files-on-ipfs-using-lit-protocol-and-pinata-27040f8048d0?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/27040f8048d0</guid>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[pinata]]></category>
            <category><![CDATA[ipfs]]></category>
            <category><![CDATA[token-gating]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 20:49:36 GMT</pubDate>
            <atom:updated>2024-01-16T06:02:45.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*spE1HlmTsfGVOGLR.jpeg" /></figure><p><a href="https://www.pinata.cloud/blog/how-to-encrypt-and-decrypt-files-on-ipfs-using-lit-protocol-and-pinata"><em>This post was originally posted on Pinata.cloud</em></a></p><p>The most popular method used for sharing files off-chain in Web3 is IPFS, and there are some <a href="https://www.pinata.cloud/blog/why-ipfs-is-the-storage-solution-for-web3-developers">good reasons for that</a>. However it does not come without its own share of problems, and one of those is the ability to share private files. IPFS is a public network so anyone with a CID can access and download that content, and this hinders projects that may want to token gate content or create subscriptions to content. With that said, encryption has proven to be one solution to this problem. Remarkably, the solution of <a href="https://www.okta.com/identity-101/asymmetric-encryption/">asymmetric encryption</a> is used in blockchain all the time and can be reused for the purpose of token gating. <a href="https://litprotocol.com/">Lit Protocol</a> is a decentralized middleware client that enables access controls to help extend asymmetric encryption to token gating based on crypto ownership, such as owning an NFT, ERC-20 token balance, or simply designating a recipient address. In this post, we’ll show you how you can combine the best of both worlds and create an app that will encrypt content, upload it to IPFS, and then given an encrypted CID, decrypt it.</p><h3>Why IPFS?</h3><p>IPFS is public and openly available, but it’s also not permanent by default. This means that unlike blockchain storage protocols that make every piece of content permanent as soon as it’s uploaded, you can potentially remove content from IPFS. You’ll see why this is important as we explore encryption more deeply.</p><p>The biggest problem with encryption is that its always evolving. One encryption method we use today will be outdated one day in the future. An example is <a href="https://www.okta.com/identity-101/md5/#:~:text=The%20MD5%20hash%20function&#39;s%20security,be%20used%20for%20malicious%20purposes.)">MD5 which was cracked almost perhaps 10 years ago</a>. but people still use it without knowing the risk. When we consider putting files on a decentralized network that are specifically designed to not be taken down, things get messy. Arweave is a common consideration for encryption and decentralized storage, however, their model puts content on the network permanently. There is the possibility those encrypted files could be cracked in another 10 years.</p><p>IPFS is different in that content is not “permanent,” but rather it is “persistent.” It’s a subtle difference but has massive ramifications. With IPFS, the content will only stay on the network if at least one IPFS node keeps the content “<a href="https://www.pinata.cloud/blog/what-is-pinning">pinned</a>,” which tells other nodes that might have a cached copy of the content to keep it available. As soon as there are no nodes pinning a particular CID, then the nodes holding that cache will dump it when they use garbage collection. It’s a unique mechanism that helps prevent digital waste and ensures only the content we value will persist. The concepts of permanence and persistence are truly philosophical differences of approaching the same problem.</p><p>When you combine IPFS with encryption, you get a unique situation where content that is no longer used can be unpinned. Granted it does not guarantee the content will be completely wiped from the network, but it does give users a level of control over their content they would normally not have with other decentralized storage networks. It is also unlikely that bad actors would go through the trouble and costs to keep encrypted content pinned for the purpose of decrypting it years down the road. The <a href="https://www.pinata.cloud/blog/is-ipfs-free">cost of storage</a> helps balance situations like these. With that said let’s actually build this thing!</p><blockquote>ℹ️ <strong>Disclosure:</strong> There will always be limitations to encryption and eventually current methods may be cracked. Please be aware of the risk involved and be sure to read <a href="https://developer.litprotocol.com/v3/sdk/authentication/security">Lit Protocol’s best practices for security</a>.</blockquote><h3>Building the App</h3><p>What’s great about this project is that we already have most of what we need to build it! Pinata created a <a href="https://www.pinata.cloud/blog/announcing-pinata-ipfs-developer-starter-templates">Next.js template</a> a while back which we can use again and just add in our Lit Protocol SDK.</p><p>To follow this tutorial you will want to make sure you have the following:</p><ul><li>Node.js 18 or higher</li><li><a href="https://app.pinata.cloud/register">A Free Pinata Account</a></li><li>A text editor like VSCode</li></ul><p>Before going any further make sure you get a <a href="https://app.pinata.cloud/register">free Pinata account</a> so you can make an <a href="https://docs.pinata.cloud/docs/api-keys">API key</a> and get a <a href="https://docs.pinata.cloud/docs/dedicated-ipfs-gateways">free Dedicated Gateway</a> for this project! Once you make an API key, save the JWT that we’ll use in a little bit, as well as the gateway domain for your Dedicated Gateways.</p><p>Thats it! To kick it off, simply run the command to use the Pinata Next.js Template</p><pre>npx create-pinata-app</pre><p>You will be prompted to choose your flavors of the app, such as Typescript vs Javascript, or Tailwindcss vs Vanilla CSS. For this template, I chose Typescript and Tailwindcss but feel free to choose your own. After giving it a name and making your selections go ahead and open the project in VSCode.</p><p>Back in the terminal the next thing we’re going to do is install the <a href="https://developer.litprotocol.com/v3/sdk/installation">Lit Protocol SDK</a>. We’ll be using the V3 of the SDK which is in beta, and you can install based on their docs <a href="https://developer.litprotocol.com/v3/sdk/installation">here</a> or use this command:</p><pre>npm install @lit-protocol/lit-node-client@cayenne</pre><p>The last thing you need to do to set up the project is open the .env.sample file which should look like this:</p><pre>PINATA_JWT=<br>NEXT_PUBLIC_GATEWAY_URL=<br>NEXT_PUBLIC_GATEWAY_TOKEN=</pre><p>Paste in the PINATA_JWT that you made earlier when you set up your Pinata account and also paste in the NEXT_PUBLIC_GATEWAY_URL with the format https://mygateway.mypinata.cloud with of course your own domain URL. Then change the name of the file from .env.sample to .env.local, a very important step for our app to work!</p><p>Now lets go ahead and spin up the dev server with npm run dev and start building. All of our work will be done in just one file, pages/index.tsx; easy! We’ll start by importing the Lit Protocol SDK at the top of the file.</p><pre>import { useState, useRef } from &quot;react&quot;;<br>import Head from &quot;next/head&quot;;<br>import Image from &quot;next/image&quot;;<br>import Files from &quot;@/components/Files&quot;;<br>// import lit protocol sdk<br>import * as LitJsSdk from &quot;@lit-protocol/lit-node-client&quot;;</pre><p>Inside the Home component, we’ll add another state variable that we’ll come back to later.</p><pre>const [file, setFile] = useState(&quot;&quot;);<br>const [cid, setCid] = useState(&quot;&quot;);<br>const [uploading, setUploading] = useState(false);<br>// add a new state for the cid to decrypt<br>const [decryptionCid, setDecryptionCid] = useState(&quot;&quot;);</pre><p>The great thing about this template is that it’s already got uploads to IPFS with Pinata baked in with an /api/files route on the backend, so all we have to do is encrypt the file before we upload it. We’ll do this in the uploadFile function inside of Home, and it should look like this to start.</p><pre>const uploadFile = async (fileToUpload) =&gt; {<br>    try {<br>      setUploading(true);<br>      const formData = new FormData();<br>      formData.append(&quot;file&quot;, fileToUpload, fileToUpload.name)<br>      const res = await fetch(&quot;/api/files&quot;, {<br>        method: &quot;POST&quot;,<br>        body: formData,<br>      });<br>      const ipfsHash = await res.text();<br>      setCid(ipfsHash);<br>      setUploading(false);<br>    } catch (e) {<br>      console.log(e);<br>      setUploading(false);<br>      alert(&quot;Trouble uploading file&quot;);<br>    }<br>  };</pre><p>At the top of our try statement but underneath our setUploading state, we’ll initialize the LitNodeClient using the ceyenne network, connect our app to that network, then get the authSig. Lit Protocol is a decentralized network middleware that helps us do some cool token gating and lets us do encryption. In these few statements, we create a client that connects to that middleware network and then gets a signature from the user. This signature will be used for signing the encrypted files.</p><pre>const uploadFile = async (fileToUpload) =&gt; {<br>    try {<br>      setUploading(true); <br>      const litNodeClient = new LitJsSdk.LitNodeClient({<br>        litNetwork: &#39;cayenne&#39;,<br>      });<br>      // then get the authSig<br>      await litNodeClient.connect();<br>      const authSig = await LitJsSdk.checkAndSignAuthMessage({<br>        chain: &#39;ethereum&#39;<br>      });<br>// rest of the code</pre><p>Next up we’ll set up our access controls for this encrypted content. We’ll dive deeper into this later in the tutorial, but essentially this is the most important part of our app as it determines who can decrypt the content we encrypt. It could be something like token gating by NFT collection or a direct address. For now, we’ll keep it simple and allow anyone with a balance of 0 ETH or higher to decrypt it (that should be everyone with a wallet).</p><pre>const uploadFile = async (fileToUpload) =&gt; {<br>    try {<br>      setUploading(true); <br>			// Create our litNodeClient<br>      const litNodeClient = new LitJsSdk.LitNodeClient({<br>        litNetwork: &#39;cayenne&#39;,<br>      });<br>      // Then get the authSig<br>      await litNodeClient.connect();<br>      const authSig = await LitJsSdk.checkAndSignAuthMessage({<br>        chain: &#39;ethereum&#39;<br>      });<br>			// Define our access controls, this is set to be anyone <br>			const accs = [<br>        {<br>          contractAddress: &#39;&#39;,<br>          standardContractType: &#39;&#39;,<br>          chain: &#39;ethereum&#39;,<br>          method: &#39;eth_getBalance&#39;,<br>          parameters: [&#39;:userAddress&#39;, &#39;latest&#39;],<br>          returnValueTest: {<br>            comparator: &#39;&gt;=&#39;,<br>            value: &#39;0&#39;,<br>          },<br>        },<br>      ];<br>// rest of the code</pre><p>The fun part; encrypting! There are several methods of encryption that Lit Protocol offers through their SDK, such as just a string, or a file, and in our case, we’ll use the encryptFileAndZipWithMetadata method. This is handy because in order to decrypt a file, our recipient will need the accs parameters we set and a secure hash. We want a simple way for all of this to be packaged and included in our IPFS CID, and that&#39;s exactly what this method will do. All we have to do is pass in our access control conditions array, our authSig, the chain, our fileToUpload that we passed into the function argument, the litNodeClient, and finally a simple readme that will explain to whoever happens to download it from IPFS what they need to do with it.</p><pre>const uploadFile = async (fileToUpload) =&gt; {<br>    try {<br>      setUploading(true);<br>      // Create our litNodeClient<br>      const litNodeClient = new LitJsSdk.LitNodeClient({<br>        litNetwork: &#39;cayenne&#39;,<br>      });<br>      // Then get the authSig<br>      await litNodeClient.connect();<br>      const authSig = await LitJsSdk.checkAndSignAuthMessage({<br>        chain: &#39;ethereum&#39;<br>      });<br>      // Define our access controls, this is set to be anyone<br>      const accs = [<br>        {<br>          contractAddress: &#39;&#39;,<br>          standardContractType: &#39;&#39;,<br>          chain: &#39;ethereum&#39;,<br>          method: &#39;eth_getBalance&#39;,<br>          parameters: [&#39;:userAddress&#39;, &#39;latest&#39;],<br>          returnValueTest: {<br>            comparator: &#39;&gt;=&#39;,<br>            value: &#39;0&#39;,<br>          },<br>        },<br>      ];<br>      // Then we use our access controls and authSig to encrypt the file and zip it up with the metadata<br>      const encryptedZip = await LitJsSdk.encryptFileAndZipWithMetadata({<br>        accessControlConditions: accs,<br>        authSig: authSig,<br>        chain: &#39;ethereum&#39;,<br>        file: fileToUpload,<br>        litNodeClient: litNodeClient,<br>        readme: &quot;Use IPFS CID of this file to decrypt it&quot;<br>      });<br>// rest of the code</pre><p>One last little touch we need to do is adapt this encrypted zip file so it will be accepted by our /api/files endpoint, and we’ll do so with just two lines of code.</p><pre>// Then we turn it into a file that will be accepted by the API endpoint<br>const encryptedBlob = new Blob([encryptedZip], { type: &#39;text/plain&#39; })<br>const encryptedFile = new File([encryptedBlob], fileToUpload.name)</pre><p>All together we should have an upload function that looks like this:</p><pre>const uploadFile = async (fileToUpload) =&gt; {<br>    try {<br>      setUploading(true);<br>      // Create our litNodeClient<br>      const litNodeClient = new LitJsSdk.LitNodeClient({<br>        litNetwork: &#39;cayenne&#39;,<br>      });<br>      // Then get the authSig<br>      await litNodeClient.connect();<br>      const authSig = await LitJsSdk.checkAndSignAuthMessage({<br>        chain: &#39;ethereum&#39;<br>      });<br>      // Define our access controls, this is set to be anyone<br>      const accs = [<br>        {<br>          contractAddress: &#39;&#39;,<br>          standardContractType: &#39;&#39;,<br>          chain: &#39;ethereum&#39;,<br>          method: &#39;eth_getBalance&#39;,<br>          parameters: [&#39;:userAddress&#39;, &#39;latest&#39;],<br>          returnValueTest: {<br>            comparator: &#39;&gt;=&#39;,<br>            value: &#39;0&#39;,<br>          },<br>        },<br>      ];<br>      // Then we use our access controls and authSig to encrypt the file and zip it up with the metadata<br>      const encryptedZip = await LitJsSdk.encryptFileAndZipWithMetadata({<br>        accessControlConditions: accs,<br>        authSig: authSig,<br>        chain: &#39;ethereum&#39;,<br>        file: fileToUpload,<br>        litNodeClient: litNodeClient,<br>        readme: &quot;Use IPFS CID of this file to decrypt it&quot;<br>      });<br>      // Then we turn it into a file that will be accepted by the Pinata API<br>      const encryptedBlob = new Blob([encryptedZip], { type: &#39;text/plain&#39; })<br>      const encryptedFile = new File([encryptedBlob], fileToUpload.name)<br>      // Finally we upload the file by passing it to our /api/files endpoint<br>      // Keep in mind this works for smaller files and you may need to do a presigned JWT and upload from the client if you&#39;re dealing with larger files<br>      // Read more about that here: &lt;https://www.pinata.cloud/blog/how-to-upload-to-ipfs-from-the-frontend-with-signed-jwts&gt;<br>      const formData = new FormData();<br>      formData.append(&quot;file&quot;, encryptedFile, encryptedFile.name)<br>      const res = await fetch(&quot;/api/files&quot;, {<br>        method: &quot;POST&quot;,<br>        body: formData,<br>      });<br>      const ipfsHash = await res.text();<br>      setCid(ipfsHash);<br>      setUploading(false);<br>    } catch (e) {<br>      console.log(e);<br>      setUploading(false);<br>      alert(&quot;Trouble uploading file&quot;);<br>    }<br>  };</pre><p>One thing to note is that there is a file size restriction when using the Next API routes, so if you have larger files you may want to move uploading to the client side and utilize pre-signed JWTs which we talk about in <a href="https://www.pinata.cloud/blog/how-to-upload-to-ipfs-from-the-frontend-with-signed-jwts">this post.</a></p><p>We now have encrypted uploads! If you upload a file through the app you should get a CID, and if you download the file it will result in a zip folder with all the stuff we just made. This is cool, but how do we decrypt it? How do we let other people decrypt it? Its actually pretty easy! We’re gonna make a new function right below our upload function called decryptFile(), which will take a fileToDecrypt CID. First thing we’ll do is fetch that file using our Dedicated Gateway and turn it into a blob.</p><pre>const decryptFile = async (fileToDecrypt) =&gt; {<br>    try {<br>      // First we fetch the file from IPFS using the CID and our Gateway URL, then turn it into a blob<br>      const fileRes = await fetch(`${process.env.NEXT_PUBLIC_GATEWAY_URL}/ipfs/${fileToDecrypt}?filename=encrypted.zip`)<br>      const file = await fileRes.blob()<br>    } catch (error) {<br>      alert(&quot;Trouble decrypting file&quot;)<br>      console.log(error)<br>    }</pre><p>Now we can re-create the litNodeClient and get the auth signature. The beauty of this SDK is that once some signs they will not need to sign again unless they disconnect from the app, making the interactions fairly smooth.</p><pre>const decryptFile = async (fileToDecrypt) =&gt; {<br>    try {<br>      // First we fetch the file from IPFS using the CID and our Gateway URL, then turn it into a blob<br>      const fileRes = await fetch(`${process.env.NEXT_PUBLIC_GATEWAY_URL}/ipfs/${fileToDecrypt}?filename=encrypted.zip`)<br>      const file = await fileRes.blob()<br>      // We recreated the litNodeClient and the authSig<br>      const litNodeClient = new LitJsSdk.LitNodeClient({<br>        litNetwork: &#39;cayenne&#39;,<br>      });<br>      await litNodeClient.connect();<br>      const authSig = await LitJsSdk.checkAndSignAuthMessage({<br>        chain: &#39;ethereum&#39;<br>      });<br>    } catch (error) {<br>      alert(&quot;Trouble decrypting file&quot;)<br>      console.log(error)<br>    }</pre><p>Just like we used encryptFileAndZipWithMetadata method, we have a matching method for decryption called decryptZipFileWithMetadata which we’ll use very similarly to the encryption. The zip folder has everything we need so all we have to pass in is the file blob, our litNodeClient, and the recipient authSig. Piece of cake! From this, we’ll extract the decryptedFile and metadata from our request.</p><pre>const decryptFile = async (fileToDecrypt) =&gt; {<br>    try {<br>      // First we fetch the file from IPFS using the CID and our Gateway URL, then turn it into a blob<br>      const fileRes = await fetch(`${process.env.NEXT_PUBLIC_GATEWAY_URL}/ipfs/${fileToDecrypt}?filename=encrypted.zip`)<br>      const file = await fileRes.blob()<br>      // We recreated the litNodeClient and the authSig<br>      const litNodeClient = new LitJsSdk.LitNodeClient({<br>        litNetwork: &#39;cayenne&#39;,<br>      });<br>      await litNodeClient.connect();<br>      const authSig = await LitJsSdk.checkAndSignAuthMessage({<br>        chain: &#39;ethereum&#39;<br>      });<br>      // Then we simpyl extract the file and metadata from the zip<br>      // We could do more with this, like try to display it in the app UI if we wanted to<br>      const { decryptedFile, metadata } = await LitJsSdk.decryptZipFileWithMetadata({<br>        file: file,<br>        litNodeClient: litNodeClient,<br>        authSig: authSig,<br>      })<br>    } catch (error) {<br>      alert(&quot;Trouble decrypting file&quot;)<br>      console.log(error)<br>    }</pre><p>All that’s left to do is deliver the file to the user! There are several ways you could go about it, for example, if you want to display the content to the user such as an image or video you could do so with a bit of formatting. In this example, we’ll just trigger a download to the recipient’s computer. All together we should have the following.</p><pre>const decryptFile = async (fileToDecrypt) =&gt; {<br>    try {<br>      // First we fetch the file from IPFS using the CID and our Gateway URL, then turn it into a blob<br>      const fileRes = await fetch(`${process.env.NEXT_PUBLIC_GATEWAY_URL}/ipfs/${fileToDecrypt}?filename=encrypted.zip`)<br>      const file = await fileRes.blob()<br>      // We recreated the litNodeClient and the authSig<br>      const litNodeClient = new LitJsSdk.LitNodeClient({<br>        litNetwork: &#39;cayenne&#39;,<br>      });<br>      await litNodeClient.connect();<br>      const authSig = await LitJsSdk.checkAndSignAuthMessage({<br>        chain: &#39;ethereum&#39;<br>      });<br>      // Then we simpyl extract the file and metadata from the zip<br>      // We could do more with this, like try to display it in the app UI if we wanted to<br>      const { decryptedFile, metadata } = await LitJsSdk.decryptZipFileWithMetadata({<br>        file: file,<br>        litNodeClient: litNodeClient,<br>        authSig: authSig,<br>      })<br>      // After we have our dcypted file we can download it<br>      const blob = new Blob([decryptedFile], { type: &#39;application/octet-stream&#39; });<br>      const downloadLink = document.createElement(&#39;a&#39;);<br>      downloadLink.href = URL.createObjectURL(blob);<br>      downloadLink.download = metadata.name;  // Use the metadata to get the file name and type<br>      downloadLink.click()<br>    } catch (error) {<br>      alert(&quot;Trouble decrypting file&quot;)<br>      console.log(error)<br>    }</pre><p>One small little change we’ll make to the JSX is a text input where someone can paste in a CID and a “Decrypt” button someone can press after pasting in their CID.</p><pre>&lt;input<br>  type=&quot;text&quot;<br>  onChange={(e) =&gt; setDecryptionCid(e.target.value)}<br>  className=&quot;px-4 py-2 border-2 border-secondary rounded-3xl text-lg&quot;<br>  placeholder=&quot;Enter CID to decrypt&quot;<br>/&gt;<br>&lt;button<br>  onClick={() =&gt; decryptFile(decryptionCid)}<br>  className=&quot;mr-10 w-[150px] bg-light text-secondary border-2 border-secondary rounded-3xl py-2 px-4 hover:bg-secondary hover:text-light transition-all duration-300 ease-in-out&quot;<br>&gt;Decrypt&lt;/button&gt;</pre><p>With all of this together, you should have an app with the following flow!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*o7bzXPqkdQjGhXLGRLeBTQ.gif" /></figure><p>You can also download and use this exact template <a href="https://github.com/PinataCloud/pinata-lit-protocol-template">here</a>!</p><h3>Going Further</h3><p>This little template is really designed just to get you started and help you understand how Pinata and Lit Protocol work, and there is so much you can do with it. I would highly recommend checking out Lit Protocol’s documentation, in particular their section on all the <a href="https://developer.litprotocol.com/v3/sdk/access-control/evm/basic-examples">different access controls</a> you can do. For example, if you only wanted holders of a particular ERC721 NFT you could use the following.</p><pre>const accessControlConditions = [<br>  {<br>    contractAddress: &#39;0xA80617371A5f511Bf4c1dDf822E6040acaa63e71&#39;,<br>    standardContractType: &#39;ERC721&#39;,<br>    chain,<br>    method: &#39;balanceOf&#39;,<br>    parameters: [<br>      &#39;:userAddress&#39;<br>    ],<br>    returnValueTest: {<br>      comparator: &#39;&gt;&#39;,<br>      value: &#39;0&#39;<br>    }<br>  }<br>]</pre><p>Or you could do DAO membership (MolochDAOv2.1, also supports DAOHaus)</p><pre>const accessControlConditions = [<br>  {<br>    contractAddress: &#39;0x50D8EB685a9F262B13F28958aBc9670F06F819d9&#39;,<br>    standardContractType: &#39;MolochDAOv2.1&#39;,<br>    chain,<br>    method: &#39;members&#39;,<br>    parameters: [<br>      &#39;:userAddress&#39;,<br>    ],<br>    returnValueTest: {<br>      comparator: &#39;=&#39;,<br>      value: &#39;true&#39;<br>    }<br>  }<br>]</pre><p>You can even do a simple check if the recipient is a particular wallet address.</p><pre>const accessControlConditions = [<br>  {<br>    contractAddress: &#39;&#39;,<br>    standardContractType: &#39;&#39;,<br>    chain,<br>    method: &#39;&#39;,<br>    parameters: [<br>      &#39;:userAddress&#39;,<br>    ],<br>    returnValueTest: {<br>      comparator: &#39;=&#39;,<br>      value: &#39;0x50e2dac5e78B5905CB09495547452cEE64426db2&#39;<br>    }<br>  }<br>]</pre><p>With these building blocks, you could easily build a standalone token gating app, or build a custom solution for your holders. The possibilities are endless!</p><p>Happy Pinning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27040f8048d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pinata/how-to-encrypt-and-decrypt-files-on-ipfs-using-lit-protocol-and-pinata-27040f8048d0">How To Encrypt And Decrypt Files On IPFS Using Lit Protocol And Pinata</a> was originally published in <a href="https://medium.com/pinata">Pinata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Run IPFS a Raspberry Pi]]></title>
            <link>https://medium.com/pinata/how-to-run-ipfs-a-raspberry-pi-135abe1ce40f?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/135abe1ce40f</guid>
            <category><![CDATA[pinata]]></category>
            <category><![CDATA[decentralization]]></category>
            <category><![CDATA[ipfs]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 20:37:44 GMT</pubDate>
            <atom:updated>2023-12-21T18:44:29.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*8CzIOP60l0Vi_yvi.jpeg" /></figure><p><a href="https://www.pinata.cloud/blog/how-to-run-ipfs-on-a-raspberry-pi"><em>This post was originally posted on Pinata.cloud</em></a></p><p>If you’re a developer or a tinkerer, then you probably have played with a Raspberry Pi at some point. They’re incredibly versatile mini-computers, capable of playing games, running a normal desktop, cybersecurity tools, and helping power a decentralized file-sharing network like IPFS. In order for these types of networks to truly grow and spread more people need to run their own IPFS nodes to help distribute content. There a lots of ways you can do this today, some of them easy as installing an app on your computer and letting it run. The only downside is that it can hog resources on your computer, create a heavy cache, and you likely won’t keep it on 24/7. This is where a Raspberry Pi is perfect, because you can plug it in, let it run all day, and you can access it from your computer without sacrificing your own performance. In this post, we’ll show you how to set up IPFS on a Raspberry Pi, as well as how to upload files to <a href="https://www.pinata.cloud/blog/what-is-ipfs">IPFS</a> &amp; Pinata from it!</p><p>To get started you will need a few things.</p><ul><li>Raspberry Pi 3/4 - You can try some older models but make sure it has 64bit architecture.</li><li>Micro SD card and card reader - Can be any size but would recommend a 32GB minimum.</li><li>SSH - If you have never set up SSH before on your computer it&#39;s pretty simple, would recommend following <a href="https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/create-with-openssh/">this guide</a>.</li><li>Pinata Account - Want to back up your pins to Pinata? <a href="https://app.pinata.cloud/register">Sign up for a free account</a> and then follow <a href="https://docs.pinata.cloud/docs/api-keys">these steps</a> to make an API key. Be sure to save the JWT that we’ll be using in this tutorial!</li></ul><h3>Raspberry Pi Setup</h3><p>Getting the software installed on our Raspberry Pi won’t be too difficult thanks to their Raspberry Pi OS Imager which you can download <a href="https://docs.pinata.cloud/docs/api-keys">here</a>. This will allow us to burn an operating software to our micro SD card, which we’ll later boot into on the Raspberry Pi. When you install the imager and run it, you’ll see the first button to “Choose OS.” Go ahead and click on that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MjDCxtvZJNUA6CY6.png" /></figure><p>Scroll down the list and select “Raspberry Pi OS (other).”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eYz1xK7vyaLNhprZ.png" /></figure><p>Then select “Raspberry Pi OS Lite (64-bit).” This is going to be a more minimal, terminal-only operating system which will take up less space and make our IPFS node more performant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yUsG07UFlmVxL8x5.png" /></figure><p>Once you select that it will take you to the main screen again where you can click “Choose Storage” where you will want to locate and select your Micro SD card that is plugged into your computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A3rdj1_YMZUPTVyp.png" /></figure><p>Now before we write this software, we need to preconfigure a few things. Since this is terminal only and we may not have an easy way to see what we’re typing, setting up stuff like wifi could be tricky. Thankfully the imager tool has some awesome tricks to make this simpler. On the main screen click the little setting cog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YdXoZxwtlJmmVFci.png" /></figure><p>You should see this next screen with a lot of stuff to fill out, but we’ll break down each bit to make it simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*at2PRl3m4hYlzOPf.png" /></figure><ul><li>Set Hostname - For this, you can make it whatever name you want it to be! It will basically be the name of the computer. Could name it raspberrypi, ipfsnode, or in my case “kubo.”</li><li>Enable SSH - For this one, you will want to use “Allow public-key authentication only” and you will want to paste in your public ssh key where it says Set authorized_keys for steve. If you’re not sure how to do that you can check out this guide <a href="https://docs.digitalocean.com/products/droplets/how-to/add-ssh-keys/create-with-openssh/">here</a>.</li><li>Set username and password - This will be used for running certain code like sudo commands so be sure to set what you want your username to be and a password, just like any other computer.</li><li>Configure wireless LAN - Here you can manually type in the name of your wifi and the password for it. What’s great about this is that your Raspberry Pi will automatically to your home wifi and make it discoverable for SSH.</li><li>Set locale settings - Handy to make sure you’re in the right timezone and have the correct keyboard layout.</li></ul><p>Thats it! Save those settings then hit “Write.” It should only take a minute or two, and once its done you can remove the micro SD card.</p><p>Now that our micro SD card has our preconfigured software, plug it into the Raspberry Pi and power it up with a USB-C cable, and give it a minute or so to boot up. The next step is a bit tricky because in order to ssh into our Pi, we need the IP address. This is assigned by your router when you connect to the wifi, so in order to get it you may need to use your home router to find the IP address. Another hack you can try is installing arp-scan in your terminal and then running sudo arp-scan -l. Doing so will list all the devices connected to that wifi and you should see the name Raspberry Pi somewhere with the IPV4 address.</p><p>Once you have the IP address, you can ssh into the Pi like so:</p><pre>ssh steve@192.168.0.100</pre><p>Just keep in mind the IP I’m using here is just an example, it will likely be totally different for your Pi. Once you run this command it will prompt you to enter the passphrase for your ssh key if you have one, prompt if you want to leave a fingerprint to which you’ll want to type yes. Then you should be logged in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WAIGBqW4BAU5lM9S.png" /></figure><h3>Installing and Setting Up IPFS</h3><p>To install IPFS we’re going to download Kubo, a Go implementation of an IPFS node. Visit the <a href="https://github.com/ipfs/kubo/releases">releases page</a> of Kubo to select which version you want to use. If you’re using Raspberry Pi OS Lite 64-bit that we set up earlier, you’re gonna want to download kubo_v0.23.3_linux-arm64.tar.gz. The version might be more advanced depending on when you’re reading this post, but Linux should still be relevant, as well as the arm64 architecture. To download it you can run:</p><pre>wget &quot;&lt;https://github.com/ipfs/kubo/releases/download/v0.23.0/kubo_v0.23.0_linux-arm64.tar.gz&gt;&quot;</pre><p>If it downloads successfully you can extract the zip file with tar -xf followed by the file name.</p><pre>tar -xf kubo_v0.23.0_linux-arm64.tar.gz</pre><p>This should create a new folder called kubo, which you will want to cd into and run the [install.sh](&lt;http://install.sh&gt;) script.</p><pre>cd kubo &amp;&amp; sudo ./install.sh</pre><p>This will move the IPFS program from the folder to /usr/bin where it can be run. To make sure it was installed correctly run the following command to check the version.</p><pre>ipfs --version</pre><p>If you get the current version then the installation was a success! Now let’s set up the IPFS node to run non-stop, and turn it back on whenever we power it on. To do that you will want to run the following command.</p><pre>sudo nano /etc/systemd/user/ipfs.service</pre><p>This will create a new file using the nano text editor where we will paste in a config file into system, giving us the ability to have this run in the background. Once that file is open paste in the following.</p><pre>[Unit]<br>Description=InterPlanetary File System (IPFS) daemon<br>Documentation=https://docs.ipfs.io/<br>After=network.target<br><br>[Service]<br>Type=notify<br>ExecStart=/usr/local/bin/ipfs daemon --enable-gc=true --migrate=true<br>ExecStop=/usr/local/bin/ipfs shutdown<br>Restart=on-failure<br>KillSignal=SIGINT<br><br>[Install]<br>WantedBy=default.target</pre><p>Once you have that pasted in you will want to hit Ctrl + O to save the file, then Ctrl + x to exit the nano text editor. Now that we have that file in place, run the following commands in order.</p><pre>ipfs init --profile=server --empty-repo<br>systemctl --user enable ipfs<br>systemctl --user start ipfs<br>systemctl --user status ipfs<br>loginctl enable-linger $USER</pre><p>Let’s walk through these just so you know what&#39;s going on!</p><ul><li>ipfs init --profile=server --empty-repo - This one is prepping our IPFS node to run and does so with some settings that will optimize it as a server node.</li><li>systemctl --user enable ipfs &amp; systemctl --user start ipfs - With this command, we fire up the ipfs.service file we made earlier, creating a background daemon that will continue to run 24/7.</li><li>systemctl --user status ipfs - After you run this command you should see an output about what happened when the daemon was started, and it should show the logs from the IPFS node starting up!</li><li>loginctl enable-linger $USER - This command will make sure our daemon will continue to run even after we leave the ssh session.</li></ul><p>That’s it! Your Raspberry Pi IPFS node is officially in business, and even if you turn it off or unplug it, you can just plug it back in and it will start up again. But let’s not stop there; what if you want to use it to upload files to IPFS and perhaps back them up to Pinata?</p><h3>Uploading Files via Pinata Pinning Service API</h3><p>Running an IPFS node is a good and noble deed for the sake of the decentralized network, however, if you want to actively use it to host files and share them with others, that’s when it can get a bit tricky. Since it’s just one IPFS node, it can make discovering any content you pin difficult. Thankfully the implementors of IPFS thought about this and saw the value of <a href="https://www.pinata.cloud/blog/what-is-an-ipfs-pinning-service">pinning services</a> and created something called the Pinning Service API. This allows you to connect your IPFS node to a larger pinning service like Pinata to help expand the reach of your content, as it uploads pins from your node to your Pinata account where they are broadcasted on a large global network of IPFS nodes.</p><p>Setting up the link between your node and Pinata is pretty simple. First, you will need to get a Pinata account and API key, both of which are free! If you haven’t done that already, be sure to <a href="https://app.pinata.cloud/">sign up here</a> and learn how to make an API key <a href="https://docs.pinata.cloud/docs/api-keys">here</a>. We will want to use the JWT in particular so be sure to save that when you create the key. Something else you may need is a way to transfer the files from your local machine to the Raspberry Pi. There are a few ways to do this, an <a href="https://filezilla-project.org/">FTP client</a> to move files is one of them. In any case, the best way to make them accessible is to put them in /home/yourname/ where your home directory is.</p><p>To set up the Pinata Pinning Service API just paste in this line, and be sure to replace PINATA_JWT with the API key JWT that you created earlier.</p><pre>ipfs pin remote service add pinata &lt;https://api.pinata.cloud/psa&gt; PINATA_JWT</pre><p>Then run this command to make sure it was successfully added.</p><pre>ipfs pin remote service ls</pre><p>If it worked then you should see Pinata listed! Now let’s upload a file. Run the command simply by using the name of your file instead. Make sure it&#39;s the correct path, so for instance if you have it in a folder called documents then it would be ./Documents/filename.ext</p><pre>ipfs add filename.ext</pre><p>So for example, if I had a file called pinnie.png in my home directory I would simply run ipfs add pinnie.png. Easy! It should respond with the CID after pinning is complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w5EiHcwgF_lqkWk-.png" /></figure><p>Now we can add that file to Pinata with the following command.</p><pre>ipfs pin remote add CID --service=pinata --background=true --name=myfile</pre><p>In our case, we’ll paste in the CID we just got back for Pinnie, and we’ll give it the name of pinnie.png. If you have a larger file that will take some time, you can add --background=true to let the pinning command run in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4NGEISthXXEsfNAi.png" /></figure><p>Nice!! Now our wonderful image of Pinnie is being distributed by not only my Raspberry Pi, but Pinata’s IPFS node network as well, making sure no one has issues seeing it.</p><p>There’s nothing more satisfying than knowing that at your home, office, or where your Raspberry Pi is plugged in, you’re taking part in growing the IPFS network and helping the distribution of content all over the world. Who knows what could be floating through your node; it could be the latest and greatest NFT image, it could be an important journalism document, or it could even be a website! Now you can upload to IPFS too, and back up any content to a pinning service like Pinata.</p><p>Happy Pinning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=135abe1ce40f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pinata/how-to-run-ipfs-a-raspberry-pi-135abe1ce40f">How to Run IPFS a Raspberry Pi</a> was originally published in <a href="https://medium.com/pinata">Pinata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create an NFT Minting App on Base with Crossmint and Pinata]]></title>
            <link>https://medium.com/pinata/how-to-create-an-nft-minting-app-on-base-with-crossmint-and-pinata-a97b7a91797d?source=rss-4d073fd47475------2</link>
            <guid isPermaLink="false">https://medium.com/p/a97b7a91797d</guid>
            <category><![CDATA[nft-development]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[web3-development]]></category>
            <category><![CDATA[base]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[Steve Simkins]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 14:37:54 GMT</pubDate>
            <atom:updated>2023-10-18T14:37:54.777Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*k06qW-_UsAFIERtu.jpeg" /></figure><p><a href="https://www.pinata.cloud/blog/how-to-create-an-nft-minting-app-on-base-with-crossmint-and-pinata"><em>This article was originally posted on the Pinata Blog</em></a></p><p>Web3 infrastructure has grown significantly in the past several years and interacting with blockchains has never been better for developers. There are many tools you can use to quickly and easily build your apps with, and a couple of those are <a href="https://crossmint.com/">Crossmint</a> and <a href="https://pinata.cloud/">Pinata</a>. Just recently Crossmint announced support for Base, a new layer 2 blockchain by Coinbase, for their minting API. Combining this with Pinata for self governed IPFS is a breeze, so in this post we’ll show you how to make an NFT minting app for Base using Pinata and Crossmint. If you want a fully blown demo of what we’re building, check out <a href="https://enchantmint.cloud/">Enchantmint.cloud</a>!</p><h3>Setup</h3><p>To follow along with this technical tutorial you will need a few things:</p><ul><li>Node.js version 16 or higher</li><li>NPM version 8 or higher</li><li>A text editor like VS Code</li><li>Accounts for:</li><li>Pinata</li><li>Crossmint</li><li>Walletconnect</li></ul><p>We’ll walk you through the setup process for each of them.</p><h3>Pinata</h3><p>Getting your Pinata account setup is super simple, just head over to <a href="http://app.pinata.cloud/register">app.pinata.cloud/register</a> and sign up for a free account! After signing up go ahead and make an API key with admin access, and save the Api Key, Api Secret, and JWT somewhere safe. We’ll only be using the JWT in this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8lA42gENmqsGtU_V9_qSg.gif" /></figure><p>You will also want to grab your Dedicated Gateway domain which comes with your free account. Simply visit the Gateways tab and copy it down!</p><h3>Crossmint</h3><p>Crossmint is also simple to setup but will take just a few more steps. First you’ll want to head over to the <a href="https://www.crossmint.com/console/overview">Crossmint Console</a> and sign up for an account. Something important to note is that Crossmint has separate consoles for staging and production, so if you want to make NFTs on a testnet then you will want to select staging here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDbdvCMAt9FLtUEeW9ygRg.png" /></figure><p>After you have signed in to your chosen console, click on the Collections tab and click “New Collection.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1y2CwR5JWWYMgpZBu5Qd0w.png" /></figure><p>Walk through the steps to give a name, description, and image for your collection. After that’s complete find the Project ID and Collection ID in the top left corner. Save both of these. If you don’t see Base available as a current chain you can also use the <a href="https://docs.crossmint.com/reference/create-collection">API endpoint</a> to create a collection. Go back to the Console and click on the API Keys page. From this page create a new API key with all the Minting API scopes, thats all you should need. Once those are created you’ll see both a Project ID and your Client Secret ; save both of these as well and you should be set!</p><h3>Walletconnect</h3><p>This project will use Walletconnect for our wallet client so we can have users login and mint NFTs to their address. Just visit <a href="http://walletconnect.com/">Walletconnect.com</a> and sign up for a free account and click “New Project” in the top right, give it a name, then click “create.” Then just copy the Project ID and save it with the rest of your secrets and keys. That’s it!</p><h3>Optional: Alchemy</h3><p>In this project we’ll just use the publicProvider for our wallet setup but if you wanted to use your own custom RPC you could get an Alchemy account and use it in the Wagmi config!</p><h3>Building the App</h3><p>To kick off our project we’re going to use Next.js, so pull up your terminal and run</p><pre>npx create-next-app@latest</pre><p>You can select which options you prefer such as typescript or tailwindcss, but our examples will go basic using the pages router. Once that’s complete and you cd into the project, install the following dependencies:</p><pre>npm install @rainbow-me/rainbowkit wagmi uuid</pre><p>Next we’ll open up our project in text editor of choice and create a file in the root of the project folder called .env.local where we will stash all our variables we created earlier. You can use this template for all the names and values.</p><pre>// .env.local<br>PINATA_JWT=<br>CROSSMINT_CLIENT_SECRET=<br>CROSSMINT_PROJECT_ID=<br>CROSSMINT_COLLECTION_ID=<br>NEXT_PUBLIC_WALLETCONNECT_ID=<br>NEXT_PUBLIC_PINATA_DEDICATED_GATEWAY=</pre><p>The Pinata Dedicated Gateway domain should be the following format: https://your-domain-name.mypinata.cloud/ipfs/</p><p>With our secrets and keys ready to go, let’s open up the _app.js file to setup our Rainbow Kit wallet!</p><pre>// _app.js<br>import { useEffect, useState } from &quot;react&quot;<br>import &#39;@/styles/globals.css&#39;<br>import &#39;@rainbow-me/rainbowkit/styles.css&#39;;<br>import {<br>  getDefaultWallets,<br>  RainbowKitProvider,<br>} from &#39;@rainbow-me/rainbowkit&#39;;<br>import { configureChains, createConfig, WagmiConfig } from &#39;wagmi&#39;;<br>import {<br>  base<br>} from &#39;wagmi/chains&#39;;<br>import { publicProvider } from &#39;wagmi/providers/public&#39;;<br>const { chains, publicClient } = configureChains(<br>  [base],<br>  <br>    publicProvider()<br>  ]<br>);<br>const { connectors } = getDefaultWallets({<br>  appName: &#39;My RainbowKit App&#39;,<br>  projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_ID,<br>  chains<br>});<br>const wagmiConfig = createConfig({<br>  autoConnect: true,<br>  connectors,<br>  publicClient<br>})<br>export default function App({ Component, pageProps }) {<br>  const [isReady, setIsReady] = useState(false)<br>  useEffect(() =&gt; {<br>    setIsReady(true)<br>  }, [])<br>  return (<br>    &lt;&gt;<br>      {isReady ? (<br>        &lt;WagmiConfig config={wagmiConfig}&gt;<br>          &lt;RainbowKitProvider<br>            chains={chains}<br>            initialChain={base}<br>          &gt;<br>            &lt;Component {...pageProps} /&gt;<br>          &lt;/RainbowKitProvider&gt;<br>        &lt;/WagmiConfig&gt;<br>      ) : null}<br>    &lt;/&gt;<br>  );<br>}</pre><p>Here we’re doing a couple of things. First we import all the things we need for our wallet provider and declare some constants. Most of this is boiler plate that you can get from Rainbow Kit’s docs and templates for Next.js. We’re also doing a bit of a hacky solution to prevent hydration errors by using useEffect and useState.</p><p>One small thing we need to adjust for Rainbow Kit to work is the next.config.js file, where you can simply paste this from their Next.js template.</p><pre>/** @type {import(&#39;next&#39;).NextConfig} */<br>const nextConfig = {<br>  reactStrictMode: true,<br>  webpack: config =&gt; {<br>    config.resolve.fallback = { fs: false, net: false, tls: false };<br>    config.externals.push(&#39;pino-pretty&#39;, &#39;lokijs&#39;, &#39;encoding&#39;);<br>    return config;<br>  },<br>}<br>module.exports = nextConfig</pre><p>Now let’s move to our index.js file and clear out all the boiler plate and reduce it to this</p><pre>//index.js<br>import Head from &#39;next/head&#39;<br><br>export default function Home() {<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Pinata NFT Minter&lt;/title&gt;<br>        &lt;meta name=&#39;description&#39; content=&#39;Generated by create next app&#39; /&gt;<br>        &lt;meta name=&#39;viewport&#39; content=&#39;width=device-width, initial-scale=1&#39; /&gt;<br>        &lt;link rel=&#39;icon&#39; href=&#39;/favicon.ico&#39; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        &lt;div&gt;<br>          &lt;h1&gt;Pinata NFT Minter&lt;/h1&gt;<br>        &lt;/div&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>This page is gonna be really easy, all we’re going to do is import a ConnectButton from Rainbow Kit, and a useAccount hook from Wagmi. Then we’ll extract isConnected from useAccount to help us do some conditional rendering for our main component. This way we can greet the user with a wallet connect button, then once they connect, show them our minting Form component (which we’ll build soon but go ahead declare the import now).</p><pre>// index.js<br>import Head from &#39;next/head&#39;<br>import { ConnectButton } from &#39;@rainbow-me/rainbowkit&#39;;<br>import { useAccount } from &#39;wagmi&#39;<br>import Form from &quot;@/components/Form&quot;<br>export default function Home() {<br>  const { isConnected } = useAccount()<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Pinata NFT Minter&lt;/title&gt;<br>        &lt;meta name=&#39;description&#39; content=&#39;Generated by create next app&#39; /&gt;<br>        &lt;meta name=&#39;viewport&#39; content=&#39;width=device-width, initial-scale=1&#39; /&gt;<br>        &lt;link rel=&#39;icon&#39; href=&#39;/favicon.ico&#39; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        &lt;div&gt;<br>          &lt;h1&gt;Pinata NFT Minter&lt;/h1&gt;<br>          {!isConnected &amp;&amp; (<br>      {/* if they&#39;re not connected, show them the button to connect */}<br>            &lt;ConnectButton /&gt;<br>          )}<br>          {isConnected &amp;&amp; (<br>            {/* Declare our new Form component that we&#39;re about to build */}<br>      &lt;Form /&gt;<br>          )}<br>        &lt;/div&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>Our main sauce will be our form component which will let users enter the details of their NFT, upload a file, and ultimately mint it. To do this create a /components directory in your src folder, then add Form.js to it. Open the file after creating it and add the following:</p><pre>// Form.js<br>import { useState } from &quot;react&quot;;<br>import { useAccount } from &quot;wagmi&quot;;<br>import { ConnectButton } from &quot;@rainbow-me/rainbowkit&quot;;<br>const Form = () =&gt; {<br>  const [selectedFile, setSelectedFile] = useState();<br>  const [name, setName] = useState();<br>  const [description, setDescription] = useState();<br>  const [externalURL, setExternalURL] = useState();<br>  const [osLink, setOsLink] = useState(&quot;https://opensea.io&quot;);<br>  const [isLoading, setIsLoading] = useState(false);<br>  const [message, setMessage] = useState(&quot;&quot;);<br>  const [isComplete, setIsComplete] = useState(false);<br>  const { address } = useAccount();<br>  const fileChangeHandler = (event) =&gt; {<br>    setSelectedFile(event.target.files[0]);<br>  };<br>  const nameChangeHandler = (event) =&gt; {<br>    setName(event.target.value);<br>  };<br>  const descriptionChangeHandler = (event) =&gt; {<br>    setDescription(event.target.value);<br>  };<br>  const externalURLChangeHandler = (event) =&gt; {<br>    setExternalURL(event.target.value);<br>  };<br>  const handleSubmission = async () =&gt; {<br>    let key;<br>    let keyId;<br>    let fileCID;<br>    let uri;<br>    try {<br>      // Minting will go here<br>    } catch (error) {<br>      console.log(error);<br>    }<br>  };<br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;<br>        &lt;ConnectButton /&gt;<br>      &lt;/div&gt;<br>      {!isLoading &amp;&amp; !isComplete &amp;&amp; (<br>        &lt;&gt;<br>          &lt;label onChange={fileChangeHandler} htmlFor=&quot;file&quot;&gt;<br>            &lt;input name=&quot;&quot; type=&quot;file&quot; id=&quot;file&quot; hidden /&gt;<br>            &lt;p&gt;{!selectedFile ? &quot;Select File&quot; : `${selectedFile.name}`}&lt;/p&gt;<br>          &lt;/label&gt;<br>          &lt;label&gt;Name&lt;/label&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            placeholder=&quot;Cool NFT&quot;<br>            onChange={nameChangeHandler}<br>          /&gt;<br>          &lt;label&gt;Description&lt;/label&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            placeholder=&quot;This NFT is just so cool&quot;<br>            onChange={descriptionChangeHandler}<br>          /&gt;<br>          &lt;label&gt;Your Website&lt;/label&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            placeholder=&quot;https://pinata.cloud&quot;<br>            onChange={externalURLChangeHandler}<br>          /&gt;<br>          &lt;button onClick={handleSubmission}&gt;Submit&lt;/button&gt;<br>        &lt;/&gt;<br>      )}<br>      {isLoading &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;h2&gt;{message}&lt;/h2&gt;<br>        &lt;/div&gt;<br>      )}<br>      {isComplete &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;h4&gt;{message}&lt;/h4&gt;<br>          &lt;a href={osLink} target=&quot;_blank&quot; rel=&quot;noreferrer&quot;&gt;<br>            &lt;h3&gt;Link to NFT&lt;/h3&gt;<br>          &lt;/a&gt;<br>          &lt;button onClick={() =&gt; setIsComplete(false)}&gt;Mint Another NFT&lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br>export default Form;</pre><p>There’s a good bit going on there but nothing too complicated so let’s walk though it. First we’re importing useState to handle our different form fields and files, useAccount to get the current address for the wallet connected which we’ll using in our yet to be made minting function, and a ConnectButton for our users to connect their wallet. We’ll take our useState and setup a bunch of different states for field forms and files, and create functions to handle the changes in the form. We’ll make a minting function which we’ll fill out later, but we’ll go ahead and add in some variables we will reassign during use.</p><p>In the JSX we’re going to have some conditional logic where the user will first see a connect wallet button. We also will show the form by default while the user is connected, and change that state once we are loading and completing our minting down the road. We also have a dynamic message that will let the user know the status of the minting process, from uploading to minting to completed.</p><p>For this project’s functions that involve secrets, we’re going to use the Next.js API routes and run serverless functions so we don’t have to expose anything in the client. There is one small problem though, there is a file limit size of what can be passed through those routes of 4MB which is pretty limiting for people wanting to mint an NFT. Thankfully with Pinata, we can create a temporary API key using our primary API key which will be scoped to two uses and then expire. This way we can do a client side upload for the benefits there, and not worry about exposing our used up key.</p><p>To accomplish this we’re going to create a new file under the /api/ route called key.js and delete the default hello.js file that came with the template. In that file we’ll past the following code:</p><pre>//key.js<br>import { v4 as uuidv4 } from &quot;uuid&quot;;<br>const pinataJWT = process.env.PINATA_JWT;<br>export default async function handler(req, res) {<br>  if (req.method === &quot;GET&quot;) {<br>    try {<br>      const uuid = uuidv4();<br>      const body = JSON.stringify({<br>        keyName: uuid.toString(),<br>        permissions: {<br>          endpoints: {<br>            pinning: {<br>              pinFileToIPFS: true,<br>              pinJSONToIPFS: true,<br>            }<br>          }<br>        },<br>        maxUses: 2,<br>      });<br>      const keyRes = await fetch(<br>        &quot;&lt;https://api.pinata.cloud/users/generateApiKey&gt;&quot;,<br>        {<br>          method: &quot;POST&quot;,<br>          body: body,<br>          headers: {<br>            accept: &quot;application/json&quot;,<br>            &quot;content-type&quot;: &quot;application/json&quot;,<br>            authorization: `Bearer ${pinataJWT}`,<br>          },<br>        }<br>      );<br>      const keyResJson = await keyRes.json();<br>   const keyData = {<br>    pinata_api_key: keyResJson.pinata_api_key,<br>    JWT: keyResJson.JWT<br>   }<br>      return res.send(keyData);<br>    } catch (error) {<br>      console.log(error.message);<br>      res.status(500).json({ text: &quot;Error creating API Key&quot;, error: error });<br>    }<br>  } else if (req.method === &quot;PUT&quot;) {<br>    try {<br>   const body = JSON.stringify(req.body)<br>      const keyDelete = await fetch(<br>        &quot;&lt;https://api.pinata.cloud/users/revokeApiKey&gt;&quot;,<br>        {<br>          method: &quot;PUT&quot;,<br>          body: body,<br>          headers: {<br>            accept: &quot;application/json&quot;,<br>            &quot;content-type&quot;: &quot;application/json&quot;,<br>            authorization: `Bearer ${pinataJWT}`,<br>          },<br>        }<br>      );<br>      const keyDeleteRes = await keyDelete.json();<br>      return res.send(keyDeleteRes);<br>    } catch (error) {<br>      console.log(error.message);<br>      res.status(500).json({ text: &quot;Error deleting API Key&quot;, error: error });<br>    }<br>  }<br>}</pre><p>Our serverless function is going to have two methods, GET and PUT. If we use GET from the client side we’ll get a key, and if we use PUT we’ll delete the key just to keep things tidy in our Pinata account. At the top we’ll import UUID just to keep the key names unique, and we’ll import our primary Pinata API key that we don’t want to leak to the client. With this key we’ll make our temporary keys.</p><p>The GET method will be pretty simple, we’ll create uuid , then make a JSON body payload with the keyName using that uuid, give it just the two endpoints we need, then make the maxUses 2 which is all we’ll need for our uploading. Then we’ll make an API request to https://api.pinata.cloud/users/generateApiKey and send the client our result.</p><p>The PUT method will accept the client request body containing the API key to delete then call https://api.pinata.cloud/users/revokeApiKey. That’s it!</p><p>Back in our Form.js file we’ll go into the handleSubmission function and make a request to our /api/key endpoint to get our temporary Pinata JWT. We’ll also start the loading sequence with setIsLoading.</p><pre>//Form.js<br>const handleSubmission = async () =&gt; {<br>  let key;<br>  let keyId;<br>  let fileCID;<br>  let uri;<br>  try {<br>    setIsLoading(true);<br>    try {<br>      const tempKey = await fetch(&quot;/api/key&quot;, {<br>        method: &quot;GET&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        },<br>      });<br>      const keyData = await tempKey.json();<br>      key = keyData.JWT;<br>      keyId = keyData.pinata_api_key;<br>    } catch (error) {<br>      console.log(&quot;error making API key:&quot;, error);<br>    }<br>  } catch (error) {<br>    console.log(error);<br>  }<br>};</pre><p>Now that we have a temporary Pinata API key, we can start uploading the NFT media and metadata. There’s <a href="https://www.pinata.cloud/blog/why-nft-metadata-should-be-hosted-on-ipfs">a lot of reasons</a> to put your NFT content on IPFS, and thankfully Pinata makes this easy. First we’ll upload the file that the user chose through the form.</p><pre>//Form.js<br>const handleSubmission = async () =&gt; {<br>  // Rest of the code<br>  try {<br>    const formData = new FormData();<br>    formData.append(&quot;file&quot;, selectedFile, { filepath: selectedFile.name });<br>    const metadata = JSON.stringify({<br>      name: `${selectedFile.name}`,<br>    });<br>    formData.append(&quot;pinataMetadata&quot;, metadata);<br>    const options = JSON.stringify({<br>      cidVersion: 0,<br>    });<br>    formData.append(&quot;pinataOptions&quot;, options);<br>    setMessage(&quot;Uploading File...&quot;);<br>    const uploadRes = await fetch(<br>      &quot;&lt;https://api.pinata.cloud/pinning/pinFileToIPFS&gt;&quot;,<br>      {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          Authorization: `Bearer ${key}`,<br>        },<br>        body: formData,<br>      }<br>    );<br>    const uploadResJson = await uploadRes.json();<br>    fileCID = uploadResJson.IpfsHash;<br>  } catch (error) {<br>    console.log(&quot;Error uploading file:&quot;, error);<br>  }<br>};</pre><p>With this function we’re doing a standard upload through the API using our temporary Pinata API key, using formData to append our file to the request and give it a name. We also have the optional pinataMetadata where we can give the file a name in our Pinata account to keep track of later, and we can specify the CID version too. After that we take the IPFS CID result from the upload and set that as fileCID to be used in our metadata function.</p><p>In the metadata function we can take advantage of Pinata’s pinJSONToIPFS endpoint which makes it easy to upload raw JSON and get a CID back; exactly what we need to mint our NFT.</p><pre>//Form.js<br>const handleSubmission = async () =&gt; {<br>  // Rest of the code<br>  try {<br>    const jsonData = JSON.stringify({<br>      name: name,<br>      description: description,<br>      image: process.env.NEXT_PUBLIC_PINATA_DEDICATED_GATEWAY + fileCID,<br>      external_url: externalURL,<br>    });<br>    setMessage(&quot;Uploading Metadata...&quot;);<br>    const jsonRes = await fetch(<br>      &quot;&lt;https://api.pinata.cloud/pinning/pinJSONToIPFS&gt;&quot;,<br>      {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>          Authorization: `Bearer ${key}`,<br>        },<br>        body: jsonData,<br>      }<br>    );<br>    const jsonResData = await jsonRes.json();<br>    uri = jsonResData.IpfsHash;<br>  } catch (error) {<br>    console.log(&quot;Error uploading metadata:&quot;, error);<br>  }<br>};</pre><p>Here we are building the NFT metadata which will be passed as the Token URI when the minting happens; this is all the information regarding the NFT. With our state variables we can just pass in the name, description, and externalURL. For the image we’ll process the Dedicated Gateway URL from our env.local file and append the fileCID we just got earlier. Once the file is uploaded we’ll take resulting CID for the metadata and assign it to uri.</p><p>Now the fun part: minting! Like we said earlier we will be using Crossmint for this part, and because we don’t have to do any major uploads we can run the minting function on the server side with our api routes. Go ahead and create a file called mint.js in the /api/ folder and paste in the following:</p><pre>// mint.js<br>const delay = (ms) =&gt; new Promise((resolve) =&gt; setTimeout(resolve, ms));<br>export default async function handler(req, res) {<br>  try {<br>    const data = JSON.stringify({<br>      recipient: `base:${req.body.address}`,<br>      metadata: req.body.uri,<br>    });<br>    const mintRes = await fetch(<br>      `https://www.crossmint.com/api/2022-06-09/collections/${process.env.CROSSMINT_COLLECTION_ID}/nfts`,<br>      {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          accept: &quot;application/json&quot;,<br>          &quot;content-type&quot;: &quot;application/json&quot;,<br>          &quot;x-client-secret&quot;: `${process.env.CROSSMINT_CLIENT_SECRET}`,<br>          &quot;x-project-id&quot;: `${process.env.CROSSMINT_PROJECT_ID}`,<br>        },<br>        body: data,<br>      }<br>    );<br>    const mintResJson = await mintRes.json();<br>    if (mintResJson.onChain.status === &quot;pending&quot;) {<br>      while (true) {<br>        await delay(5000);<br>        const mintStatus = await fetch(<br>          `https://www.crossmint.com/api/2022-06-09/collections/${process.env.CROSSMINT_COLLECTION_ID}/nfts/${mintResJson.id}`,<br>          {<br>            method: &quot;GET&quot;,<br>            headers: {<br>              accept: &quot;application/json&quot;,<br>              &quot;x-client-secret&quot;: `${process.env.CROSSMINT_CLIENT_SECRET}`,<br>              &quot;x-project-id&quot;: `${process.env.CROSSMINT_PROJECT_ID}`,<br>            },<br>          }<br>        );<br>        const mintStatusJson = await mintStatus.json();<br>        if (mintStatusJson.onChain.status === &quot;success&quot;) {<br>          console.log(mintStatusJson);<br>          res.status(200).json(mintStatusJson);<br>          return;<br>        }<br>      }<br>    }<br>  } catch (error) {<br>    console.log(error);<br>    res.status(500).json({ text: &quot;Error minting NFT&quot;, error: error });<br>  }<br>}</pre><p>Let’s break down everything that’s happening here. First we’ll make a simple delay() function that will let us pause between running code (we’ll get to why in a second). Next we’ll have the actual API minting function run which is gonna do a few things.</p><p>First we’ll make a JSON payload with the recipient (our user with their wallet address) and the token URI that we just made earlier. Then we’ll send that data off to Crossmint in our secure serverless backend, then wait for the data. Crossmint will send a response before the NFT is actually finished minting, so we’ll do something fun here. If onChain.status === &quot;pending&quot; we’ll run a while loop as long as that status is true. In that loop we’ll make a quick delay of 5seconds, and then check again if the NFT is done minting. If it is, then we’ll send the full info about the NFT back to our client. We don’t necessarily have to do this because you can use the smart contract address, but if we do this then we can return the token ID for the NFT and give the end user a better UX. You’ll see in a bit 😁 Now we can go back to our main minting function on the client side and make the request to our new api route.</p><pre>//Form.js<br><br>const handleSubmission = async () =&gt; {<br>  // Rest of the code<br>  try {<br>    const mintBody = JSON.stringify({<br>      address: address,<br>      uri: process.env.NEXT_PUBLIC_PINATA_DEDICATED_GATEWAY + uri,<br>    });<br>    setMessage(&quot;Minting NFT...&quot;);<br>    const mintRes = await fetch(&quot;/api/mint&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      },<br>      body: mintBody,<br>    });<br>    const mintResData = await mintRes.json();<br>    setOsLink(<br>      `https://opensea.io/assets/base/${mintResData.onChain.contractAddress}/${mintResData.onChain.tokenId}`<br>    );<br>  } catch (error) {<br>    console.log(&quot;Error minting NFT:&quot;, error);<br>  }<br>};</pre><p>Most of the hard work is being done on the server side, so all we have to do is pass our wallet address, and the token URI link using the Pinata Dedicated Gateway plus our uri variable. From there we just make the request, get the result back, and from there build an OpenSea URL that we can give to the user and they can view their NFT.</p><p>After we have everything together it should look something like this:</p><pre>import { useState } from &#39;react&#39;<br>import { useAccount } from &#39;wagmi&#39;<br>import { ConnectButton } from &#39;@rainbow-me/rainbowkit&#39;;<br><br>const Form = () =&gt; {<br>  const [selectedFile, setSelectedFile] = useState()<br>  const [name, setName] = useState()<br>  const [description, setDescription] = useState()<br>  const [externalURL, setExternalURL] = useState()<br>  const [osLink, setOsLink] = useState(&quot;https://opensea.io&quot;)<br>  const [isLoading, setIsLoading] = useState(false)<br>  const [message, setMessage] = useState(&quot;&quot;)<br>  const [isComplete, setIsComplete] = useState(false)<br>  const { address } = useAccount()<br>  const fileChangeHandler = (event) =&gt; {<br>    setSelectedFile(event.target.files[0])<br>  }<br>  const nameChangeHandler = (event) =&gt; {<br>    setName(event.target.value)<br>  }<br>  const descriptionChangeHandler = (event) =&gt; {<br>    setDescription(event.target.value)<br>  }<br>  const externalURLChangeHandler = (event) =&gt; {<br>    setExternalURL(event.target.value)<br>  }<br>  const handleSubmission = async () =&gt; {<br>    let key;<br>    let keyId;<br>    let fileCID;<br>    let uri<br>    try {<br>      setIsLoading(true)<br>      try {<br>        const tempKey = await fetch(&quot;/api/key&quot;, {<br>          method: &#39;GET&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;<br>          }<br>        })<br>        const tempKeyJson = await tempKey.json()<br>        key = tempKeyJson.JWT<br>        keyId = tempKeyJson.pinata_api_key<br>      } catch (error) {<br>        console.log(&quot;error making API key:&quot;, error)<br>      }<br>      try {<br>        const formData = new FormData()<br>        formData.append(&#39;file&#39;, selectedFile, { filepath: selectedFile.name })<br>        const metadata = JSON.stringify({<br>          name: `${selectedFile.name}`,<br>        })<br>        formData.append(&#39;pinataMetadata&#39;, metadata)<br>        const options = JSON.stringify({<br>          cidVersion: 0,<br>        })<br>        formData.append(&#39;pinataOptions&#39;, options)<br>        setMessage(&quot;Uploading File...&quot;)<br>        const uploadRes = await fetch(&#39;&lt;https://api.pinata.cloud/pinning/pinFileToIPFS&gt;&#39;, {<br>          method: &#39;POST&#39;,<br>          headers: {<br>            Authorization: `Bearer ${key}`,<br>          },<br>          body: formData<br>        })<br>        const uploadResJson = await uploadRes.json()<br>        fileCID = uploadResJson.IpfsHash<br>      } catch (error) {<br>        console.log(&quot;Error uploading file:&quot;, error)<br>      }<br>      try {<br>        const jsonData = JSON.stringify({<br>          name: name,<br>          description: description,<br>          image: process.env.NEXT_PUBLIC_PINATA_DEDICATED_GATEWAY + fileCID,<br>          external_url: externalURL<br>        })<br>        setMessage(&quot;Uploading Metadata...&quot;)<br>        const jsonRes = await fetch(&quot;&lt;https://api.pinata.cloud/pinning/pinJSONToIPFS&gt;&quot;, {<br>          method: &#39;POST&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            Authorization: `Bearer ${key}`,<br>          },<br>          body: jsonData<br>        })<br>        const jsonResData = await jsonRes.json()<br>        uri = jsonResData.IpfsHash<br>      } catch (error) {<br>        console.log(&quot;Error uploading metadata:&quot;, error)<br>      }<br>      try {<br>        const mintBody = JSON.stringify({<br>          address: address,<br>          uri: process.env.NEXT_PUBLIC_PINATA_DEDICATED_GATEWAY + uri,<br>        })<br>        setMessage(&quot;Minting NFT...&quot;)<br>        const mintRes = await fetch(&quot;/api/mint&quot;, {<br>          method: &#39;POST&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>          },<br>          body: mintBody<br>        })<br>        const mintResData = await mintRes.json()<br>        setOsLink(`https://opensea.io/assets/base/${mintResData.onChain.contractAddress}/${mintResData.onChain.tokenId}`)<br>      } catch (error) {<br>        console.log(&quot;Error minting NFT:&quot;, error)<br>      }<br>      try {<br>        const deleteData = JSON.stringify({<br>          apiKey: keyId,<br>        })<br>        const deleteKey = await fetch(&quot;/api/key&quot;, {<br>          method: &#39;PUT&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>          },<br>          body: deleteData<br>        })<br>      } catch (error) {<br>        console.log(&quot;Error deleting API key:&quot;, error)<br>      }<br>      setMessage(&quot;Minting Complete!&quot;)<br>      setIsLoading(false)<br>      setIsComplete(true)<br>    } catch (error) {<br>      console.log(error)<br>      setIsLoading(false)<br>      setIsComplete(false)<br>      alert(&quot;Error Minting NFT&quot;)<br>    }<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;<br>        &lt;ConnectButton /&gt;<br>      &lt;/div&gt;<br>      {!isLoading &amp;&amp; !isComplete &amp;&amp; (<br>        &lt;&gt;<br>          &lt;label onChange={fileChangeHandler} htmlFor=&quot;file&quot;&gt;<br>            &lt;input name=&quot;&quot; type=&quot;file&quot; id=&quot;file&quot; hidden /&gt;<br>            &lt;p&gt;{!selectedFile ? &quot;Select File&quot; : `${selectedFile.name}`}&lt;/p&gt;<br>          &lt;/label&gt;<br>          &lt;label&gt;Name&lt;/label&gt;<br>          &lt;input type=&#39;text&#39; placeholder=&#39;Cool NFT&#39; onChange={nameChangeHandler} /&gt;<br>          &lt;label&gt;Description&lt;/label&gt;<br>          &lt;input<br>            type=&#39;text&#39;<br>            placeholder=&#39;This NFT is just so cool&#39;<br>            onChange={descriptionChangeHandler}<br>          /&gt;<br>          &lt;label&gt;Your Website&lt;/label&gt;<br>          &lt;input<br>            type=&#39;text&#39;<br>            placeholder=&#39;&lt;https://pinata.cloud&gt;&#39;<br>            onChange={externalURLChangeHandler}<br>          /&gt;<br>          &lt;button onClick={handleSubmission}&gt;Submit&lt;/button&gt;<br>        &lt;/&gt;<br>      )}<br>      {isLoading &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;h2&gt;{message}&lt;/h2&gt;<br>        &lt;/div&gt;<br>      )}<br>      {isComplete &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;h4&gt;{message}&lt;/h4&gt;<br>          &lt;a href={osLink} target=&quot;_blank&quot; className={styles.link} rel=&quot;noreferrer&quot;&gt;&lt;h3&gt;Link to NFT&lt;/h3&gt;&lt;/a&gt;<br>          &lt;button onClick={() =&gt; setIsComplete(false)} className={styles.logout}&gt;Mint Another NFT&lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  )<br>}<br>export default Form</pre><pre>And there you have it! From there you can add styles to make it more branded to your taste, or add some loading indicators for when you’re showing the isLoading state. I got one more treat for ya: run npm install canvas-confetti and add confetti.js to your src directory. Paste this code in that file:</pre><pre>// confetti.js<br>import confetti from &quot;canvas-confetti&quot;<br>var count = 200;<br>var defaults = {<br>  origin: { y: 0.7 }<br>};<br>const fireConfetti = () =&gt; {<br>function fire(particleRatio, opts) {<br>  confetti(Object.assign({}, defaults, opts, {<br>    particleCount: Math.floor(count * particleRatio)<br>  }));<br>}<br>fire(0.25, {<br>  spread: 26,<br>  startVelocity: 55,<br>});<br>fire(0.2, {<br>  spread: 60,<br>});<br>fire(0.35, {<br>  spread: 100,<br>  decay: 0.91,<br>  scalar: 0.8<br>});<br>fire(0.1, {<br>  spread: 120,<br>  startVelocity: 25,<br>  decay: 0.92,<br>  scalar: 1.2<br>});<br>fire(0.1, {<br>  spread: 120,<br>  startVelocity: 45,<br>});<br>}<br>export default fireConfetti</pre><p>Now back in Form.js you can import it and fire after minting is complete!</p><pre>// Form.js<br>//other imports<br>import fireConfetti from &quot;../../utils/confetti&quot;;<br>// other code<br>const handleSubmission = async () =&gt; {<br>  // other code, skip to the minting completion<br>  setMessage(&quot;Minting Complete!&quot;);<br>  setIsLoading(false);<br>  setIsComplete(true);<br>  fireConfetti();<br>};</pre><p>In the end you should see this when you complete the minting!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSOk3ZFjg1cxfW61c320Iw.gif" /></figure><p>You did it! A fully functional Base minting app using Pinata and Crossmint. For your convenience we have also made this a starter template which you can find <a href="https://github.com/PinataCloud/pinata-nft-minting-app-template">here</a>. This is just the beginning of what you can do with Web3, Next.js, and Pinata. Check out our other templates and SDK <a href="https://docs.pinata.cloud/docs/sdks">here</a>, and we can’t wait to see what you build!</p><p>Happy Pinning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a97b7a91797d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pinata/how-to-create-an-nft-minting-app-on-base-with-crossmint-and-pinata-a97b7a91797d">How to Create an NFT Minting App on Base with Crossmint and Pinata</a> was originally published in <a href="https://medium.com/pinata">Pinata</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>