• Documentation
  • /
  • Remix Supabase
  • /
  • Uploading data to Storage

Uploading data to Storage

To upload data to Supabase Storage, we can use the Supabase JavaScript client.

Uploading a file

To upload a file, we can use the upload method.

For example, the code below is the code that uploads a user's profile image to the avatars bucket:

async function uploadUserProfilePhoto(
  client: SupabaseClient,
  photoFile: File,
  userId: string
) {
  const bytes = await photoFile.arrayBuffer();
  const bucket = client.storage.from('avatars');
  const extension = photoFile.name.split('.').pop();
  const fileName = `${userId}.${extension}`;

  const result = await bucket.upload(fileName, bytes, {
    upsert: true,
  });

  if (!result.error) {
    return bucket.getPublicUrl(fileName).data.publicUrl;
  }

  throw result.error;
}

You can also combine the above with useMutation from react-query when you use the code above from a React component:

export function useUploadUserProfilePhotoMutation() {
  const client = useSupabase();

  return useMutation(async (file: File, userId: string) => {
    return uploadUserProfilePhoto(client, file, userId);
  });
}

And then, you can use it like this:

const updateProfilePhoto = useUploadUserProfilePhotoMutation();

<Form onUpload={(file: File, userId: string) => {
  return updateProfilePhoto.mutateAsync(file, userId)
} />

Stay informed with our latest resources for building a SaaS

Subscribe to our newsletter to receive updatesor