Learn how to list files from a Supabase storage bucket using JavaScript. Follow our step-by-step guide to set up your project, initialize the client, and handle errors.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set up Supabase Project
Before listing files from a Supabase storage bucket, ensure you have a Supabase project. If you don’t have a project, create one by visiting Supabase. Once the project is set up, obtain your project URL and the anon key from your Supabase dashboard, which are necessary for authentication.
Step 2: Install Dependencies
To interact with Supabase storage using JavaScript, you need to install the Supabase JavaScript client. If you're using Node.js, create a new project directory and initialize npm.
mkdir supabase-project
cd supabase-project
npm init -y
npm install @supabase/supabase-js
Alternatively, if you're working in a web environment, include the script in your HTML file:
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js"></script>
Step 3: Initialize Supabase Client
In your JavaScript file, initialize the Supabase client using your Supabase project URL and anon key obtained from the Supabase dashboard.
import { createClient } from '@supabase/supabase-js';
// Replace 'your-supabase-url' and 'your-anon-key' with actual values
const supabaseUrl = 'your-supabase-url';
const supabaseAnonKey = 'your-anon-key';
const supabase = createClient(supabaseUrl, supabaseAnonKey);
Step 4: List Files in Supabase Storage Bucket
Once the client is initialized, you can list all files from a specific storage bucket. Replace 'your-bucket-name'
with the actual name of your bucket.
async function listFiles() {
try {
const { data, error } = await supabase
.storage
.from('your-bucket-name')
.list('');
if (error) {
console.error('Error listing files:', error.message);
return;
}
console.log('Files in the bucket:');
data.forEach(file => {
console.log(`Name: ${file.name}, Size: ${file.size} bytes, Last Modified: ${file.updated_at}`);
});
} catch (error) {
console.error('Error:', error);
}
}
listFiles();
This function fetches information on all files in the specified bucket and logs their name, size, and last modified date.
Step 5: Execute Your Code
Run your JavaScript code to execute the function and list files in the storage bucket. If using Node.js, execute it in your terminal:
node your-js-file.js
If you're using a browser environment, ensure your script is linked in an HTML file, open the HTML file in a browser, and check the console for output.
Step 6: Handle Errors
Implement error handling to manage issues such as invalid bucket names or network errors. Always check if the error
property is populated in the response and handle it accordingly in your code.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.