Skip to content

Instantly share code, notes, and snippets.

@scattered-code
Created June 3, 2021 19:32
Show Gist options
  • Save scattered-code/7f2b6a564f23e9b5b5b1417d6ea5c05c to your computer and use it in GitHub Desktop.
Save scattered-code/7f2b6a564f23e9b5b5b1417d6ea5c05c to your computer and use it in GitHub Desktop.
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
async function handleRequest(request) {
const { pathname, searchParams, host } = new URL(request.url);
const url = new URL(request.url)
url.hostname = "photos.example.com"
const newRequest = new Request(
url.toString(),
request
)
let response = await fetch(newRequest,
{
cf: {
// Always cache this fetch regardless of content type
cacheTtlByStatus: { "200-299": 16070400, 404: 1, "500-599": 0 }
},
});
response = new Response(response.body, response)
// Set cache control headers to cache on browser for 25 minutes
response.headers.set("Cache-Control", "public, max-age=16070400")
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment