DEV Community

Cover image for Upload media to Supabase from remote URL with nodejs
Antoine Mesnil
Antoine Mesnil

Posted on

Upload media to Supabase from remote URL with nodejs

Introduction

Recently I had to upload images in bulk to Supabase but I was kind of rusty on my nodejs and lost some time so I thought I would share the simple result to spare time for others.


Supabase setup

The first step is to create your bucket on supabase, make it public or make sure to create policies to have the right access.

Image description

You can also get your service_role API key to bypass any RLS policies at this URL (do not share or display in public):
https://app.supabase.com/project/{YOUR_PROJECT_ID}/settings/api


Script setup

To init your project we are going to need npm or yarn and run those two commands

npm init
npm install @supabase/supabase-js node-fetch@2
Enter fullscreen mode Exit fullscreen mode

It will create a package.json and install the necessary dependencies. Now you can create your script.js file and run

node script.js
Enter fullscreen mode Exit fullscreen mode

If you wish to use typescript you can also do

npx ts-node script.ts
Enter fullscreen mode Exit fullscreen mode

Script

import fetch from "node-fetch"
import { createClient } from '@supabase/supabase-js'

const script = async () => {
  const options = {
    schema: 'public',
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: false,
  }

   const supabase = createClient(
    `https://${process.env.SUPABASE_PROJECT_ID}.supabase.co`,
    process.env.SUPABASE_API_KEY || '',
    options,
  )

  const url = "https://www.grapheine.com/wp-content/uploads/2015/09/nouveau-logo-google-2015.jpg"
  const blob = await fetch(url).then((r) => r.blob())
    await supabase.storage.from('my-new-bucket').upload("my-name" + '.jpg', blob)
    const { publicURL } = supabase.storage.from('covers').getPublicUrl("my-name" + '.jpg')

    //To save it in your DB
    await supabase.from('myTable').update({ logo_url: publicURL }).eq('id', the_thing_id)
}
script()
Enter fullscreen mode Exit fullscreen mode

That's it, now you can run the script and loop it for bulk upload.


πŸ˜„ Thanks for reading! If you found this article useful, want more tips and follow my journey to create my own startup studio follow me on Twitter

Top comments (0)