File tree Expand file tree Collapse file tree 2 files changed +32
-5
lines changed
packages/adapter-cloudflare/files Expand file tree Collapse file tree 2 files changed +32
-5
lines changed Original file line number Diff line number Diff line change 1+ ---
2+ ' @sveltejs/adapter-cloudflare ' : patch
3+ ---
4+
5+ Add cloudflare cache to store responses with a cache header.
Original file line number Diff line number Diff 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 }
You can’t perform that action at this time.
0 commit comments