Skip to content

Commit 08bb98c

Browse files
authored
Add cloudflare cache (#4412)
1 parent eebe928 commit 08bb98c

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@sveltejs/adapter-cloudflare': patch
3+
---
4+
5+
Add cloudflare cache to store responses with a cache header.

packages/adapter-cloudflare/files/worker.js

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,34 @@ export default {
5050

5151
// dynamically-generated pages
5252
try {
53-
return await server.respond(req, {
54-
platform: { env, context },
55-
getClientAddress() {
56-
return req.headers.get('cf-connecting-ip');
53+
// @ts-expect-error - `default` exists only in the cloudflare workers environment
54+
const cache = caches.default;
55+
let response = await cache.match(req);
56+
57+
if (!response) {
58+
response = await server.respond(req, {
59+
platform: { env, context },
60+
getClientAddress() {
61+
return req.headers.get('cf-connecting-ip');
62+
}
63+
});
64+
65+
// Use waitUntil so you can return the response without blocking on
66+
// writing to cache
67+
try {
68+
// If cookies are being set, ensure we dont cache the page.
69+
if (response.headers.has('Set-Cookie')) {
70+
response = new Response(response.body, response);
71+
response.headers.append('Cache-Control', 'private=Set-Cookie');
72+
}
73+
74+
context.waitUntil(cache.put(req, response.clone()));
75+
} catch {
76+
// noop
5777
}
58-
});
78+
}
79+
80+
return response;
5981
} catch (e) {
6082
return new Response('Error rendering route: ' + (e.message || e.toString()), { status: 500 });
6183
}

0 commit comments

Comments
 (0)