@@ -126,65 +126,38 @@ function hostMatchesAny(host, patterns) {
126126}
127127
128128/**
129- * Try to fetch cached version from Cloudflare Cache
129+ * Try to fetch cached version from Cloudflare Cache (only called on error)
130+ * Uses the native Cloudflare cache that was populated during normal operation
130131 * @param {Request } request - Incoming request
131132 * @returns {Promise<Response|null> } Cached response or null
132133 */
133134async function tryFetchAlwaysOnlineCache ( request ) {
134135 try {
135136 console . log ( 'Trying to fetch from Cloudflare cache for:' , request . url ) ;
136137
137- // Strategy 1: Try to fetch with cache-first approach using cf options
138- try {
139- const cacheFirstResponse = await fetch ( request . url , {
140- method : 'GET' ,
141- cf : {
142- cacheEverything : true ,
143- cacheTtl : 86400 , // 1 day
144- cacheKey : request . url
145- }
146- } ) ;
147-
148- // If we get a valid response (even from cache), use it
149- if ( cacheFirstResponse && cacheFirstResponse . ok ) {
150- const headers = new Headers ( cacheFirstResponse . headers ) ;
151- headers . set ( 'X-Served-From-Cache' , 'cloudflare-cache-strategy-1' ) ;
152- headers . set ( 'X-Worker-Handled' , 'true' ) ;
153-
154- console . log ( 'Cache hit from strategy 1' ) ;
155- return new Response ( cacheFirstResponse . body , {
156- status : 200 ,
157- statusText : 'OK' ,
158- headers : headers
159- } ) ;
160- }
161- } catch ( fetchErr ) {
162- console . log ( 'Strategy 1 failed, trying strategy 2' ) ;
163- }
164-
165- // Strategy 2: Try to get from Workers Cache API
138+ // Try to access Cloudflare's cache directly via Cache API
139+ // This will use the cache that Cloudflare populates automatically
166140 const cache = caches . default ;
167141 const cacheKey = new Request ( request . url , {
168- method : 'GET' ,
169- headers : request . headers
142+ method : 'GET'
170143 } ) ;
171144
172145 const cachedResponse = await cache . match ( cacheKey ) ;
173146
174- if ( cachedResponse && cachedResponse . ok ) {
147+ if ( cachedResponse ) {
175148 const headers = new Headers ( cachedResponse . headers ) ;
176- headers . set ( 'X-Served-From-Cache' , 'cloudflare-cache-strategy-2 ' ) ;
149+ headers . set ( 'X-Served-From-Cache' , 'cloudflare-always-online ' ) ;
177150 headers . set ( 'X-Worker-Handled' , 'true' ) ;
178151
179- console . log ( 'Cache hit from strategy 2 ' ) ;
152+ console . log ( 'Cache hit! Serving cached version ' ) ;
180153 return new Response ( cachedResponse . body , {
181154 status : 200 ,
182155 statusText : 'OK' ,
183156 headers : headers
184157 } ) ;
185158 }
186159
187- console . log ( 'No cache found' ) ;
160+ console . log ( 'No cache found for this URL ' ) ;
188161 } catch ( err ) {
189162 console . error ( 'Always Online cache fetch failed:' , err ) ;
190163 }
0 commit comments