Skip to content

Instantly share code, notes, and snippets.

@jamesarosen
Created February 20, 2020 19:20
Show Gist options
  • Save jamesarosen/4d1fa616973e4373feb5f09fd953a6af to your computer and use it in GitHub Desktop.
Save jamesarosen/4d1fa616973e4373feb5f09fd953a6af to your computer and use it in GitHub Desktop.
Caching with Cloudflare
function isCacheable(response) {
const vary = response.headers.get('Vary')
return (
response.status >= 200 &&
response.status < 400 &&
response.status !== 206 &&
response.headers.get('Cache-Control') != null &&
vary !== '_' &&
vary !== '*'
)
}
// response.body may be a ReadableStream that can only be read once. If so,
// we can't send the same copy to the cache _and_ over the network back to the
// client.
function cloneResponse(response) {
const { body } = response
const [body1, body2] = body && typeof body.tee === 'function' ? body.tee() : [body, body]
return [new Response(body1, response), new Response(body2, response)]
}
// See https://developers.cloudflare.com/workers/reference/apis/cache/
export default async function cacheResponses(request, next) {
if (request.method !== 'GET') return next(request)
const cache = caches.default
const cachedResponse = await cache.match(request)
if (cachedResponse) return cachedResponse
const response = await next(request)
if (!isCacheable(response)) return response
const [r1, r2] = cloneResponse(response)
await caches.default.put(request, r1)
return r2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment