close
close
delete from storage with supabase edge function

delete from storage with supabase edge function

3 min read 27-02-2025
delete from storage with supabase edge function

Supabase's Edge Functions provide a powerful way to extend your application's functionality without the overhead of managing servers. One particularly useful application is managing your Supabase storage, including deleting files. This article will guide you through creating an Edge Function to securely delete files from your Supabase storage. We'll cover authentication, authorization, and error handling to build a robust and reliable solution.

Setting Up Your Development Environment

Before we begin, make sure you have the following:

  • A Supabase Project: If you don't already have one, create a free account at supabase.com.
  • Supabase CLI: Install the Supabase CLI using the instructions on the Supabase documentation.
  • A Code Editor: Choose your favorite code editor (VS Code is recommended).

Creating the Edge Function

We'll create a Node.js Edge Function that uses the Supabase JavaScript client library to interact with the storage. This function will delete a file based on its path.

import { createClient } from '@supabase/supabase-js';

export default async function handler(req) {
  const { method, headers, query } = req;

  if (method !== 'DELETE') {
    return new Response('Method Not Allowed', { status: 405 });
  }

  const supabaseUrl = process.env.SUPABASE_URL;
  const supabaseAnonKey = process.env.SUPABASE_ANON_KEY;

  if (!supabaseUrl || !supabaseAnonKey) {
    return new Response('Missing environment variables', { status: 500 });
  }

  const supabase = createClient(supabaseUrl, supabaseAnonKey);

  const filePath = query.path;

  if (!filePath) {
    return new Response('Missing file path', { status: 400 });
  }


  try {
    const { data, error } = await supabase.storage.from('your-bucket-name').remove([filePath]); // Replace 'your-bucket-name'

    if (error) {
      return new Response(error.message, { status: 500 });
    }

    return new Response('File deleted successfully', { status: 200 });

  } catch (error) {
    return new Response('An unexpected error occurred', { status: 500 });
  }
}

Explanation:

  1. Import createClient: Imports the necessary Supabase client.
  2. Handle HTTP Method: Checks if the request method is DELETE. Returns a 405 error if not.
  3. Environment Variables: Retrieves Supabase URL and anon key from environment variables. Crucial for security; never hardcode these.
  4. Create Supabase Client: Initializes the Supabase client.
  5. Get File Path: Extracts the file path from the query parameters.
  6. Delete File: Uses supabase.storage.from().remove() to delete the file. Remember to replace 'your-bucket-name' with your actual bucket name.
  7. Error Handling: Includes comprehensive error handling to catch and report issues.

Deploying the Edge Function

  1. Save the Code: Save the code above as deleteFile.js.
  2. Set Environment Variables: In your Supabase project, navigate to Settings > API > Environment Variables. Add your SUPABASE_URL and SUPABASE_ANON_KEY. Consider using a service role key for enhanced security in a production environment.
  3. Deploy with the CLI: Use the Supabase CLI to deploy the function:
supabase functions deploy deleteFile.js

Testing the Edge Function

After deployment, you can test the function using a tool like curl or Postman. Here's an example using curl:

curl -X DELETE "https://<your-supabase-project-id>.supabase.co/functions/v1/deleteFile?path=path/to/your/file.txt"

Replace <your-supabase-project-id> and path/to/your/file.txt with your project ID and the file path, respectively. Ensure the file exists in your Supabase storage bucket before testing.

Adding Authentication and Authorization

For production applications, you'll want to add authentication and authorization to restrict access to this function. This prevents unauthorized deletion of files. You can achieve this by using Supabase Auth and checking the user's role or permissions within the Edge Function before proceeding with the deletion. This will require modifying the function to verify JWT tokens and implement role-based access control.

Conclusion

Supabase Edge Functions provide a streamlined and efficient way to manage your Supabase storage. This guide demonstrates how to build a secure and reliable Edge Function for deleting files. Remember to always prioritize security by using environment variables and implementing robust authentication and authorization mechanisms. Proper error handling ensures a robust user experience.

Related Posts


Latest Posts