I have one frontend only project in which I am using third party api from duckduckgo to fetch favicon for given website URL. Now whenever we try to fetch favicon for fake/non-existing hostname it return 404 error with default fallback icon. now I am unable to catch exact point when it is returning 404 error. In below code catch block never gets executed because API is always returning the fallback favicon.
export const getFaviconLink = (bookmarkLink: string) => {
try {
const linkHost = new URL(bookmarkLink).hostname;
return `https://icons.duckduckgo.com/ip3/${linkHost}.ico`;
} catch {
return "https://placehold.co/24/202124/FFF?text=>";
}
};
Above utility is being used in my code like this
<img src={getFaviconLink(link)} className={styles.favicon} />
I also tried using the fetch with Promise (code below) and tried to subscribe to external API from frontend and it is giving me CORS policy error which is expected from the third party API.
Any solutions for this? or do I have to create a could function for this?
const fetchFavicon = async () => {
try {
const linkHost = new URL(link).hostname;
const faviconUrl = `https://api.faviconkit.com/${linkHost}/64`;
const response = await fetch(faviconUrl);
if (response.ok) {
setFaviconUrl(faviconUrl);
} else {
setFaviconUrl('https://placehold.co/24/202124/FFF?text=>');
}
} catch (error) {
console.error('Network error fetching favicon:', error);
setFaviconUrl('https://placehold.co/24/202124/FFF?text=>');
}
};
Edit:
Adding code snippets for both the methods, which still does not work 1, onError in image tag: Link 2, fetch method: Link
fetchapi. What I don't get: as far as I can tell you're invoking anasyncmethod, which indicates it happens on server side, in a React Server Component. But then again, CORS shouldn't be an issue, either, b/c it's not invoked from the browser at all - at other places running requests don't care about CORS.reactjs, I didn't expect it to be possible there. At least not in the used manner.