diff --git a/.changeset/pretty-carpets-scream.md b/.changeset/pretty-carpets-scream.md new file mode 100644 index 000000000000..869f0a9b168f --- /dev/null +++ b/.changeset/pretty-carpets-scream.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/adapter-cloudflare': patch +--- + +Add cloudflare cache to store responses with a cache header. diff --git a/packages/adapter-cloudflare/files/worker.js b/packages/adapter-cloudflare/files/worker.js index caa76b852a13..8a56e6a544db 100644 --- a/packages/adapter-cloudflare/files/worker.js +++ b/packages/adapter-cloudflare/files/worker.js @@ -50,12 +50,34 @@ export default { // dynamically-generated pages try { - return await server.respond(req, { - platform: { env, context }, - getClientAddress() { - return req.headers.get('cf-connecting-ip'); + // @ts-expect-error - `default` exists only in the cloudflare workers environment + const cache = caches.default; + let response = await cache.match(req); + + if (!response) { + response = await server.respond(req, { + platform: { env, context }, + getClientAddress() { + return req.headers.get('cf-connecting-ip'); + } + }); + + // Use waitUntil so you can return the response without blocking on + // writing to cache + try { + // If cookies are being set, ensure we dont cache the page. + if (response.headers.has('Set-Cookie')) { + response = new Response(response.body, response); + response.headers.append('Cache-Control', 'private=Set-Cookie'); + } + + context.waitUntil(cache.put(req, response.clone())); + } catch { + // noop } - }); + } + + return response; } catch (e) { return new Response('Error rendering route: ' + (e.message || e.toString()), { status: 500 }); }