Now that you know how to upload and download files with Supabase Storage, let's tackle the crucial task of deleting them. Whether you need to clean up old user avatars, remove temporary files, or manage your storage space, deleting files is a straightforward process. We'll explore how to do this programmatically using the Supabase JavaScript client.
Supabase provides a dedicated method for deleting files: storage.from('<your-bucket-name>').remove(['<path/to/your/file.ext>']). This method takes an array of file paths as an argument, allowing you to delete multiple files in a single operation if needed. It's important to specify the exact path to the file within your bucket.
import { createClient } from '@supabase/supabase-js'
const supabaseUrl = 'YOUR_SUPABASE_URL'
const supabaseKey = 'YOUR_SUPABASE_ANON_KEY'
const supabase = createClient(supabaseUrl, supabaseKey)
async function deleteMyFile() {
const bucketName = 'avatars'
const filePath = 'public/user-123/profile.jpg'
const { data, error } = await supabase
.storage
.from(bucketName)
.remove([filePath])
if (error) {
console.error('Error deleting file:', error.message)
} else {
console.log('File deleted successfully:', data)
}
}
deleteMyFile()The remove method returns an object containing data and error properties, similar to other Supabase operations. If the deletion is successful, data will contain an empty array, indicating that the operation was performed without returning specific file information (as the files are, well, gone!). The error object will contain details if something went wrong.
Permissions are key here. Ensure that the authenticated user or service role has the necessary permissions to delete files from the specified bucket. You can manage these permissions within the Supabase Storage UI.
graph TD
A[Client Application] --> B{Call supabase.storage.from().remove()}
B --> C{Supabase Storage API}
C --> D{Check Permissions}
D -- Authorized --> E[Delete File]
D -- Unauthorized --> F[Return Error]
E --> G[Return Success Data]
F --> G
Deleting files is a permanent action, so always double-check the file paths before executing the remove operation. Consider implementing confirmation prompts in your user interface to prevent accidental deletions.