Skip to content

Commit

Permalink
Add cloudflare cache (#4412)
Browse files Browse the repository at this point in the history
  • Loading branch information
johnwalshuk authored Mar 24, 2022
1 parent eebe928 commit 08bb98c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
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

0 comments on commit 08bb98c

Please sign in to comment.