How to Upload Image Using Supabase Storage
Next.js
I was recently working on a project that has image upload as one of the core feature. Luckily I was using Supabase as a database. which provide an easy way to upload file using Supabase storage.
Set up in Supabase
To start, you must init your supabase project, then go into storage and create a new buckets.
Upload Image Function
After create a bucket, for simplicity you can set the image to
public
, then we can start upload the image by creating the functionTypescript
index
export async function uploadImage(image: File) {
const supabase = createClient();
const { data, error } = await supabase.storage
.from(`BUCKET_NAME`)
.upload(`PATH`, image, {
cacheControl: "3600",
upsert: true, //Upsert to overwrite duplicate image
});
if (error) {
return {
error: error,
};
}
const {
data: { publicUrl },
} = supabase.storage.from(`BUCKET_NAME`).getPublicUrl(data.path);
return {
publicUrl,
error,
};
}
So the function will upload the image into the specify
PATH
and BUCKET_NAME
. Sadly, supabase does not have a function that automatically return image URL after uploaded the image so we must write a function to retrieve the image URL.After that you should be able to call the function in your application
Typescript
index
const { publicUrl, error } = await uploadImage(image);
Optional: Compressed Image
Each image may take up alot of space, and consider that Supabase only give you 2GB of storage, plus to avoid Large Content Paint, it is ideal that you should compress the image before upload it to Supabase.
First, you can run
yarn add browser-image-compression
, then you can create a compress image function.Typescript
index
import imageCompression from "browser-image-compression";
export async function compressImage(image: File, options: Options) {
return await imageCompression(image, options);
}
After that, you can add this function above the
uploadImage
function.Typescript
index
const compressedImage = await compressImage(image, { maxSizeMB: 1 });
const { publicUrl, error } = await uploadImage(compressedImage);