Skip to content

Instantly share code, notes, and snippets.

@dustinrouillard
Created January 12, 2021 16:13
Show Gist options
  • Save dustinrouillard/f6ed1c83efa0cb233dcfc18ebb85dc3f to your computer and use it in GitHub Desktop.
Save dustinrouillard/f6ed1c83efa0cb233dcfc18ebb85dc3f to your computer and use it in GitHub Desktop.
CloudFlare worker for first available YouTube thumbnail (maxresdefault or hqdefault)
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
});
async function fetchImage(id, type = 'maxresdefault') {
const req = await fetch(`https://i.ytimg.com/vi/${id}/${type}.jpg`);
if (req.status != 200) return await fetchImage(id, 'hqdefault');
return req;
};
async function handleRequest(request) {
const url = new URL(request.url);
if (!url.pathname.split('/')[1]) {
const def = await fetch('https://img.youtube.com/vi/jNQXAC9IVRw/maxresdefault.jpg');
return new Response(def.body, def);
}
let videoId = url.pathname.split('/')[1]
if (videoId.includes('.jpg')) videoId = videoId.split('.')[0];
const image = await fetchImage(videoId);
return new Response(image.body, image);
};
@hellofaizan
Copy link

Ah got this finally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment