Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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.
26 changes: 21 additions & 5 deletions packages/adapter-cloudflare/files/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,28 @@ export default {

// dynamically-generated pages
try {
return await server.respond(req, {
platform: { env, context },
getClientAddress() {
return req.headers.get('cf-connecting-ip');
// @ts-ignore
Copy link
Member

@benmccann benmccann Mar 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use ServiceWorkerGlobalScope from @cloudflare/workers-types so that we don't have to @ts-ignore this?

If there's no solution then it should be turned into @ts-expect-error along with a comment explaining why it cannot be addressed, but I would hope that it can be

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @benmccann, I tried to add the package above but it started to throw ~30 errors in the JS files so for now I've used @ts-expect-error with a comment as to why.

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 context so you can return the response without blocking on
// writing to cache
try {
context(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