SvelteKit
Server-side Setup
This guide will walk you through a server side upload flow in SvelteKit
Start up SvelteKit Project
The easiest way to start building a SvelteKit app is to run npm create
After the project is created cd
into the repo and install pinata
In this demo we will be using tailwindcss
with typography plugin. Follow other CSS Framework guides respectively.
After making the project, create a .env.local
file in the root of the project and put in the following variables:
Use the JWT
from the API key creation in the previous step as well as the Gateway Domain
. The format of the Gateway domain should be mydomain.mypinata.cloud
.
Setup Pinata
Create a directory called server
in the src/lib
folder of the project and then make a file called pinata.ts
inside of it. In that file we’ll export an instance of the Files SDK that we can use throughout the rest of the app.
The use of the server
directory prevents it being used client side.
Create Client Side Form
Next we’ll want to add a form on our home page that will allow someone to select a file and upload it.
In the src/routes/+page.svelte
file take out the boiler plate code and use the following.
Lets also restrict the allowed extensions for the file. (e.g. jpg, jpeg, png, webp).
This will take a file from the client side and upload it through a form Action we are going to make next.
Create Server Action
Create a server file, src/routes/+page.server.ts
, so that we can add a form action to use.
Since this demo and page only has 1 form, we will keep the default
action.
The form action will send an API request to Pinata with the upload, then make one more request to get a signed URL we can use to see the content. Once complete, we can define the return data sent to the client.
Access the Returned value of the Form Action
We can access the returned data by exporting the form
prop on our +page.svelte
. Now, after submitting the form,
the form
prop will be updated and we can conditionally render the image we just uploaded.
And just like that we have uploaded an image to Pinata and recieved a usable URL in return! Remember that the url for the image is ephemeral, once you refresh the page the url and image will be gone.