Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/pretty-carpets-scream.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/adapter-cloudflare': patch
---

Add cloudflare cache to store responses with a cache header.
32 changes: 27 additions & 5 deletions packages/adapter-cloudflare/files/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}
Expand Down