Accessing stored files
Learn how to access and download files stored in your supastarter application.
In the previous step you learned how to upload files to your storage provider. At this point, these uploaded files are not accessible to anyone including the user that uploaded them.
This behavior is by design as we want control the access to the files in the API layer of the application.
So in this step you will learn how to make these files accessible to the user(s) that should be allowed to access them.
Reminder: The uploaded files from the previous step are stored in the documents
bucket prefixed with the user's id.
Accessing the files
To access the files, you need to create a signed URL for the file.
This can either be done on demand or if you are listing your file entries from the database which should have the file path attached to them, you can already create a signed URL for each file entry.
All you need to do is to call the getSignedUrl
function from the storage
package.
In the above example, we are creating a signed URL for the file based on the filePath
which would be the value from the database entry and set the expiration to 1 hour.
The returned URL can then be used to access the file from the browser and will be valid for the duration you set.
Note: The signed URL will work for everyone that has access to the URL, so be careful with the expiration time and who you output the signed URL to.
With this you could for example create a download button in your UI that calls an API route that checks the permission of the user and creates a signed URL for the file.
Then you can fetch the signed URL form the frontend and open it to download the file.
Alternative: Create a file proxy
If you to avoid creating signed URLs each time you can create a proxy endpoint that will automatically create a signed URL for the requested file. This proxy endpoint should also include additional logic like checking if the user has access to the file or adding a cache layer.