Published on

How to check if File Exists in Supabase Storage in Nodejs

Authors

Supabase provides an easy-to-use SDK to upload and download files. Previously we've talked about how to upload and download files

In this post, let's see a common use case, checking if a file exists

At the moment, it does not provide exists function in its SDK (and yeah, even if GPT-4 says otherwise 😅)

So we'll be using it's List all buckets and filtering our file against it.

Here's how to do that in Node.js and a similar approach can be followed for other SDKs

npm install @supabase/supabase-js

And get the values for SUPABASE_URL and SUPABASE_PRIVATE_KEY from the Supabase dashboard as well.

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

const SUPABASE_URL = process.env.SUPABASE_URL;
const SUPABASE_PRIVATE_KEY = process.env.SUPABASE_PRIVATE_KEY;

const supabaseAdmin = createClient(SUPABASE_URL, SUPABASE_PRIVATE_KEY);

export default supabaseAdmin;
import supabaseAdmin from './supabaseAdminClient';

const checkFileExists = async (bucketName, filePath) => {
  const { data, error } = await supabaseAdmin.storage
    .from(bucketName)
    .list(filePath)

  if (error) {
    console.error(error)
    return false
  }

  const files = data.filter(item => item.name === filePath)
  return files.length > 0
};


const bucketName = 'YourBucketName';
const filePath = 'path/to/file.pdf'; // in your Supabase bucket
const fileExists = await checkFileExists(bucketName, filePath)
console.log(fileExists) // true or false

Happy filtering files!