Published on

How to download a file using Supabase Storage in Node.js

Authors

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

And here's how to download file directly

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';
import fs from 'fs/promises';


const downloadFile = async (bucketName, filePath, downloadFilePath) => {
  const { data, error } = await supabaseAdmin.storage
    .from(bucketName)
    .download(filePath);

  if (error) {
    throw error;
  }

  const buffer = Buffer.from(await data.arrayBuffer());
  await fs.writeFile(downloadFilePath, buffer);
  console.log(`File downloaded to ${downloadFilePath}`);
};


const bucketName = 'YourBucketName';
const filePath = 'path/to/file'; // in your Supabase bucket
const downloadFilePath = "/var/temp"
downloadFile(bucketName, filePath, downloadFilePath);

Happy downloading files!