Home > other >  Why asynchronous function "getDownloadURL" are used to get file URLs in Firebase Storage
Why asynchronous function "getDownloadURL" are used to get file URLs in Firebase Storage

Time:10-31

In order to get the URL of a file uploaded to Cloud Storage, we have to write a code like the following.

import { getStorage, ref } from 'firebase/storage'

const storage = ref(getStorage(firebaseApp))
const url = await getDownloadURL(ref(storage, 'images/sample.jpg'))

Why do we need to call an asynchronous function instead of knowing the URL of a unique file from the beginning?
I guess the authentication is done when you call "getDownloadURL".
However, if authentication is necessary, why not issue a unique URL for the file, and then perform authentication when the URL is called?

CodePudding user response:

I am going to assume that you're using Firebase for the Web. It should be the same for other platforms.

Seems that it's asynchronous as it needs a network request in order to get the download URL, and as you said, it performs authentication as well (via Storage Rules).

However, if authentication is necessary, why not issue a unique URL for the file, and then perform authentication when the URL is called?

My assumption: Imagine you call 1000 images and when they're going to render, it fails as the user is not authenticated. Of course this is not a good user experience - it's better to fail during the request so you can show some feedback that the request fails to the user, maybe by using alert, modal, or anything of the like.

References:

CodePudding user response:

Why do we need to call an asynchronous function instead of knowing the URL of a unique file from the beginning?

It's because the download URL is generated on the server. This URL becomes available as soon as the data is successfully uploaded to Firebase Storage. It's an asynchronous operation, as it takes time to actually upload the data to the server. Depending on the connection speed and the state, and the size of the data, it may take from a few hundred milliseconds to a few seconds to finish the upload. Besides that, the URL contains a token, which is automatically created whenever a file is uploaded to Cloud Storage. It's a random token, which makes the URL hard to guess.

That's the reason why you cannot know the final download URL ahead of time. That's not the same as pushing an ID in the Realtime Database or generating a document ID in Firestore, where both operations take place on the client.

  • Related