Replies: 2 comments
-
I actually got a suggestion to use middleware for this, seems to work well! Although the Cloudflare types (Response, Request, fetch) that
import { defineMiddleware } from 'astro:middleware';
import { parse } from 'cache-control-parser';
export const onRequest = defineMiddleware(async (ctx, next) => {
try {
const cache = ctx.locals.runtime.caches.default;
const cachedResponse = (await cache.match(ctx.request as any)) as
| Response
| undefined;
if (cachedResponse) {
console.log('Cache: HIT');
if (shouldRevalidate(cachedResponse)) {
console.log('Cache: REVALIDATE');
ctx.locals.runtime.ctx.waitUntil(
next().then((response) => cache.put(ctx.request as any, response.clone() as any)),
);
}
return new Response(cachedResponse.body, cachedResponse);
}
console.log('Cache: MISS');
const response = await next();
ctx.locals.runtime.ctx.waitUntil(
cache.put(ctx.request as any, response.clone() as any),
);
return response;
} catch (ex) {
console.error(ex);
return new Response('Internal server error', { status: 500 });
}
});
function shouldRevalidate(cachedResponse: Response) {
const ageHeader = cachedResponse.headers.get('age');
const cacheControlHeader = cachedResponse.headers.get('cdn-cache-control');
if (!ageHeader || !cacheControlHeader) {
return false;
}
const staleWhileRevalidate = parse(cacheControlHeader)['stale-while-revalidate'];
if (typeof staleWhileRevalidate === 'undefined') {
return false;
}
const age = Number(ageHeader);
if (Number.isNaN(age)) {
return false;
}
return age > staleWhileRevalidate;
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
It is actually better to use a proxy worker on top of the main astro app using the service bindings described here. This is not ideal as we need two workers to be deployed and managed in a monorepo, but is not a big problem. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Body
Is it possible to set up my own worker script similar to Remix framework? I want to set up custom SWR caching, but the only option is Vite configuration with Cloudflare proxy plugin? Thx.
/worker.ts
:Beta Was this translation helpful? Give feedback.
All reactions