Skip to content

Instantly share code, notes, and snippets.

@altryne
Created November 1, 2022 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save altryne/94e8e31679b2732a8953f0769fcf655c to your computer and use it in GitHub Desktop.
Save altryne/94e8e31679b2732a8953f0769fcf655c to your computer and use it in GitHub Desktop.
Cloudflare image proxy worker to support twitter video cards
addEventListener("fetch", event => {
event.respondWith(handleRequest(event))
})
CLOUDFLARE_CUSTOMER_ID = '123123' //CHANGE THIS TO YOURS
const CF_THUMBNAIL_URL = `https://customer-${CLOUDFLARE_CUSTOMER_ID}.cloudflarestream.com/`
async function serveAsset(event) {
const url = new URL(event.request.url)
console.log('serving images', url)
/* Fix for robots.txt */
if(url.pathname == "/robots.txt"){
let body = 'User-agent: *\nDisallow:'
return new Response(body, {
status: 200}
)
}
const cache = caches.default
let response = await cache.match(event.request.url)
console.log('Checking cache')
if (!response) {
console.log('No Cache found')
const cf_thumb_url = `${CF_THUMBNAIL_URL}${url.pathname}${url.search}`
response = await fetch(cf_thumb_url, { headers: event.request.headers })
// Cache for however long, here is 4 hours.
const headers = new Headers(response.headers);
headers.set("cache-control", `public, max-age=14400`);
headers.set("vary", "Accept");
response = new Response(response.body, { ...response, headers })
event.waitUntil(cache.put(event.request, response.clone()))
}else{
console.log('Found image in cache, serving')
}
return response
}
async function handleRequest(event) {
console.log('Requesting the image')
if (event.request.method === "GET") {
let response = await serveAsset(event)
if (response.status > 399) {
response = new Response(response.statusText, { status: response.status })
}
return response
} else {
return new Response("Method not allowed", { status: 405 })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment