/firebase-tutorials

How to get public URL of Firebase storage file?

Easily get the public URL of a Firebase Storage file. Follow our clear guide on setting up, uploading files, retrieving URLs, and adjusting security rules.

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 get public URL of Firebase storage file?

 

Step 1: Set Up Firebase in Your Project

 

To work with Firebase Storage and get the public URL of a file, you first need to set up Firebase in your project. Follow these steps:

  • Go to the Firebase Console.
  • Click on "Add Project" and follow the prompts to create a new project or select an existing project.
  • Once your project is ready, click on "Add app" to add a web app to your Firebase project. This will help in getting the Firebase configuration for your web application.
  • After registering your app, you'll be presented with Firebase SDK configuration, which looks like this:
 
// Your web app's Firebase configuration
const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    databaseURL: "https://YOUR_PROJECT_ID.firebaseio.com",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_PROJECT_ID.appspot.com",
    messagingSenderId: "YOUR_MESSAGING_SENDER\_ID",
    appId: "YOUR_APP_ID",
    measurementId: "YOUR_MEASUREMENT_ID"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

Ensure you replace the placeholders with your actual project details. Include this in your HTML file to initialize Firebase.

 

Step 2: Upload the File to Firebase Storage

 

After Firebase setup, the next step is to upload a file to Firebase Storage.

Add the Firebase Storage script to your HTML:

<script src="https://www.gstatic.com/firebasejs/9.x.x/firebase-storage.js"></script>

Then, use the following function to upload a file:


function uploadFile(file) {
    // Create a root reference
    const storageRef = firebase.storage().ref();
    
    // Create a reference to 'your_file_name'
    const fileRef = storageRef.child('your_file_name');
    
    // 'file' comes from the Blob or File API
    fileRef.put(file).then((snapshot) => {
        console.log('Uploaded a file!');
        getPublicURL(fileRef);
    });
}

Make sure to call this function by passing the file object when you're ready to upload.

 

Step 3: Get the Public URL of the Uploaded File

 

Once the file is uploaded to Firebase Storage, you can get its public URL.

Use the following function to get the URL:


function getPublicURL(fileRef) {
    fileRef.getDownloadURL()
        .then((url) => {
            console.log('Public URL:', url);
            // You can now use this URL to access your file publicly
        })
        .catch((error) => {
            // Handle any errors
            console.error('Error getting public URL:', error);
        });
}

Call this function after the file is uploaded to get and print the public URL.

 

Step 4: Secure the File if Necessary

 

By default, files in Firebase Storage are protected, and only authenticated users can access them. If you want your files to be publicly accessible:

  • Go to Firebase Console.
  • Navigate to "Storage" and then "Rules".
  • Update the rules to allow public access:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=\*\*} {
      allow read, write: if true;
    }
  }
}

Use these rules for development purposes only, as they make your storage public. For production, consider more secure rules.

For better security practices, always consult Firebase's official documentation and tailor the rules according to your application's needs.

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