Skip to content

Instantly share code, notes, and snippets.

@fgregg
Created April 1, 2022 00:58
Show Gist options
  • Save fgregg/fa2a89b6c351978c06c569fcdafc7032 to your computer and use it in GitHub Desktop.
Save fgregg/fa2a89b6c351978c06c569fcdafc7032 to your computer and use it in GitHub Desktop.
Code for Cloudflare Worker to be Census API Proxy
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
async function handleRequest(event) {
let cache = caches.default
let response = await cache.match(event.request)
if (!response){
response = await subRequest(event.request)
if (response.ok) {
event.waitUntil(cache.put(event.request, response.clone()))
}
}
return response
}
async function subRequest(request) {
const url = new URL(request.url);
const params = new URLSearchParams(url.search);
params.set('key', 'YOUR_API_KEY');
const sub_response = await fetch(`https://api.census.gov${url.pathname}?${params.toString()}`)
// Recreate the response so we can modify the headers
const response = new Response(sub_response.body, sub_response)
// Append to/Add Vary header so browser will cache response correctly
response.headers.append("Vary", "Origin")
response.headers.append("Cache-Control", "s-maxage=604800");
response.headers.set('cache-control', 'public, max-age=604800')
response.headers.set("cf-cache-status", "MISS")
response.headers.delete('set-cookie');
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment