/supabase-tutorials

How to display images from Supabase storage?

Learn how to display images from Supabase Storage using JavaScript—set up your project, upload images, fetch URLs, and render them on your web page step by step.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to display images from Supabase storage?

 

Step 1: Set Up Supabase Project

 

Start by creating a new project in Supabase. Go to supabase.com, sign up, and create a new project. Once the project is set up, navigate to the Dashboard.

 

Step 2: Initialize Supabase in Your Project

 

To interact with Supabase's services, you need to install the Supabase client in your application and initialize it.

npm install @supabase/supabase-js

Import and initialize Supabase client using your project’s URL and API key (find these in your Supabase dashboard under project settings):

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

const supabaseUrl = 'https://your-project-ref.supabase.co';
const supabaseKey = 'your-anon-public-key';
const supabase = createClient(supabaseUrl, supabaseKey);

 

Step 3: Configure Storage

 

Create a new bucket in the Storage section of the Supabase dashboard. Name this bucket (e.g., "images") and adjust any permissions as necessary. Make sure to allow public access if you want images to be viewable by anyone without authentication.

 

Step 4: Upload Images to Supabase Storage

 

You can upload images using the Supabase dashboard directly or through the client.

Here’s how you can upload an image using JavaScript:

async function uploadImage(file) {
  const { data, error } = await supabase
    .storage
    .from('images')  // your bucket name
    .upload(`public/${file.name}`, file);

  if (error) {
    console.log('Error uploading image:', error.message);
  } else {
    console.log('Image uploaded successfully:', data.Key);
  }
}

Make sure you have a file input element in your HTML to select images:

<input type="file" id="fileInput">

And use this function to upload:

document.getElementById('fileInput').addEventListener('change', (event) => {
  const file = event.target.files[0];
  if (file) {
    uploadImage(file);
  }
});

 

Step 5: Fetch Image URLs from Supabase Storage

 

To display the images, you'll need to fetch their URLs. Use the getPublicUrl function provided by the Supabase client:

async function fetchImages() {
  const { data, error } = await supabase
    .storage
    .from('images')
    .list('public');

  if (error) {
    console.error('Error fetching images:', error.message);
  } else {
    const imageUrls = data.map(file => {
      const { publicURL } = supabase
        .storage
        .from('images')
        .getPublicUrl(`public/${file.name}`);
        
      return publicURL;
    });

    displayImages(imageUrls);
  }
}

 

Step 6: Display Images on Your Web Page

 

Create a function to render these images:

function displayImages(urls) {
  const imageContainer = document.getElementById('imageContainer');

  urls.forEach(url => {
    const img = document.createElement('img');
    img.src = url;
    img.alt = 'Supabase Image';
    img.style.width = '200px';
    img.style.height = 'auto';
    imageContainer.appendChild(img);
  });
}

Make sure you have a div where images will be appended:

<div id="imageContainer"></div>

Finally, call fetchImages() to display images on page load or any expected event:

fetchImages();

 

Step 7: Test and Debug

 

Ensure all credentials, project settings, and endpoints are correctly configured. Verify image URLs to check for permissions and path accuracy. Debug any issues with browser developer tools.

 

This completes displaying images from Supabase storage on your web page. Adjust styles and functionality according to your requirements.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022