How to know if a public url doesn't exist?

Im trying to fetch a user's avatar from the public bucket. I wish to know whether the URL is valid or not so that I could use a default URL in case url is invalid. How to achieve this?
export const fetchAvatarUrl = async (userId: string) => {
const { data } = await supabase.storage
.from('profile_pictures')
.getPublicUrl(`${userId}`)

console.log("avatar url:", data.publicUrl)
}
export const fetchAvatarUrl = async (userId: string) => {
const { data } = await supabase.storage
.from('profile_pictures')
.getPublicUrl(`${userId}`)

console.log("avatar url:", data.publicUrl)
}
2 Replies
garyaustin
garyaustin2y ago
You have to write a postgres function to check the storage.objects table for the path. Then call that with an rpc call. getPublicUrl is just a helper and does not call the storage server.
pandas
pandas2y ago
export const fetchAvatarUrl = async (userId: string) => {
const { data } = await supabase.storage
.from('profile_pictures')
.getPublicUrl(`${userId}`)

let avatarUrl = data.publicUrl;

// Check if the URL is valid
const response = await fetch(avatarUrl);
if (!response.ok) {
// If the URL is not valid, use a default URL
avatarUrl = 'default_url';
}

console.log("avatar url:", avatarUrl)
}
export const fetchAvatarUrl = async (userId: string) => {
const { data } = await supabase.storage
.from('profile_pictures')
.getPublicUrl(`${userId}`)

let avatarUrl = data.publicUrl;

// Check if the URL is valid
const response = await fetch(avatarUrl);
if (!response.ok) {
// If the URL is not valid, use a default URL
avatarUrl = 'default_url';
}

console.log("avatar url:", avatarUrl)
}
try to fetch image see if actually exists such as bytes or what response is from server another simple thing to do is save avatar as avatar-userId.png and build url from that

Did you find this page helpful?