Uploading files
Learn how to upload files in your supastarter application.
Before you start uploading files, make sure to setup your storage.
You also want to make sure that you have the bucket created that you want to upload files to.
For this example we are going to upload a PDF file to a bucket called documents
, that we assume you have already created in your storage provider.
Make sure to disable public access to all your buckets as we will care about access control in the API layer of the application.
Add the bucket name to the config
For easy reusability, we recommend adding the bucket name to the config.ts
file.
This also allows you to use a dynamic value by using an environment variable instead of a static value.
Prepare upload endpoint
As explained on the overview page, supastarter uses the presigned URLs to upload files to your storage provider.
So what we need to do first is to extend the api/signed-upload-url
API route to be able to upload files to the documents
bucket.
This route will now allow authenticated users to get a signed upload URL for the documents
bucket. Be careful though, as this will allow anyone to write any path to the documents
bucket.
If you want to only allow uploading to specific paths or check for specifc file types, you can add a check for the path or file type:
Allow public uploads
In general, we don't recommend allowing public uploads as this can lead to security issues or spam to your storage provider.
However, if you want to allow public uploads, you can create a new route that doesn't require authentication.
Upload files from the UI
In order to upload files from the UI, use your preferred method to select a file (like a file input or a dropzone component). Then you need to execute the following steps:
- Get a signed upload URL for the file you want to upload.
- Upload the file to the signed URL.
- Store the file url to your database to be able to use the file later
Here is an example of how you can upload a file from the UI:
Now your users can use the upload component to upload files to the documents
bucket.
In the next step you can learn how to access the uploaded files.